import { Head, Link, useForm } from '@inertiajs/react';
import { ChevronDown, Plus, Trash2 } from 'lucide-react';
import { useRef, useState } from 'react';
import type { ComponentProps, FormEvent } from 'react';
import EntreeBoisController from '@/actions/App/Http/Controllers/EntreeBoisController';
import InputError from '@/components/input-error';
import { PageHeader } from '@/components/page-header';
import { SearchableSelect } from '@/components/searchable-select';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import {
    Collapsible,
    CollapsibleContent,
    CollapsibleTrigger,
} from '@/components/ui/collapsible';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { formatNumber, plural } from '@/lib/utils';
import { dashboard } from '@/routes';
import { create, index } from '@/routes/entrees-bois';
import type { Chantier, Essence, Exploitant } from '@/types/business';

type BilleForm = {
    key: number;
    essence_id: string;
    numero_bille: string;
    lettre: string;
    zone: string;
    coordonnee_x: string;
    coordonnee_y: string;
    longueur: string;
    diametre: string;
    cubage: string;
};

const emptyBille = (key: number, essenceId = ''): BilleForm => ({
    key,
    essence_id: essenceId,
    numero_bille: '',
    lettre: '',
    zone: '29N',
    coordonnee_x: '',
    coordonnee_y: '',
    longueur: '',
    diametre: '',
    cubage: '',
});

/** Volume d'une grume : π/4 × d² × L (longueur en m, diamètre en cm). */
function computeCubage(longueur: string, diametre: string): string {
    const l = Number(longueur);
    const d = Number(diametre) / 100;

    return l > 0 && d > 0 ? ((Math.PI / 4) * d * d * l).toFixed(3) : '';
}

const TEXT_FIELDS = [
    'numero_je',
    'numero_bordereau',
    'date_chargement',
    'date_entree',
    'transporteur',
    'numero_camion',
    'chauffeur',
    'date_heure_depart',
    'date_heure_arrivee',
    'destination',
    'parc_usine',
] as const;

type TextField = (typeof TEXT_FIELDS)[number];

const TRANSPORT_FIELDS: TextField[] = [
    'transporteur',
    'numero_camion',
    'chauffeur',
    'date_chargement',
    'date_heure_depart',
    'date_heure_arrivee',
    'destination',
    'parc_usine',
];

type FormData = Record<TextField, string> & {
    chantier_id: string;
    exploitant_id: string;
    billes: BilleForm[];
};

