import { Head, useForm } from '@inertiajs/react';

import { AdminLayout } from '@/layouts/admin-layout';
import { WebhookEndpointFormView } from './create';

type EventOption = {
    value: string;
    label: string;
};

type WebhookEndpoint = {
    id: number;
    name: string;
    url: string;
    subscribed_events: string[];
    headers_json: string;
    is_active: boolean;
    max_attempts: number;
    timeout_seconds: number;
};

type WebhookEndpointForm = {
    name: string;
    url: string;
    secret: string;
    subscribed_events: string[];
    headers_json: string;
    is_active: boolean;
    max_attempts: number;
    timeout_seconds: number;
};

type WebhookEndpointEditProps = {
    endpoint: WebhookEndpoint;
    eventOptions: EventOption[];
};

export default function WebhookEndpointEdit({
    endpoint,
    eventOptions,
}: WebhookEndpointEditProps) {
    const form = useForm<WebhookEndpointForm>({
        name: endpoint.name,
        url: endpoint.url,
        secret: '',
        subscribed_events: endpoint.subscribed_events,
        headers_json: endpoint.headers_json || '',
        is_active: endpoint.is_active,
        max_attempts: endpoint.max_attempts,
        timeout_seconds: endpoint.timeout_seconds,
    });

    const submit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();

        form.transform((data) => ({
            ...data,
            secret: data.secret.trim() === '' ? null : data.secret.trim(),
            headers_json: data.headers_json.trim(),
        }));

        form.put(`/admin/webhook-endpoints/${endpoint.id}`);
    };

    return (
        <AdminLayout>
            <Head title="Edit Webhook Endpoint" />
            <WebhookEndpointFormView
                title="Edit Webhook Endpoint"
                form={form}
                eventOptions={eventOptions}
                onSubmit={submit}
                submitLabel="Update Endpoint"
                secretHelp="Leave blank to keep the current signing secret. Enter a new value to rotate it."
            />
        </AdminLayout>
    );
}
