import { Head, router } from '@inertiajs/react';
import { Printer } from 'lucide-react';
import { useState } from 'react';
import type { ReactNode } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { cn, formatNumber, plural } from '@/lib/utils';
import { dashboard } from '@/routes';
import { entrees as journalEntrees } from '@/routes/journal';

type Ligne = {
    id: number;
    perimetre: string | null;
    origine: string | null;
    code_exploitant: string | null;
    marteau: string | null;
    page_bordereau: string | null;
    date_dechargement: string;
    numero_bille: string;
    zone: string | null;
    x: number | null;
    y: number | null;
    lettre: string | null;
    essence: string;
    code_essence: string;
    longueur: number;
    diametre: number;
    cubage: number;
};

/** Nombre de lignes d'une page du livre officiel. */
const LIGNES_PAR_PAGE = 15;

const TOTAUX = [
    ['foret_naturelle_pef', 'VOLUME BOIS DE FORETS NATURELLES DE PEF'],
    ['foret_naturelle_fc', 'VOLUME BOIS DE FORETS NATURELLES FC'],
    ['plantation_rurale', 'VOLUME BOIS DE PLANTATIONS DU DOMAINE RURAL'],
    ['plantation_fc', 'VOLUME BOIS DE PLANTATIONS ISSUS DE FC'],
] as const;

/** Largeurs des colonnes, en pourcentage de la page. */
const COLONNES = [2.5, 10.5, 5, 6, 8.5, 7, 7, 4, 5.5, 5.5, 3, 9, 5, 7, 4.5, 7];

const decimal = (value: number, decimals: number) =>
    value.toFixed(decimals).replace('.', ',');

/** Peigne de saisie : une case par caractère, comme sur l'imprimé. */
function Peigne({ valeur, cases }: { valeur?: string | null; cases: number }) {
    const caracteres = (valeur ?? '').split('');

    return (
        <span className="inline-flex justify-center align-bottom">
            {Array.from(
                { length: Math.max(cases, caracteres.length) },
                (_, i) => (
                    <span
                        key={i}
                        className="inline-block h-[15px] w-[10px] border-b border-l border-black text-center leading-[15px] last:border-r"
                    >
                        {caracteres[i]}
                    </span>
                ),
            )}
        </span>
    );
}

function Th({
    children,
    className,
    ...props
}: React.ComponentProps<'th'> & { children?: ReactNode }) {
    return (
        <th
            className={cn(
                'border border-black px-0.5 py-0.5 text-center align-middle text-[8px] leading-tight font-normal',
                className,
            )}
            {...props}
        >
            {children}
        </th>
    );
}

function Td({ children }: { children?: ReactNode }) {
    return (
        <td className="h-[25px] overflow-hidden border border-black px-0.5 text-center align-middle whitespace-nowrap">
            {children}
        </td>
    );
}

/** À l'impression, seules les feuilles restent : ni menu, ni fil d'Ariane. */
const STYLE_IMPRESSION = `
@page { size: A4 landscape; margin: 7mm; }
@media print {
    [data-slot='sidebar'], [data-slot='sidebar-inset'] > header { display: none !important; }
    [data-slot='sidebar-wrapper'], [data-slot='sidebar-inset'] {
        display: block !important;
        min-height: 0 !important;
        margin: 0 !important;
        overflow: visible !important;
        background: white !important;
        box-shadow: none !important;
    }
}
`;

type Entete = {
    ljeNumero: string;
    pageNumero: string;
    usine: string;
    localite: string;
    code: string;
};

