import { Link, useForm } from '@inertiajs/react';
import { ExternalLink, ShieldCheck, ShieldAlert } from 'lucide-react';
import { CopyText } from '@/components/CopyText';
import { embedCode } from '@/components/EmbedCode';
import { PageHeader } from '@/components/PageHeader';
import { Button } from '@/components/ui/button';
import { Card, CardBody, CardHeader } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Input, Select, Textarea } from '@/components/ui/input';
import { Field } from '@/components/ui/label';
import AppLayout from '@/layouts/AppLayout';

type Mode = 'off' | 'optional' | 'required';
type FormSettings = { enabled: boolean; heading: string; intro: string | null; button: string; thanks: string; owner_id: number | null; fields: Record<'company' | 'phone' | 'address' | 'file', Mode> };

/** Lead form settings (per company): fields, wording, who gets new leads, and the share link / embed code. */
export default function LeadFormSettings({ form, labels, owners, shareUrl, captcha }: {
    form: FormSettings; labels: Record<string, string>; owners: { id: number; name: string }[]; shareUrl: string; captcha: boolean;
}) {
    const f = useForm<FormSettings & { owner_id: number | null }>({ ...form, intro: form.intro ?? '' });
    const submit = (e: React.FormEvent) => { e.preventDefault(); f.put('/leads/form', { preserveScroll: true }); };
    const setField = (k: keyof FormSettings['fields'], v: Mode) => f.setData('fields', { ...f.data.fields, [k]: v });

    return (
        <AppLayout title="Lead form">
            <PageHeader title="Lead form" breadcrumbs={[{ label: 'Leads', href: '/leads' }, { label: 'Lead form' }]}
                description="Your public enquiry form. Message, name and email are always asked for; choose the other fields." />
            <div className="grid gap-6 lg:grid-cols-[1fr_24rem]">
                <form onSubmit={submit} className="grid content-start gap-6">
                    <Card>
                        <CardHeader title="Form" />
                        <CardBody className="grid gap-4">
                            <Checkbox label="Accept enquiries (switch off to show a “contact us directly” message)" checked={f.data.enabled} onChange={(e) => f.setData('enabled', e.target.checked)} />
                            <Field label="Heading" htmlFor="lf-heading" error={f.errors.heading}><Input id="lf-heading" value={f.data.heading} onChange={(e) => f.setData('heading', e.target.value)} /></Field>
                            <Field label="Intro" htmlFor="lf-intro" error={f.errors.intro}><Textarea id="lf-intro" rows={2} value={f.data.intro ?? ''} onChange={(e) => f.setData('intro', e.target.value)} /></Field>
                            <div className="grid gap-4 sm:grid-cols-2">
                                <Field label="Button text" htmlFor="lf-button" error={f.errors.button}><Input id="lf-button" value={f.data.button} onChange={(e) => f.setData('button', e.target.value)} /></Field>
                                <Field label="New leads go to" htmlFor="lf-owner" error={f.errors.owner_id} hint="They get a notification. Unassigned: everyone who can create quotes.">
                                    <Select id="lf-owner" value={f.data.owner_id ?? ''} onChange={(e) => f.setData('owner_id', e.target.value ? Number(e.target.value) : null)}>
                                        <option value="">Unassigned</option>
                                        {owners.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
                                    </Select>
                                </Field>
                            </div>
                            <Field label="Thank-you message" htmlFor="lf-thanks" error={f.errors.thanks}><Textarea id="lf-thanks" rows={2} value={f.data.thanks} onChange={(e) => f.setData('thanks', e.target.value)} /></Field>
                        </CardBody>
                    </Card>
                    <Card>
                        <CardHeader title="Fields" description="Message, name and email are always required." />
                        <CardBody className="grid gap-3 sm:grid-cols-2">
                            {(Object.keys(labels) as (keyof FormSettings['fields'])[]).map((k) => (
                                <Field key={k} label={labels[k]} htmlFor={`lf-f-${k}`} error={(f.errors as Record<string, string>)[`fields.${k}`]}>
                                    <Select id={`lf-f-${k}`} value={f.data.fields[k]} onChange={(e) => setField(k, e.target.value as Mode)} data-testid={`lead-field-${k}`}>
                                        <option value="off">Don’t ask</option><option value="optional">Optional</option><option value="required">Required</option>
                                    </Select>
                                </Field>
                            ))}
                        </CardBody>
                    </Card>
                    <div><Button disabled={f.processing} data-testid="save-lead-form">Save lead form</Button></div>
                </form>
                <div className="grid content-start gap-6">
                    <Card>
                        <CardHeader title="Share & embed" />
                        <CardBody className="grid gap-4 text-sm">
                            <div><div className="mb-1 font-medium">Share link</div><CopyText value={shareUrl} testId="lead-share-url" />
                                <a href={shareUrl} target="_blank" rel="noopener" className="mt-1 inline-flex items-center gap-1 text-xs text-link underline">Open the form <ExternalLink className="h-3 w-3" /></a></div>
                            <div><div className="mb-1 font-medium">Embed on your website</div><CopyText multiline value={embedCode(`${shareUrl}?embed=1`, 'spin-lead-form', 'Enquiry form', 640)} testId="lead-embed-code" />
                                <p className="mt-1 text-xs text-ink-muted">Paste it where the form should appear (it replaces the Quotient form). It resizes to fit.</p></div>
                            <p className={`flex gap-1.5 text-xs ${captcha ? 'text-green-800' : 'text-amber-800'}`}>
                                {captcha ? <ShieldCheck className="h-4 w-4 shrink-0" /> : <ShieldAlert className="h-4 w-4 shrink-0" />}
                                {captcha ? 'Protected by Cloudflare Turnstile (invisible captcha).' : 'Spam protection: honeypot only. Add TURNSTILE_SITE_KEY and TURNSTILE_SECRET_KEY to the server .env to switch on Cloudflare Turnstile.'}
                            </p>
                        </CardBody>
                    </Card>
                    <Card>
                        <CardHeader title="Preview" description="Save to update." />
                        <iframe src={`${shareUrl}?embed=1`} title="Lead form preview" className="h-[640px] w-full border-0" key={JSON.stringify(form)} />
                    </Card>
                    <p className="text-sm"><Link href="/leads" className="text-link underline">Back to leads</Link></p>
                </div>
            </div>
        </AppLayout>
    );
}
