import { Head, useForm } from '@inertiajs/react';
import AppLayout from '@/layouts/app-layout';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import InputError from '@/components/input-error';
import { Checkbox } from '@/components/ui/checkbox';
import { Textarea } from '@/components/ui/textarea';
import { type BreadcrumbItem } from '@/types';
import { useState } from 'react';

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Entries', href: '/entries' },
    { title: 'Create', href: '/entries/create' }
];

const GROUPS: { key: string; title: string; fields: string[] }[] = [
    { key: 'meta', title: 'Meta & Status', fields: ['form_name', 'origin_site', 'seven_days_from', 'last_page_filled', 'approved', 'approved_at', 'death_cert_received', 'pm_med_records_received'] },
    { key: 'respondent', title: 'Respondent Details', fields: ['title', 'title_other', 'first_name', 'last_name', 'address_1', 'address_2', 'city', 'county', 'country', 'postcode', 'telephone', 'email', 'relationship_type', 'relationship_if_family', 'relationship_if_friend', 'relationship_if_professional'] },
    { key: 'consent', title: 'Consent', fields: ['consent', 'agree_study_publications', 'agree_further_research', 'agree_use_of_info', 'agree_use_of_info_part2', 'allowed_to_contact', 'preferred_contact', 'wants_more_info_on_helping', 'receive_enews', 'allowed_to_contact_med_team'] },
    { key: 'medical', title: 'Medical Notice', fields: ['medical_notice_details', 'medical_notice_permission'] },
    { key: 'deceased', title: 'Deceased Details', fields: ['deceased_title', 'deceased_first_name', 'deceased_last_name', 'deceased_known_as', 'deceased_address_1', 'deceased_address_2', 'deceased_city', 'deceased_county', 'deceased_country', 'deceased_postcode', 'age_at_death', 'exact_age_at_death', 'deceased_gender', 'deceased_gender_other', 'date_of_birth', 'date_of_death'] },
    { key: 'death', title: 'Death Circumstances', fields: ['knows_where_death_occurred', 'where_death_occurred', 'coroner_or_fiscal', 'gp', 'knows_certified_cause', 'type_of_death_certificate', 'cause_1a', 'cause_1b', 'cause_1c', 'cause_2', 'other_type_certificate', 'no_certificate_but_told_cause', 'agree_to_contact_for_copy'] },
    { key: 'demographics', title: 'Demographics', fields: ['language', 'nationality', 'ethnicity', 'ethnicity_other', 'occupation', 'occupation_other'] },
    { key: 'other', title: 'Other', fields: ['other_comments'] },
];

const BOOLEAN_FIELDS = new Set(['approved', 'death_cert_received', 'pm_med_records_received', 'consent', 'agree_study_publications', 'agree_further_research', 'agree_use_of_info', 'agree_use_of_info_part2', 'allowed_to_contact', 'wants_more_info_on_helping', 'receive_enews', 'allowed_to_contact_med_team', 'medical_notice_permission', 'knows_where_death_occurred', 'knows_certified_cause', 'no_certificate_but_told_cause', 'agree_to_contact_for_copy']);
const DATE_FIELDS = new Set(['approved_at', 'seven_days_from', 'date_of_birth', 'date_of_death']);
const TEXTAREA_FIELDS = new Set(['medical_notice_details', 'other_comments', 'cause_1a', 'cause_1b', 'cause_1c', 'cause_2']);
const NUMBER_FIELDS = new Set(['age_at_death']);

type FormDataShape = { [k: string]: string | number | boolean | null | undefined };

const initialData: FormDataShape = GROUPS.flatMap(g => g.fields).reduce((acc, f) => { acc[f] = ''; return acc; }, {} as FormDataShape);
initialData['consent'] = false;

export default function CreateEntry() {
    const [stepIndex, setStepIndex] = useState(0);
    const group = GROUPS[stepIndex];
    const { data, setData, post, processing, errors } = useForm(initialData);

    const setField = (field: string, value: unknown) => {
        // Inertia's setData expects (key,value)
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        (setData as any)(field, value);
    };

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        if (stepIndex < GROUPS.length - 1) {
            setStepIndex(stepIndex + 1);
            return;
        }
        post(route('entries.store'));
    };

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Create Entry" />
            <div className="space-y-6 max-w-5xl">
                <div className="flex items-center justify-between flex-wrap gap-2">
                    <h1 className="text-2xl font-semibold">New Entry: {group.title}</h1>
                    <div className="flex gap-2 flex-wrap">
                        {GROUPS.map((g, i) => (
                            <Button key={g.key} type="button" variant={i === stepIndex ? 'default' : 'secondary'} size="sm" onClick={() => setStepIndex(i)}>{g.title}</Button>
                        ))}
                    </div>
                </div>
                <form onSubmit={submit} className="space-y-8">
                    <div className="grid gap-6 md:grid-cols-2">
                        {group.fields.map(field => {
                            const value = data[field] ?? (BOOLEAN_FIELDS.has(field) ? false : '');
                            const commonProps = { id: field, name: field };
                            return (
                                <div key={field} className="flex flex-col gap-2">
                                    <Label htmlFor={field} className="capitalize">{field.replace(/_/g, ' ')}</Label>
                                    {BOOLEAN_FIELDS.has(field) ? (
                                        <div className="flex items-center gap-2">
                                            <Checkbox id={field} checked={!!value} onCheckedChange={val => setField(field, !!val)} />
                                        </div>
                                    ) : DATE_FIELDS.has(field) ? (
                                        <Input type="date" {...commonProps} value={value as string || ''} onChange={e => setField(field, e.target.value)} />
                                    ) : NUMBER_FIELDS.has(field) ? (
                                        <Input type="number" {...commonProps} value={value as number | string || ''} onChange={e => setField(field, e.target.value ? parseInt(e.target.value, 10) : '')} />
                                    ) : TEXTAREA_FIELDS.has(field) ? (
                                        <Textarea {...commonProps} value={value as string || ''} onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setField(field, e.target.value)} rows={3} />
                                    ) : (
                                        <Input type="text" {...commonProps} value={value as string || ''} onChange={e => setField(field, e.target.value)} />
                                    )}
                                    <InputError message={(errors as Record<string, string | undefined>)[field]} />
                                </div>
                            );
                        })}
                    </div>
                    <div className="flex items-center gap-4 flex-wrap">
                        <Button type="submit" disabled={processing}>{stepIndex < GROUPS.length - 1 ? 'Next' : 'Create Entry'}</Button>
                        {stepIndex > 0 && (
                            <Button type="button" variant="outline" onClick={() => setStepIndex(stepIndex - 1)}>Previous</Button>
                        )}
                    </div>
                </form>
            </div>
        </AppLayout>
    );
}