export default function EntreesBoisCreate({
    essences,
    exploitants,
    chantiers,
}: {
    essences: Essence[];
    exploitants: Exploitant[];
    chantiers: Chantier[];
}) {
    const nextKey = useRef(1);
    const form = useForm<FormData>({
        ...(Object.fromEntries(TEXT_FIELDS.map((name) => [name, ''])) as Record<
            TextField,
            string
        >),
        date_entree: new Date().toISOString().slice(0, 10),
        chantier_id: '',
        exploitant_id: '',
        billes: [emptyBille(0)],
    });
    const { data, setData, processing } = form;
    const errors = form.errors as Record<string, string | undefined>;
    const [transportOuvert, setTransportOuvert] = useState(false);
    const erreurTransport = TRANSPORT_FIELDS.some((name) => errors[name]);

    const essenceOptions = essences.map((e) => ({
        value: String(e.id),
        label: `${e.nom} (${e.code})`,
    }));
    const exploitant = exploitants.find(
        (e) => String(e.id) === data.exploitant_id,
    );

    const totalCubage = data.billes.reduce(
        (sum, bille) => sum + (Number(bille.cubage) || 0),
        0,
    );

    function field(
        name: TextField,
        label: string,
        props: ComponentProps<typeof Input> = {},
    ) {
        return (
            <div className="grid content-start gap-2">
                <Label htmlFor={name}>{label}</Label>
                <Input
                    id={name}
                    value={data[name]}
                    onChange={(e) => setData(name, e.target.value)}
                    aria-invalid={errors[name] ? true : undefined}
                    {...props}
                />
                <InputError message={errors[name]} />
            </div>
        );
    }

    function selectChantier(value: string) {
        const chantier = chantiers.find((c) => String(c.id) === value);

        setData((current) => ({
            ...current,
            chantier_id: value === 'none' ? '' : value,
            exploitant_id: chantier?.exploitant_id
                ? String(chantier.exploitant_id)
                : current.exploitant_id,
        }));
    }

    function updateBille(key: number, changes: Partial<BilleForm>) {
        setData((current) => ({
            ...current,
            billes: current.billes.map((bille) => {
                if (bille.key !== key) {
                    return bille;
                }

                const next = { ...bille, ...changes };

                if ('longueur' in changes || 'diametre' in changes) {
                    next.cubage = computeCubage(next.longueur, next.diametre);
                }

                return next;
            }),
        }));
    }

    function addBille() {
        const key = nextKey.current++;

        setData((current) => ({
            ...current,
            billes: [
                ...current.billes,
                emptyBille(key, current.billes.at(-1)?.essence_id),
            ],
        }));
    }

    function removeBille(key: number) {
        // Les erreurs sont indexées par position : elles deviendraient fausses.
        form.clearErrors();
        setData((current) => ({
            ...current,
            billes: current.billes.filter((bille) => bille.key !== key),
        }));
    }

    function submit(event: FormEvent) {
        event.preventDefault();
        form.post(EntreeBoisController.store.url(), { preserveScroll: true });
    }

    return (
        <>
            <Head title="Nouvelle entrée de bois" />

            <div className="flex h-full flex-1 flex-col gap-6 p-4 md:p-6">
                <PageHeader
                    className="mb-0"
                    title="Nouvelle entrée de bois"
                    description="Saisir un bordereau de circulation et ses billes"
                />

                <form onSubmit={submit} className="space-y-6">
                    <Card>
                        <CardHeader>
                            <CardTitle>Bordereau</CardTitle>
                        </CardHeader>
                        <CardContent className="grid gap-4 md:grid-cols-3">
                            {field(
                                'numero_je',
                                'N° du journal des entrées (JE)',
                                {
                                    required: true,
                                },
                            )}
                            {field(
                                'numero_bordereau',
                                'Bordereau de circulation, page n°',
                            )}
                            {field(
                                'date_entree',
                                "Date d'entrée (déchargement)",
                                {
                                    type: 'date',
                                    required: true,
                                },
                            )}
                            <div className="grid content-start gap-2">
                                <Label htmlFor="chantier_id">Chantier</Label>
                                <SearchableSelect
                                    id="chantier_id"
                                    options={chantiers.map((c) => ({
                                        value: String(c.id),
                                        label: [
                                            c.numero,
                                            c.village,
                                            c.cantonnement,
                                        ]
                                            .filter(Boolean)
                                            .join(' — '),
                                    }))}
                                    value={data.chantier_id || 'none'}
                                    onChange={selectChantier}
                                    noneLabel="Non renseigné"
                                    invalid={!!errors.chantier_id}
                                />
                                <InputError message={errors.chantier_id} />
                            </div>
                            <div className="grid content-start gap-2">
                                <Label htmlFor="exploitant_id">
                                    Exploitant
                                </Label>
                                <SearchableSelect
                                    id="exploitant_id"
                                    options={exploitants.map((e) => ({
                                        value: String(e.id),
                                        label: `${e.marteau} — ${e.nom}`,
                                    }))}
                                    value={data.exploitant_id || 'none'}
                                    onChange={(value) =>
                                        setData(
                                            'exploitant_id',
                                            value === 'none' ? '' : value,
                                        )
                                    }
                                    noneLabel="Non renseigné"
                                    invalid={!!errors.exploitant_id}
                                />
                                <InputError message={errors.exploitant_id} />
                            </div>
                            {exploitant && (
                                <p className="rounded-md bg-muted/50 px-3 py-2 text-sm md:col-span-3">
                                    <span className="text-muted-foreground">
                                        Code exploitant :{' '}
                                    </span>
                                    {exploitant.code ?? '—'}
                                    <span className="ml-6 text-muted-foreground">
                                        Marteau :{' '}
                                    </span>
                                    {exploitant.marteau}
                                </p>
                            )}
                        </CardContent>
                    </Card>

                    <Collapsible
                        open={transportOuvert || erreurTransport}
                        onOpenChange={setTransportOuvert}
                        asChild
                    >
                        <Card>
                            <CardHeader>
                                <CollapsibleTrigger className="group flex items-center justify-between text-left">
                                    <CardTitle>
                                        Transport (facultatif)
                                    </CardTitle>
                                    <ChevronDown className="size-4 transition-transform group-data-[state=open]:rotate-180" />
                                </CollapsibleTrigger>
                            </CardHeader>
                            <CollapsibleContent asChild>
                                <CardContent className="grid gap-4 md:grid-cols-3">
                                    {field('transporteur', 'Transporteur')}
                                    {field('numero_camion', 'N° du camion')}
                                    {field('chauffeur', 'Chauffeur')}
                                    {field(
                                        'date_chargement',
                                        'Date de chargement',
                                        {
                                            type: 'date',
                                        },
                                    )}
                                    {field('date_heure_depart', 'Départ', {
                                        type: 'datetime-local',
                                    })}
                                    {field('date_heure_arrivee', 'Arrivée', {
                                        type: 'datetime-local',
                                    })}
                                    {field('destination', 'Destination')}
                                    {field('parc_usine', 'Parc usine')}
                                </CardContent>
                            </CollapsibleContent>
                        </Card>
                    </Collapsible>

                    <Card>
                        <CardHeader>
                            <CardTitle>Billes</CardTitle>
                            <CardDescription>
                                Longueur en mètres, diamètre en centimètres. Le
                                cubage est calculé automatiquement et reste
                                modifiable.
                            </CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            {data.billes.map((bille, i) => {
                                const input = (
                                    name: Exclude<
                                        keyof BilleForm,
                                        'key' | 'essence_id'
                                    >,
                                    label: string,
                                    props: ComponentProps<typeof Input> = {},
                                ) => {
                                    const id = `billes.${i}.${name}`;

                                    return (
                                        <div className="grid content-start gap-2">
                                            <Label htmlFor={id}>{label}</Label>
                                            <Input
                                                id={id}
                                                value={bille[name]}
                                                onChange={(e) =>
                                                    updateBille(bille.key, {
                                                        [name]: e.target.value,
                                                    })
                                                }
                                                aria-invalid={
                                                    errors[id]
                                                        ? true
                                                        : undefined
                                                }
                                                {...props}
                                            />
                                            <InputError message={errors[id]} />
                                        </div>
                                    );
                                };
                                const decimal = {
                                    type: 'number',
                                    inputMode: 'decimal',
                                } as const;
                                const measure = {
                                    ...decimal,
                                    min: 0,
                                    required: true,
                                } as const;
                                const essenceError =
                                    errors[`billes.${i}.essence_id`];

                                return (
                                    <fieldset
                                        key={bille.key}
                                        aria-label={`Bille ${i + 1}`}
                                        className="space-y-4 rounded-lg border p-4"
                                    >
                                        <div className="flex items-center justify-between">
                                            <p className="text-sm font-medium">
                                                Bille {i + 1}
                                            </p>
                                            {data.billes.length > 1 && (
                                                <Button
                                                    type="button"
                                                    variant="ghost"
                                                    size="sm"
                                                    onClick={() =>
                                                        removeBille(bille.key)
                                                    }
                                                >
                                                    <Trash2 />
                                                    Retirer
                                                </Button>
                                            )}
                                        </div>
                                        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                                            <div className="grid content-start gap-2 sm:col-span-2 lg:col-span-1">
                                                <Label
                                                    htmlFor={`billes.${i}.essence_id`}
                                                >
                                                    Essence
                                                </Label>
                                                <SearchableSelect
                                                    id={`billes.${i}.essence_id`}
                                                    options={essenceOptions}
                                                    value={bille.essence_id}
                                                    onChange={(value) =>
                                                        updateBille(bille.key, {
                                                            essence_id: value,
                                                        })
                                                    }
                                                    placeholder="Choisir une essence…"
                                                    invalid={!!essenceError}
                                                />
                                                <InputError
                                                    message={essenceError}
                                                />
                                            </div>
                                            <div className="grid content-start gap-2">
                                                <Label
                                                    htmlFor={`billes.${i}.code`}
                                                >
                                                    Code essence
                                                </Label>
                                                <Input
                                                    id={`billes.${i}.code`}
                                                    value={
                                                        essences.find(
                                                            (e) =>
                                                                String(e.id) ===
                                                                bille.essence_id,
                                                        )?.code ?? ''
                                                    }
                                                    placeholder="Automatique"
                                                    readOnly
                                                    tabIndex={-1}
                                                    className="bg-muted/50"
                                                />
                                            </div>
                                            {input(
                                                'numero_bille',
                                                'N° de bille',
                                                { required: true },
                                            )}
                                            {input('lettre', 'Lettre', {
                                                maxLength: 1,
                                            })}
                                            {input('longueur', 'Longueur (m)', {
                                                ...measure,
                                                step: '0.01',
                                            })}
                                            {input(
                                                'diametre',
                                                'Diamètre (cm)',
                                                {
                                                    ...measure,
                                                    step: '1',
                                                },
                                            )}
                                            {input('cubage', 'Cubage (m³)', {
                                                ...measure,
                                                step: '0.001',
                                            })}
                                            {input('zone', 'Zone')}
                                            {input(
                                                'coordonnee_x',
                                                'Coordonnée X',
                                                { ...decimal, step: '0.01' },
                                            )}
                                            {input(
                                                'coordonnee_y',
                                                'Coordonnée Y',
                                                { ...decimal, step: '0.01' },
                                            )}
                                        </div>
                                    </fieldset>
                                );
                            })}

                            <InputError message={errors.billes} />

                            <div className="flex flex-wrap items-center justify-between gap-3">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={addBille}
                                >
                                    <Plus />
                                    Ajouter une bille
                                </Button>
                                <p className="text-sm font-medium tabular-nums">
                                    {plural(data.billes.length, 'bille')} ·{' '}
                                    {formatNumber(totalCubage, 3)} m³
                                </p>
                            </div>
                        </CardContent>
                    </Card>

                    <div className="flex gap-3">
                        <Button disabled={processing}>
                            Enregistrer l'entrée
                        </Button>
                        <Button variant="outline" asChild>
                            <Link href={index()}>Annuler</Link>
                        </Button>
                    </div>
                </form>
            </div>
        </>
    );
}

EntreesBoisCreate.layout = {
    breadcrumbs: [
        { title: 'Tableau de bord', href: dashboard() },
        { title: 'Entrées de bois', href: index() },
        { title: 'Nouvelle entrée', href: create() },
    ],
};
