import { Head, Link, router } from '@inertiajs/react';
import {
    AlertTriangle,
    ArrowLeft,
    ClipboardCheck,
    Package,
} from 'lucide-react';
import InventoryController from '@/actions/App/Http/Controllers/Admin/InventoryController';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { formatDate } from '@/lib/utils';
import { dashboard } from '@/routes';
import { index as inventoriesIndex } from '@/routes/admin/inventories';
import {
    StockInventoryForm,
    type ProductOption,
} from './stock-inventory-form';

type InventoryLine = {
    id: number;
    product: { id: number; code: string; name: string } | null;
    theoretical_quantity: number;
    actual_quantity: number | null;
    variance: number | null;
    justification: string | null;
};

type Inventory = {
    id: number;
    code: string;
    status: string;
    status_label: string;
    counted_at: string | null;
    notes: string | null;
    closed_at: string | null;
    adjusted_at: string | null;
    created_at: string | null;
    warehouse: { id: number; code: string; name: string };
    creator: { id: number; name: string } | null;
    closer: { id: number; name: string } | null;
    adjuster: { id: number; name: string } | null;
    lines: InventoryLine[];
    lines_count: number;
    variance_count: number;
    adjusted_units: number;
};

function statusVariant(
    status: string,
): 'default' | 'secondary' | 'outline' | 'destructive' {
    switch (status) {
        case 'adjusted':
            return 'default';
        case 'closed':
            return 'secondary';
        case 'draft':
            return 'outline';
        case 'cancelled':
            return 'outline';
        default:
            return 'outline';
    }
}

