"use client";

import React, { useRef, useState } from 'react';
import { Form, Button } from '../elements';
import { DynamicFormFields } from '../components/DynamicFormFields';
import type { FormDefinition } from '../../types/api/form';
import { useFormDefinitions } from '../../next/contexts/form-definitions';

export interface EmailSignupSectionProps {
    title?: string;
    subtitle?: string;
    buttonText?: string;
    successMessage?: string;
    /** Override the form definition (falls back to context). */
    formDefinition?: FormDefinition | null;
}

export const EmailSignupSection = ({
    title = "Stay in the loop",
    subtitle = "Subscribe to our newsletter for updates, tips, and exclusive offers.",
    buttonText = "Subscribe",
    successMessage = "You're subscribed! Thank you.",
    formDefinition,
}: EmailSignupSectionProps) => {
    const { marketingListSignupFormDefinition } = useFormDefinitions();
    const resolvedFormDefinition = formDefinition ?? marketingListSignupFormDefinition;
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [submitStatus, setSubmitStatus] = useState<'idle' | 'success' | 'error'>('idle');
    const [statusMessage, setStatusMessage] = useState('');
    const formRef = useRef<HTMLFormElement>(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: 'marketing_list_signup' };
        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();
                setTimeout(() => setSubmitStatus('idle'), 6000);
            } 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 (!resolvedFormDefinition) return null;

    return (
        <section className="bg-secondary py-16 md:py-20">
            <div className="mx-auto max-w-container px-4 md:px-8">
                <div className="mx-auto max-w-xl text-center">
                    <h2 className="font-display text-display-sm font-semibold text-primary md:text-display-md">
                        {title}
                    </h2>
                    {subtitle && (
                        <p className="mt-4 font-body text-lg text-tertiary">
                            {subtitle}
                        </p>
                    )}
                    <Form
                        ref={formRef}
                        onSubmit={handleSubmit}
                        className="mt-8 flex flex-col gap-6 text-left"
                    >
                        <DynamicFormFields form={resolvedFormDefinition} />
                        {submitStatus === 'success' && (
                            <div className="rounded-lg bg-success-50 p-4 text-success-700">
                                {statusMessage || successMessage}
                            </div>
                        )}
                        {submitStatus === 'error' && (
                            <div className="rounded-lg bg-error-50 p-4 text-error-700">
                                {statusMessage}
                            </div>
                        )}
                        <Button
                            type="submit"
                            color="primary"
                            size="xl"
                            isDisabled={isSubmitting}
                            isLoading={isSubmitting}
                            className="w-full"
                        >
                            {isSubmitting ? 'Subscribing...' : buttonText}
                        </Button>
                    </Form>
                </div>
            </div>
        </section>
    );
};
