"use client";

import React, { useRef, useState } from 'react';
import { Form, Button } from '../elements';
import { DynamicFormFields } from '../components/DynamicFormFields';
import { trackMetaLead } from '../../tracking/trackMetaLead';
import type { FormDefinition } from '../../types/api/form';

interface ContactSectionFormProps {
    /** Form fields are rendered from this definition (required). */
    formDefinition: FormDefinition | null | undefined;
    submitButtonText?: string;
    successMessage?: string;
    thankYouMessage?: string;
    onSuccess?: () => void;
}

export const ContactSectionForm = ({
    formDefinition,
    submitButtonText = "Send message",
    successMessage = "Thank you for contacting us! We'll get back to you soon.",
    thankYouMessage,
    onSuccess,
}: ContactSectionFormProps) => {
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [submitStatus, setSubmitStatus] = useState<'idle' | 'success' | 'error'>('idle');
    const [statusMessage, setStatusMessage] = useState<string>('');
    const formRef = useRef<HTMLFormElement>(null);

    if (!formDefinition || !Array.isArray(formDefinition.fields) || formDefinition.fields.length === 0) {
        return null;
    }

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setIsSubmitting(true);
        setSubmitStatus('idle');
        setStatusMessage('');

        const formData = new FormData(e.currentTarget);
        const data: Record<string, string> = { formType: 'lead' };
        formData.forEach((value, key) => {
            if (key !== 'privacy' && typeof value === 'string') data[key] = value;
        });

        try {
            const response = await fetch('/api/form', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data),
            });
            const result = await response.json();

            if (result.success) {
                setSubmitStatus('success');
                setStatusMessage(result.message || successMessage);
                formRef.current?.reset();
                onSuccess?.();
                trackMetaLead(result.eventId);
                setTimeout(() => setSubmitStatus('idle'), 5000);
            } else {
                setSubmitStatus('error');
                setStatusMessage(result.error || 'Something went wrong. Please try again.');
            }
        } catch {
            setSubmitStatus('error');
            setStatusMessage('Network error. Please try again later.');
        }
        setIsSubmitting(false);
    };

    return (
        <Form ref={formRef} onSubmit={handleSubmit} className="flex flex-col gap-8">
            <div className="flex flex-col gap-6">
                <DynamicFormFields form={formDefinition} />
            </div>
            {submitStatus === 'success' && (
                <div className="rounded-lg bg-success-50 p-4 text-success-700">
                    {thankYouMessage ?? statusMessage}
                </div>
            )}
            {submitStatus === 'error' && (
                <div className="rounded-lg bg-error-50 p-4 text-error-700">{statusMessage}</div>
            )}
            <Button
                type="submit"
                size="xl"
                isDisabled={isSubmitting}
                isLoading={isSubmitting}
            >
                {isSubmitting ? 'Sending...' : submitButtonText}
            </Button>
        </Form>
    );
};
