import { Head, Link, router, useForm } from '@inertiajs/react';
import { ArrowLeft, Check, Trash2, X } from 'lucide-react';
import type { ReactNode } from 'react';
import EntreeBoisController from '@/actions/App/Http/Controllers/EntreeBoisController';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { formatTableDay } from '@/components/data-table';
import InputError from '@/components/input-error';
import { PageHeader } from '@/components/page-header';
import { ResponsiveList } from '@/components/responsive-list';
import { StatutEntreeBadge } from '@/components/statut-entree-badge';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { useHasRole } from '@/hooks/use-can';
import { formatNumber, plural } from '@/lib/utils';
import { dashboard } from '@/routes';
import { index } from '@/routes/entrees-bois';
import type { EntreeBois } from '@/types/business';

/**
 * Les heures saisies sont stockées telles quelles (fuseau UTC, celui d'Abidjan) :
 * on les réaffiche sans conversion vers le fuseau du navigateur.
 */
const dateTime = (value: string | null) =>
    value
        ? new Intl.DateTimeFormat('fr-FR', {
              dateStyle: 'medium',
              timeStyle: 'short',
              timeZone: 'UTC',
          }).format(new Date(value))
        : '—';

function Details({ items }: { items: [string, ReactNode][] }) {
    return (
        <dl className="grid gap-4 sm:grid-cols-2">
            {items.map(([label, value]) => (
                <div key={label}>
                    <dt className="text-sm text-muted-foreground">{label}</dt>
                    <dd className="text-sm font-medium">{value || '—'}</dd>
                </div>
            ))}
        </dl>
    );
}

function ValidationCard({ entree }: { entree: EntreeBois }) {
    const form = useForm({ observations: entree.observations ?? '' });

    function decide(statut: 'validee' | 'rejetee') {
        form.transform((data) => ({ ...data, statut }));
        form.patch(EntreeBoisController.validateEntree.url(entree.id), {
            preserveScroll: true,
        });
    }

    return (
        <Card>
            <CardHeader>
                <CardTitle>Validation du bordereau</CardTitle>
                <CardDescription>
                    Vérifiez les billes avant de valider ou rejeter l'entrée.
                    Cette décision est définitive.
                </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
                <div className="grid gap-2">
                    <Label htmlFor="observations">Observations</Label>
                    <textarea
                        id="observations"
                        rows={3}
                        value={form.data.observations}
                        onChange={(e) =>
                            form.setData('observations', e.target.value)
                        }
                        className="rounded-md border border-input bg-transparent px-3 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"
                    />
                    <InputError message={form.errors.observations} />
                </div>
                <div className="flex flex-wrap gap-3">
                    <ConfirmDialog
                        trigger={
                            <Button disabled={form.processing}>
                                <Check />
                                Valider
                            </Button>
                        }
                        variant="default"
                        title={`Valider l'entrée ${entree.numero_je} ?`}
                        description="Cette décision est définitive."
                        confirmLabel="Valider"
                        onConfirm={() => decide('validee')}
                    />
                    <ConfirmDialog
                        trigger={
                            <Button
                                variant="outline"
                                disabled={form.processing}
                            >
                                <X />
                                Rejeter
                            </Button>
                        }
                        title={`Rejeter l'entrée ${entree.numero_je} ?`}
                        description="Cette décision est définitive."
                        confirmLabel="Rejeter"
                        onConfirm={() => decide('rejetee')}
                    />
                </div>
            </CardContent>
        </Card>
    );
}

