"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';

interface JobApplicationFormProps {
    jobSlug: string;
    /** Form fields are rendered from this definition (required). */
    formDefinition: FormDefinition | null | undefined;
    inline?: boolean;
}

export const JobApplicationForm = ({ jobSlug, formDefinition, inline = false }: JobApplicationFormProps) => {
    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 = formDefinition != null && Array.isArray(formDefinition.fields) && formDefinition.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: 'job_application', jobSlug };
        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 || "Thank you for applying! We'll be in touch soon.");
                formRef.current?.reset();
                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.');
        }
        setIsSubmitting(false);
    };

    if (!hasFields) return null;

    const formContent = (
        <Form ref={formRef} onSubmit={handleSubmit} className="flex flex-col gap-6">
            <DynamicFormFields form={formDefinition} jobSlug={jobSlug} />
            {submitStatus === 'success' && (
                <div className="rounded-lg bg-success-50 p-4 text-success-700">{statusMessage}</div>
            )}
            {submitStatus === 'error' && (
                <div className="rounded-lg bg-error-50 p-4 text-error-700">{statusMessage}</div>
            )}
            <Button
                type="submit"
                color="primary"
                size="xl"
                className="w-full"
                isDisabled={isSubmitting}
                isLoading={isSubmitting}
            >
                {isSubmitting ? 'Submitting...' : 'Submit Application'}
            </Button>
        </Form>
    );

    if (inline) return formContent;

    return (
        <section id="application-form" className="bg-primary py-16 md:py-20">
            <div className="mx-auto max-w-container px-4 md:px-8">
                <div className="mx-auto max-w-2xl">
                    <div className="mb-8 text-center">
                        <h2 className="text-display-sm font-semibold text-primary md:text-display-md">
                            Apply for this Position
                        </h2>
                        <p className="mt-4 text-lg text-tertiary">
                            Fill out the form below to submit your application
                        </p>
                    </div>
                    {formContent}
                </div>
            </div>
        </section>
    );
};
