"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';
import { useFormDefinitions } from '../../next/contexts/form-definitions';

interface ContactSectionFormBareluxProps {
    formDefinition: FormDefinition | null | undefined;
    submitButtonText?: string;
    successMessage?: string;
    thankYouMessage?: string;
    onSuccess?: () => void;
    privacyPolicyUrl?: string;
    termsOfServiceUrl?: string;
}

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

    const hasFields =
        resolvedFormDefinition != null &&
        Array.isArray(resolvedFormDefinition.fields) &&
        resolvedFormDefinition.fields.length > 0;

    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.endsWith('_prefix')) return;
            if (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);
    };

    if (!hasFields) return null;

    return (
        <Form ref={formRef} onSubmit={handleSubmit} className="flex flex-col gap-6">
            <DynamicFormFields
                form={resolvedFormDefinition}
                privacyPolicyUrl={privacyPolicyUrl}
                termsOfServiceUrl={termsOfServiceUrl}
            />
            <Button
                type="submit"
                color="primary"
                size="md"
                className="w-full"
                isDisabled={isSubmitting}
                isLoading={isSubmitting}
            >
                {submitStatus === 'success' ? successMessage.split('!')[0] + '!' : (isSubmitting ? 'Sending...' : submitButtonText)}
            </Button>
            {submitStatus === 'success' && (
                <div className="font-body text-sm text-center" style={{ color: 'var(--color-text-brand-accent)' }}>
                    {thankYouMessage ?? statusMessage}
                </div>
            )}
            {submitStatus === 'error' && (
                <div className="rounded-lg bg-error-50 p-4 text-error-700 font-body text-sm text-center">{statusMessage}</div>
            )}
        </Form>
    );
};
