import { CheckCircle2, Loader2, Paperclip } from 'lucide-react';
import { useRef, useState } from 'react';
import { type Brand, postForm, PublicShell, publicInputStyle, Turnstile } from '@/components/public/PublicShell';

type Mode = 'off' | 'optional' | 'required';
type Props = {
    brand: Brand;
    form: { enabled: boolean; heading: string; intro: string | null; button: string; thanks: string; fields: Record<'company' | 'phone' | 'address' | 'file', Mode>; labels: Record<string, string> };
    action: string; embed: boolean; turnstileSiteKey: string | null; startedAt: string;
};

/** The public lead form (share link or iframe embed). */
export default function LeadForm({ brand, form, action, embed, turnstileSiteKey, startedAt }: Props) {
    const ref = useRef<HTMLFormElement>(null);
    const [busy, setBusy] = useState(false);
    const [errors, setErrors] = useState<Record<string, string>>({});
    const [done, setDone] = useState<string | null>(null);
    const [fileName, setFileName] = useState<string | null>(null);

    const submit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!ref.current) return;
        setBusy(true); setErrors({});
        const fd = new FormData(ref.current);
        fd.set('page_url', (document.referrer || window.location.href).slice(0, 500));
        const r = await postForm(action, fd);
        setBusy(false);
        if (r.ok) setDone(r.data?.message ?? form.thanks);
        else {
            setErrors(r.errors);
            (window as any).turnstile?.reset?.();
        }
    };

    return (
        <PublicShell brand={brand} title={form.heading} embed={embed}>
            {({ p, hf }) => {
                const input = 'mt-1 block w-full rounded-lg border px-3 py-2.5 text-[15px] outline-none focus:ring-2';
                const ring = { ...publicInputStyle(p), ['--tw-ring-color' as string]: p.tintStrong };
                const label = (name: string, text: string, required: boolean) => (
                    <label htmlFor={`lf-${name}`} className="text-sm font-medium">{text}{required ? <span aria-hidden style={{ color: p.accentInk }}> *</span> : <span className="font-normal" style={{ color: p.muted }}> (optional)</span>}</label>
                );
                const err = (name: string) => errors[name] ? <p className="mt-1 text-sm text-red-700" role="alert">{errors[name]}</p> : null;
                const field = (name: 'company' | 'phone' | 'address', type = 'text', autoComplete?: string) => form.fields[name] !== 'off' && (
                    <div>
                        {label(name, form.labels[name], form.fields[name] === 'required')}
                        <input id={`lf-${name}`} name={name} type={type} autoComplete={autoComplete} required={form.fields[name] === 'required'} className={input} style={ring} />
                        {err(name)}
                    </div>
                );
                if (!form.enabled) {
                    return <div className="rounded-2xl p-6 text-center" style={{ background: p.bg, border: `1px solid ${p.cardLine}` }}>This form isn’t taking enquiries at the moment. Please contact {brand.name} directly{brand.phone ? ` on ${brand.phone}` : ''}.</div>;
                }
                if (done) {
                    return (
                        <div className="rounded-2xl p-8 text-center" style={{ background: p.bg, border: `1px solid ${p.cardLine}` }} data-testid="lead-thanks" role="status">
                            <CheckCircle2 className="mx-auto h-10 w-10" style={{ color: p.accent }} aria-hidden />
                            <h1 className="mt-3 text-xl font-semibold" style={hf}>Thank you</h1>
                            <p className="mt-2 text-[15px]" style={{ color: p.muted }}>{done}</p>
                        </div>
                    );
                }
                return (
                    <form ref={ref} onSubmit={submit} noValidate={false} className="rounded-2xl p-6 sm:p-8" style={{ background: p.bg, border: embed ? undefined : `1px solid ${p.cardLine}` }} data-testid="lead-form">
                        <h1 className="text-2xl font-semibold leading-tight" style={hf}>{form.heading}</h1>
                        {form.intro && <p className="mt-2 text-[15px]" style={{ color: p.muted }}>{form.intro}</p>}
                        <div className="mt-6 grid gap-4">
                            <div className="grid gap-4 sm:grid-cols-2">
                                <div>{label('name', 'Your name', true)}<input id="lf-name" name="name" autoComplete="name" required className={input} style={ring} />{err('name')}</div>
                                <div>{label('email', 'Email', true)}<input id="lf-email" name="email" type="email" autoComplete="email" required className={input} style={ring} />{err('email')}</div>
                            </div>
                            {(form.fields.company !== 'off' || form.fields.phone !== 'off') && (
                                <div className="grid gap-4 sm:grid-cols-2">{field('company', 'text', 'organization')}{field('phone', 'tel', 'tel')}</div>
                            )}
                            {field('address', 'text', 'street-address')}
                            <div>
                                {label('message', 'How can we help?', true)}
                                <textarea id="lf-message" name="message" rows={5} required className={input} style={ring} />
                                {err('message')}
                            </div>
                            {form.fields.file !== 'off' && (
                                <div>
                                    <span className="text-sm font-medium">{form.labels.file}{form.fields.file === 'required' ? <span aria-hidden style={{ color: p.accentInk }}> *</span> : <span className="font-normal" style={{ color: p.muted }}> (optional, up to 10 MB)</span>}</span>
                                    <label className="mt-1 flex cursor-pointer items-center gap-2 rounded-lg border border-dashed px-3 py-3 text-sm" style={{ borderColor: p.cardLine, color: p.muted }}>
                                        <Paperclip className="h-4 w-4 shrink-0" aria-hidden />
                                        <span className="min-w-0 truncate">{fileName ?? 'Attach a brief, plan or photo'}</span>
                                        <input name="file" type="file" className="sr-only" required={form.fields.file === 'required'} onChange={(e) => setFileName(e.target.files?.[0]?.name ?? null)}
                                            accept=".pdf,.doc,.docx,.xls,.xlsx,.csv,.txt,.jpg,.jpeg,.png,.gif,.webp,.zip" />
                                    </label>
                                    {err('file')}
                                </div>
                            )}
                            {/* Honeypot (hidden from people) and the form's start time. */}
                            <div aria-hidden className="absolute -left-[9999px] h-0 w-0 overflow-hidden"><label>Website<input name="website_url" tabIndex={-1} autoComplete="off" /></label></div>
                            <input type="hidden" name="started_at" value={startedAt} />
                            <Turnstile siteKey={turnstileSiteKey} />
                            {(errors.captcha || errors.form) && <p className="text-sm text-red-700" role="alert">{errors.captcha ?? errors.form}</p>}
                            <button type="submit" disabled={busy} className="inline-flex h-12 items-center justify-center gap-2 rounded-lg px-6 text-[15px] font-semibold disabled:opacity-60"
                                style={{ background: p.button, color: p.onButton }} data-testid="lead-submit">
                                {busy && <Loader2 className="h-4 w-4 animate-spin" />} {form.button}
                            </button>
                        </div>
                    </form>
                );
            }}
        </PublicShell>
    );
}