export default function EntreesBoisShow({
    entree,
    validationRequise,
}: {
    entree: EntreeBois;
    validationRequise: boolean;
}) {
    const isAdmin = useHasRole('admin');
    const isAgentParc = useHasRole('agent_parc');
    const isResponsable = useHasRole('responsable_production');

    const canValidate =
        validationRequise &&
        (isAdmin || isResponsable) &&
        entree.statut === 'en_attente';
    const canDelete =
        (isAdmin || isAgentParc) &&
        (!validationRequise || entree.statut !== 'validee');

    const billes = entree.billes ?? [];
    const totalCubage = billes.reduce((sum, b) => sum + Number(b.cubage), 0);
    const m3 = (value: string | number) => formatNumber(Number(value), 3);
    const metres = (value: string) => formatNumber(Number(value), 2);

    return (
        <>
            <Head title={`Entrée ${entree.numero_je}`} />

            <div className="flex h-full flex-1 flex-col gap-6 p-4 md:p-6">
                <PageHeader
                    className="mb-0"
                    title={`Entrée ${entree.numero_je}`}
                    badge={
                        validationRequise && (
                            <StatutEntreeBadge statut={entree.statut} />
                        )
                    }
                    description={`${plural(billes.length, 'bille')} · ${m3(totalCubage)} m³`}
                    actions={
                        <>
                            <Button variant="outline" asChild>
                                <Link href={index()}>
                                    <ArrowLeft />
                                    Retour
                                </Link>
                            </Button>
                            {canDelete && (
                                <ConfirmDialog
                                    trigger={
                                        <Button variant="destructive">
                                            <Trash2 />
                                            Supprimer
                                        </Button>
                                    }
                                    title={`Supprimer l'entrée ${entree.numero_je} ?`}
                                    description="L'entrée et ses billes seront supprimées. Cette action est irréversible."
                                    confirmLabel="Supprimer"
                                    onConfirm={() =>
                                        router.delete(
                                            EntreeBoisController.destroy.url(
                                                entree.id,
                                            ),
                                        )
                                    }
                                />
                            )}
                        </>
                    }
                />

                <div className="grid gap-6 lg:grid-cols-2">
                    <Card>
                        <CardHeader>
                            <CardTitle>Bordereau</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <Details
                                items={[
                                    [
                                        "Date d'entrée",
                                        formatTableDay(entree.date_entree),
                                    ],
                                    [
                                        'Bordereau, page n°',
                                        entree.numero_bordereau,
                                    ],
                                    ['Chantier', entree.chantier?.numero],
                                    ['Exploitant', entree.exploitant?.nom],
                                    [
                                        'Code exploitant',
                                        entree.exploitant?.code,
                                    ],
                                    ['Marteau', entree.exploitant?.marteau],
                                    ['Saisie par', entree.saisie_par?.name],
                                    ...(validationRequise
                                        ? ([
                                              [
                                                  entree.statut === 'rejetee'
                                                      ? 'Rejetée par'
                                                      : 'Validée par',
                                                  entree.valide_par?.name,
                                              ],
                                              [
                                                  'Date de décision',
                                                  dateTime(entree.valide_le),
                                              ],
                                          ] as [string, ReactNode][])
                                        : []),
                                ]}
                            />
                        </CardContent>
                    </Card>
                    <Card>
                        <CardHeader>
                            <CardTitle>Transport</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <Details
                                items={[
                                    ['Transporteur', entree.transporteur],
                                    ['N° du camion', entree.numero_camion],
                                    ['Chauffeur', entree.chauffeur],
                                    [
                                        'Chargement',
                                        formatTableDay(entree.date_chargement),
                                    ],
                                    [
                                        'Départ',
                                        dateTime(entree.date_heure_depart),
                                    ],
                                    [
                                        'Arrivée',
                                        dateTime(entree.date_heure_arrivee),
                                    ],
                                    ['Destination', entree.destination],
                                    ['Parc usine', entree.parc_usine],
                                ]}
                            />
                        </CardContent>
                    </Card>
                </div>

                <ResponsiveList
                    items={billes}
                    getKey={(b) => b.id!}
                    columns={[
                        {
                            header: 'N° de bille',
                            cell: (b) => (
                                <span className="font-medium">
                                    {b.numero_bille}
                                </span>
                            ),
                        },
                        { header: 'Lettre', cell: (b) => b.lettre ?? '—' },
                        {
                            header: 'Essence',
                            cell: (b) => b.essence?.nom ?? '—',
                        },
                        { header: 'Code', cell: (b) => b.essence?.code ?? '—' },
                        { header: 'Zone', cell: (b) => b.zone ?? '—' },
                        {
                            header: 'X / Y',
                            cell: (b) =>
                                `${b.coordonnee_x ?? '—'} / ${b.coordonnee_y ?? '—'}`,
                        },
                        {
                            header: 'Longueur (m)',
                            align: 'right',
                            cell: (b) => metres(b.longueur),
                        },
                        {
                            header: 'Diamètre (cm)',
                            align: 'right',
                            cell: (b) => formatNumber(Number(b.diametre)),
                        },
                        {
                            header: 'Cubage (m³)',
                            align: 'right',
                            cell: (b) => m3(b.cubage),
                        },
                    ]}
                    card={(b) => (
                        <div className="space-y-1">
                            <p className="font-medium">
                                {b.numero_bille} {b.lettre} · {b.essence?.nom}
                            </p>
                            <p className="text-sm text-muted-foreground">
                                {metres(b.longueur)} m × Ø{' '}
                                {formatNumber(Number(b.diametre))} cm ·{' '}
                                {m3(b.cubage)} m³
                            </p>
                        </div>
                    )}
                />

                {canValidate ? (
                    <ValidationCard entree={entree} />
                ) : (
                    entree.observations && (
                        <Card>
                            <CardHeader>
                                <CardTitle>Observations</CardTitle>
                            </CardHeader>
                            <CardContent className="text-sm whitespace-pre-line">
                                {entree.observations}
                            </CardContent>
                        </Card>
                    )
                )}
            </div>
        </>
    );
}

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