function Feuille({
    lignes,
    rang,
    mois,
    entete,
    aucuneEntree,
}: {
    lignes: Ligne[];
    rang: number;
    mois: string;
    entete: Entete;
    aucuneEntree: boolean;
}) {
    const [annee, numeroMois] = mois.split('-');
    const premierePage = Number(entete.pageNumero);
    const page = premierePage
        ? String(premierePage + rang).padStart(entete.pageNumero.length, '0')
        : '';
    const pointilles = 'inline-block border-b border-dotted border-black px-2';

    return (
        <section className="w-full min-w-[960px] bg-white p-3 font-sans text-[10px] text-black print:min-w-0 print:p-0 [&:not(:last-child)]:break-after-page">
            <div className="relative flex min-h-9 items-center justify-center border-b border-black pb-1">
                <span className="absolute left-0 rounded-full border border-black px-2 py-1 text-sm font-bold">
                    LJE
                </span>
                <h2 className="text-lg font-bold tracking-wide">
                    LIVRE JOURNAL DES ENTREES
                </h2>
            </div>

            <div className="grid grid-cols-3 gap-4 py-1.5 font-bold">
                <div className="space-y-1">
                    <p className="text-sm">
                        LJE N°{' '}
                        <span className={cn(pointilles, 'min-w-24')}>
                            {entete.ljeNumero}
                        </span>{' '}
                        / {annee.slice(2)}
                    </p>
                    <p>
                        Année <Peigne valeur={annee} cases={4} />
                    </p>
                    <p>
                        Nom Usine :{' '}
                        <span className={cn(pointilles, 'min-w-48')}>
                            {entete.usine}
                        </span>
                    </p>
                </div>
                <div className="space-y-1">
                    <p className="text-sm">
                        PAGE N°{' '}
                        <span className={cn(pointilles, 'min-w-24')}>
                            {page}
                        </span>
                    </p>
                    <p>
                        <span className="inline-block w-10">Mois</span>
                        <Peigne valeur={numeroMois} cases={2} />
                    </p>
                    <p>
                        <span className="inline-block w-10">Code</span>
                        <Peigne valeur={entete.code} cases={3} />
                    </p>
                </div>
                <div className="space-y-1">
                    <p>
                        Mettre code 1 si aucune{' '}
                        <Peigne valeur={aucuneEntree ? '1' : ''} cases={1} />
                    </p>
                    <p>entrée dans le mois</p>
                    <p>
                        Localité :{' '}
                        <span className={cn(pointilles, 'min-w-48')}>
                            {entete.localite}
                        </span>
                    </p>
                </div>
            </div>

            <table className="w-full table-fixed border-collapse">
                <colgroup>
                    {COLONNES.map((largeur, i) => (
                        <col key={i} style={{ width: `${largeur}%` }} />
                    ))}
                </colgroup>
                <thead>
                    <tr>
                        <Th rowSpan={3}>N°</Th>
                        <Th colSpan={3} className="text-[10px] font-bold">
                            IDENTIFIANT DE L'ATTRIBUTAIRE
                        </Th>
                        <Th colSpan={3} className="text-[10px] font-bold">
                            MARQUES DE LA BILLE
                        </Th>
                        <Th colSpan={3} rowSpan={2}>
                            COORDONNÉES CARTESIENNES (UTM)
                        </Th>
                        <Th colSpan={6} className="text-[10px] font-bold">
                            CARACTERISTIQUES DE LA BILLE
                        </Th>
                    </tr>
                    <tr>
                        <Th rowSpan={2}>Périmètre / FC</Th>
                        <Th colSpan={2}>EXPLOITANT / INDUSTRIEL DU BOIS</Th>
                        <Th rowSpan={2}>N° page BCBGFH / BTGU / AUTRES</Th>
                        <Th rowSpan={2}>Date Déchargement</Th>
                        <Th rowSpan={2}>
                            Numéro Arbre / nature produits de bois
                        </Th>
                        <Th rowSpan={2}>Lettre Bille</Th>
                        <Th rowSpan={2}>Nom Essence</Th>
                        <Th rowSpan={2}>Code Essence</Th>
                        <Th rowSpan={2}>Longueur m / nombre</Th>
                        <Th rowSpan={2}>Diamètre cm</Th>
                        <Th rowSpan={2}>Volume m³</Th>
                    </tr>
                    <tr>
                        <Th>Code exploitant / Code industriel</Th>
                        <Th>Marteau</Th>
                        <Th>Zone / H</Th>
                        <Th>X</Th>
                        <Th>Y</Th>
                    </tr>
                </thead>
                <tbody>
                    {Array.from({ length: LIGNES_PAR_PAGE }, (_, i) => {
                        const l = lignes[i];

                        return (
                            <tr key={i}>
                                <Td>{i + 1}</Td>
                                <Td>{l?.perimetre}</Td>
                                <Td>{l?.code_exploitant}</Td>
                                <Td>{l?.marteau}</Td>
                                <Td>{l?.page_bordereau}</Td>
                                <Td>{l?.date_dechargement}</Td>
                                <Td>{l?.numero_bille}</Td>
                                <Td>{l?.zone}</Td>
                                <Td>{l?.x}</Td>
                                <Td>{l?.y}</Td>
                                <Td>{l?.lettre}</Td>
                                <Td>{l?.essence}</Td>
                                <Td>{l?.code_essence}</Td>
                                <Td>{l && decimal(l.longueur, 2)}</Td>
                                <Td>{l && String(l.diametre)}</Td>
                                <Td>{l && decimal(l.cubage, 3)}</Td>
                            </tr>
                        );
                    })}
                </tbody>
            </table>

            <div className="mt-2 flex flex-col items-end gap-1 font-bold">
                {TOTAUX.map(([origine, libelle]) => {
                    const total = lignes
                        .filter((l) => l.origine === origine)
                        .reduce((sum, l) => sum + l.cubage, 0);

                    return (
                        <p key={origine} className="flex items-end gap-2">
                            {libelle}
                            <Peigne
                                valeur={total ? decimal(total, 3) : ''}
                                cases={7}
                            />
                        </p>
                    );
                })}
            </div>
        </section>
    );
}

