import { router, useForm } from '@inertiajs/react';
import { Check, Pencil, Trash2, X } from 'lucide-react';
import { useState } from 'react';
import EssenceTarifController from '@/actions/App/Http/Controllers/Referentiels/EssenceTarifController';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { DataTableActionButton, formatTableDay } from '@/components/data-table';
import InputError from '@/components/input-error';
import { Input } from '@/components/ui/input';
import { formatNumber } from '@/lib/utils';
import type { Essence, EssenceTarif } from '@/types/business';

/** Date de la ligne qui porte le tarif en place avant tout changement daté. */
const ORIGINE = '2000-01-01';

function Ligne({
    essenceId,
    tarif,
}: {
    essenceId: number;
    tarif: EssenceTarif;
}) {
    const date = tarif.date_effet.slice(0, 10);
    const origine = date === ORIGINE;
    const libelle = origine ? 'Origine' : formatTableDay(date);
    const params = { essence: essenceId, tarif: tarif.id };

    const [editing, setEditing] = useState(false);
    const form = useForm({
        date_effet: date,
        cout_m3: String(tarif.cout_m3),
        taux_m3: String(tarif.taux_m3),
    });

    function cancel() {
        form.reset();
        form.clearErrors();
        setEditing(false);
    }

    function save() {
        form.put(EssenceTarifController.update.url(params), {
            preserveScroll: true,
            preserveState: true,
            onSuccess: () => setEditing(false),
        });
    }

    const montant = (name: 'cout_m3' | 'taux_m3', label: string) => (
        <td className="py-1 pl-2 align-top">
            <Input
                type="number"
                min={0}
                step={1}
                aria-label={label}
                className="text-right"
                value={form.data[name]}
                onChange={(e) => form.setData(name, e.target.value)}
            />
            <InputError message={form.errors[name]} />
        </td>
    );

    return (
        <tr className="border-t">
            {editing ? (
                <>
                    <td className="py-1 align-top">
                        {origine ? (
                            libelle
                        ) : (
                            <Input
                                type="date"
                                aria-label="Date d'effet"
                                value={form.data.date_effet}
                                onChange={(e) =>
                                    form.setData('date_effet', e.target.value)
                                }
                            />
                        )}
                        <InputError message={form.errors.date_effet} />
                    </td>
                    {montant('cout_m3', 'Coût au m³')}
                    {montant('taux_m3', 'Taux au m³')}
                </>
            ) : (
                <>
                    <td className="py-1">{libelle}</td>
                    <td className="py-1 text-right tabular-nums">
                        {formatNumber(tarif.cout_m3)}
                    </td>
                    <td className="py-1 text-right tabular-nums">
                        {formatNumber(tarif.taux_m3)}
                    </td>
                </>
            )}
            <td className="py-1 pl-2">
                <div className="flex justify-end gap-1">
                    {editing ? (
                        <>
                            <DataTableActionButton
                                label="Enregistrer la correction"
                                tone="accent"
                                icon={<Check className="size-4" />}
                                disabled={form.processing}
                                onClick={save}
                            />
                            <DataTableActionButton
                                label="Annuler"
                                icon={<X className="size-4" />}
                                onClick={cancel}
                            />
                        </>
                    ) : (
                        <>
                            <DataTableActionButton
                                label={`Corriger le tarif : ${libelle}`}
                                tone="accent"
                                icon={<Pencil className="size-4" />}
                                onClick={() => setEditing(true)}
                            />
                            {!origine && (
                                <ConfirmDialog
                                    trigger={
                                        <DataTableActionButton
                                            label={`Supprimer le tarif : ${libelle}`}
                                            tone="destructive"
                                            icon={<Trash2 className="size-4" />}
                                        />
                                    }
                                    title={`Supprimer le tarif du ${libelle} ?`}
                                    description="Les billes déjà saisies gardent leur montant."
                                    confirmLabel="Supprimer"
                                    onConfirm={() =>
                                        router.delete(
                                            EssenceTarifController.destroy.url(
                                                params,
                                            ),
                                            {
                                                preserveScroll: true,
                                                preserveState: true,
                                            },
                                        )
                                    }
                                />
                            )}
                        </>
                    )}
                </div>
            </td>
        </tr>
    );
}

export function EssenceTarifHistory({ essence }: { essence: Essence }) {
    const tarifs = essence.tarifs ?? [];

    return tarifs.length === 0 ? null : (
        <div className="space-y-2 border-t pt-4">
            <h3 className="text-sm font-medium">Historique du barème</h3>
            <p className="text-xs text-muted-foreground">
                Une correction ne modifie pas les billes déjà saisies.
            </p>
            <table className="w-full text-sm">
                <thead className="text-left text-muted-foreground">
                    <tr>
                        <th className="py-1 font-normal">À partir du</th>
                        <th className="py-1 text-right font-normal">
                            Coût / m³
                        </th>
                        <th className="py-1 text-right font-normal">
                            Taux / m³
                        </th>
                        <th className="py-1">
                            <span className="sr-only">Actions</span>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    {tarifs.map((tarif) => (
                        <Ligne
                            key={`${tarif.id}-${tarif.date_effet}-${tarif.cout_m3}-${tarif.taux_m3}`}
                            essenceId={essence.id}
                            tarif={tarif}
                        />
                    ))}
                </tbody>
            </table>
        </div>
    );
}