export default function InventoriesShow({
    inventory,
    products,
    canUpdate = false,
    canClose = false,
    canApplyAdjustments = false,
    canCancel = false,
}: {
    inventory: Inventory;
    products: ProductOption[];
    canUpdate?: boolean;
    canClose?: boolean;
    canApplyAdjustments?: boolean;
    canCancel?: boolean;
}) {
    const isDraft = inventory.status === 'draft';

    function cancelInventory() {
        if (
            !window.confirm(
                "Annuler cet inventaire brouillon ? Cette action est irréversible.",
            )
        ) {
            return;
        }

        router.delete(InventoryController.destroy.url(inventory.id));
    }

    function applyAdjustments() {
        if (
            !window.confirm(
                'Appliquer les ajustements au stock selon ce constat ? Cette action mettra à jour les quantités en entrepôt.',
            )
        ) {
            return;
        }

        router.post(
            InventoryController.applyAdjustments.url(inventory.id),
        );
    }

    return (
        <>
            <Head title={inventory.code} />

            <div className="flex h-full flex-1 flex-col gap-6 p-4 md:p-6">
                <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
                    <div className="space-y-2">
                        <div className="flex flex-wrap items-center gap-2">
                            <h1 className="font-mono text-xl font-semibold tracking-tight">
                                {inventory.code}
                            </h1>
                            <Badge variant={statusVariant(inventory.status)}>
                                {inventory.status_label}
                            </Badge>
                        </div>
                        <p className="text-muted-foreground text-sm">
                            {formatDate(inventory.counted_at)}
                            <span className="mx-1.5">·</span>
                            {inventory.warehouse.name}
                        </p>
                    </div>
                    <Button variant="outline" asChild>
                        <Link href={inventoriesIndex.url()}>
                            <ArrowLeft />
                            Retour
                        </Link>
                    </Button>
                </div>

                <div className="grid gap-4 sm:grid-cols-3">
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Produits comptés</CardDescription>
                            <CardTitle className="text-2xl tabular-nums">
                                {inventory.lines_count}
                            </CardTitle>
                        </CardHeader>
                    </Card>
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Écarts détectés</CardDescription>
                            <CardTitle className="flex items-center gap-2 text-2xl tabular-nums">
                                <AlertTriangle className="size-5 text-amber-500" />
                                {inventory.variance_count}
                            </CardTitle>
                        </CardHeader>
                    </Card>
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Unités à ajuster</CardDescription>
                            <CardTitle className="flex items-center gap-2 text-2xl tabular-nums">
                                <Package className="size-5 text-muted-foreground" />
                                {inventory.adjusted_units}
                            </CardTitle>
                        </CardHeader>
                    </Card>
                </div>

                {isDraft && canUpdate ? (
                    <StockInventoryForm
                        inventoryId={inventory.id}
                        countedAt={inventory.counted_at ?? ''}
                        notes={inventory.notes}
                        lines={inventory.lines}
                        products={products}
                        canClose={canClose}
                        canCancel={canCancel}
                        onCancelInventory={cancelInventory}
                    />
                ) : (
                    <>
                        {canApplyAdjustments &&
                            inventory.status === 'closed' && (
                            <div className="flex justify-end">
                                <Button onClick={applyAdjustments}>
                                    <ClipboardCheck />
                                    Appliquer les ajustements au stock
                                </Button>
                            </div>
                        )}

                        <Card>
                            <CardHeader>
                                <CardTitle>Informations</CardTitle>
                            </CardHeader>
                            <CardContent className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                                <div>
                                    <p className="text-muted-foreground text-xs uppercase tracking-wide">
                                        Entrepôt
                                    </p>
                                    <p className="mt-1 text-sm font-medium">
                                        {inventory.warehouse.code} —{' '}
                                        {inventory.warehouse.name}
                                    </p>
                                </div>
                                <div>
                                    <p className="text-muted-foreground text-xs uppercase tracking-wide">
                                        Créé par
                                    </p>
                                    <p className="mt-1 text-sm font-medium">
                                        {inventory.creator?.name ?? '—'}
                                    </p>
                                </div>
                                <div>
                                    <p className="text-muted-foreground text-xs uppercase tracking-wide">
                                        Clôturé par
                                    </p>
                                    <p className="mt-1 text-sm font-medium">
                                        {inventory.closer?.name ?? '—'}
                                    </p>
                                </div>
                                <div>
                                    <p className="text-muted-foreground text-xs uppercase tracking-wide">
                                        Clôturé le
                                    </p>
                                    <p className="mt-1 text-sm font-medium">
                                        {inventory.closed_at
                                            ? formatDate(inventory.closed_at)
                                            : '—'}
                                    </p>
                                </div>
                                <div>
                                    <p className="text-muted-foreground text-xs uppercase tracking-wide">
                                        Ajusté par
                                    </p>
                                    <p className="mt-1 text-sm font-medium">
                                        {inventory.adjuster?.name ?? '—'}
                                    </p>
                                </div>
                                <div>
                                    <p className="text-muted-foreground text-xs uppercase tracking-wide">
                                        Ajusté le
                                    </p>
                                    <p className="mt-1 text-sm font-medium">
                                        {inventory.adjusted_at
                                            ? formatDate(inventory.adjusted_at)
                                            : '—'}
                                    </p>
                                </div>
                                {inventory.notes ? (
                                    <div className="sm:col-span-2 lg:col-span-4">
                                        <p className="text-muted-foreground text-xs uppercase tracking-wide">
                                            Notes
                                        </p>
                                        <p className="mt-1 text-sm">
                                            {inventory.notes}
                                        </p>
                                    </div>
                                ) : null}
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle>Comparaison stock</CardTitle>
                                <CardDescription>
                                    Stock théorique vs stock réel compté sur le
                                    terrain.
                                </CardDescription>
                            </CardHeader>
                            <CardContent>
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>Produit</TableHead>
                                            <TableHead className="text-right">
                                                Théorique
                                            </TableHead>
                                            <TableHead className="text-right">
                                                Réel
                                            </TableHead>
                                            <TableHead className="text-right">
                                                Écart
                                            </TableHead>
                                            <TableHead>Justification</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {inventory.lines.length === 0 ? (
                                            <TableRow>
                                                <TableCell
                                                    colSpan={5}
                                                    className="text-muted-foreground text-center"
                                                >
                                                    Aucune ligne produit.
                                                </TableCell>
                                            </TableRow>
                                        ) : (
                                            inventory.lines.map((line) => (
                                                <TableRow key={line.id}>
                                                    <TableCell>
                                                        <div className="flex flex-col gap-0.5">
                                                            <span className="font-medium">
                                                                {line.product
                                                                    ?.name ??
                                                                    '—'}
                                                            </span>
                                                            <span className="text-muted-foreground font-mono text-xs">
                                                                {line.product
                                                                    ?.code ??
                                                                    '—'}
                                                            </span>
                                                        </div>
                                                    </TableCell>
                                                    <TableCell className="text-right tabular-nums">
                                                        {
                                                            line.theoretical_quantity
                                                        }
                                                    </TableCell>
                                                    <TableCell className="text-right tabular-nums">
                                                        {line.actual_quantity ??
                                                            '—'}
                                                    </TableCell>
                                                    <TableCell className="text-right tabular-nums">
                                                        {line.variance ===
                                                            null ||
                                                        line.variance === 0 ? (
                                                            <span className="text-muted-foreground">
                                                                0
                                                            </span>
                                                        ) : (
                                                            <Badge
                                                                variant={
                                                                    line.variance >
                                                                    0
                                                                        ? 'default'
                                                                        : 'destructive'
                                                                }
                                                            >
                                                                {line.variance >
                                                                0
                                                                    ? '+'
                                                                    : ''}
                                                                {line.variance}
                                                            </Badge>
                                                        )}
                                                    </TableCell>
                                                    <TableCell className="max-w-xs text-sm">
                                                        {line.justification ??
                                                            '—'}
                                                    </TableCell>
                                                </TableRow>
                                            ))
                                        )}
                                    </TableBody>
                                </Table>
                            </CardContent>
                        </Card>

                        {inventory.status === 'closed' && (
                            <div className="flex items-center gap-2 text-sm text-muted-foreground">
                                <ClipboardCheck className="size-4" />
                                Constat clôturé — le stock n&apos;a pas encore
                                été ajusté.
                            </div>
                        )}

                        {inventory.status === 'adjusted' && (
                            <div className="flex items-center gap-2 text-sm text-muted-foreground">
                                <ClipboardCheck className="size-4" />
                                Stock ajusté selon l&apos;inventaire.
                            </div>
                        )}
                    </>
                )}
            </div>
        </>
    );
}

InventoriesShow.layout = {
    breadcrumbs: [
        { title: 'Tableau de bord', href: dashboard() },
        { title: 'Inventaires', href: inventoriesIndex.url() },
        { title: 'Détail', href: '#' },
    ],
};