export default function JournalEntrees({
    mois,
    lignes,
    usine,
    localite,
}: {
    mois: string;
    lignes: Ligne[];
    usine: string;
    localite: string;
}) {
    const [saisie, setSaisie] = useState<Partial<Entete>>({});
    const entete: Entete = {
        ljeNumero: '',
        pageNumero: '',
        code: '',
        usine,
        localite,
        ...saisie,
    };

    const pages = Array.from(
        { length: Math.max(1, Math.ceil(lignes.length / LIGNES_PAR_PAGE)) },
        (_, i) => lignes.slice(i * LIGNES_PAR_PAGE, (i + 1) * LIGNES_PAR_PAGE),
    );
    const total = lignes.reduce((sum, l) => sum + l.cubage, 0);
    const sansOrigine = lignes.filter((l) => !l.origine).length;

    const champ = (name: keyof Entete, label: string) => (
        <div className="grid gap-1">
            <Label htmlFor={name}>{label}</Label>
            <Input
                id={name}
                value={entete[name]}
                onChange={(e) =>
                    setSaisie({ ...saisie, [name]: e.target.value })
                }
                className="w-40 bg-card"
            />
        </div>
    );

    return (
        <>
            <Head title="Journal des entrées" />
            <style>{STYLE_IMPRESSION}</style>

            <div className="flex min-w-0 flex-1 flex-col print:block print:bg-white">
                <div className="space-y-3 border-b bg-background p-4 print:hidden">
                    <div className="flex flex-wrap items-end gap-3">
                        <div className="grid gap-1">
                            <Label htmlFor="mois">Mois</Label>
                            <Input
                                id="mois"
                                type="month"
                                value={mois}
                                onChange={(e) =>
                                    e.target.value &&
                                    router.get(
                                        journalEntrees.url(),
                                        { mois: e.target.value },
                                        { preserveState: false },
                                    )
                                }
                                className="w-44 bg-card"
                            />
                        </div>
                        {champ('ljeNumero', 'LJE n°')}
                        {champ('pageNumero', 'Première page n°')}
                        {champ('usine', 'Nom usine')}
                        {champ('code', 'Code')}
                        {champ('localite', 'Localité')}
                        <Button onClick={() => window.print()}>
                            <Printer />
                            Imprimer / PDF
                        </Button>
                    </div>
                    <p className="text-sm text-muted-foreground">
                        {plural(lignes.length, 'bille')} ·{' '}
                        {formatNumber(total, 3)} m³ dans le mois ·{' '}
                        {plural(pages.length, 'page')}
                    </p>
                    {sansOrigine > 0 && (
                        <p className="text-sm text-destructive">
                            {plural(sansOrigine, 'bille')} sans origine du bois
                            : renseignez-la sur le chantier pour qu'elle compte
                            dans les totaux de volume.
                        </p>
                    )}
                </div>

                <div className="space-y-3 overflow-x-auto print:space-y-0 print:overflow-visible">
                    {pages.map((page, i) => (
                        <Feuille
                            key={i}
                            rang={i}
                            lignes={page}
                            mois={mois}
                            entete={entete}
                            aucuneEntree={lignes.length === 0}
                        />
                    ))}
                </div>
            </div>
        </>
    );
}

JournalEntrees.layout = {
    breadcrumbs: [
        { title: 'Tableau de bord', href: dashboard() },
        { title: 'Journal des entrées', href: journalEntrees() },
    ],
};
