import { Head, Link } from '@inertiajs/react';
import { ArrowLeft, Boxes, History, Pencil } from 'lucide-react';
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 { formatCurrency, formatDate } from '@/lib/utils';
import { dashboard } from '@/routes';
import { edit, index } from '@/routes/admin/products';
import { index as stockMovementsIndex } from '@/routes/admin/stock-movements';

type StockByWarehouse = {
    warehouse: { id: number; code: string; name: string };
    quantity: number;
};

type Movement = {
    id: number;
    type: string;
    type_label: string;
    signed_quantity: number;
    quantity: number;
    motif: string | null;
    occurred_at: string | null;
    warehouse: { id: number; code: string; name: string } | null;
    performed_by: { id: number; name: string } | null;
    source: { type: string; label: string; id: number } | null;
};

type ProductDetail = {
    id: number;
    code: string;
    name: string;
    description: string | null;
    category: { id: number; name: string } | null;
    unit_of_measure: string;
    unit_of_measure_label: string;
    sale_price: string;
    cost_price: string;
    min_stock: number;
    is_active: boolean;
    total_quantity: number;
    stock_by_warehouse: StockByWarehouse[];
    recent_movements: Movement[];
};

export default function ProductsShow({ product }: { product: ProductDetail }) {
    const isLowStock =
        product.min_stock > 0 && product.total_quantity <= product.min_stock;

    return (
        <>
            <Head title={product.name} />

            <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="text-xl font-semibold tracking-tight">
                                {product.name}
                            </h1>
                            <Badge
                                variant={
                                    product.is_active ? 'secondary' : 'outline'
                                }
                            >
                                {product.is_active ? 'Actif' : 'Inactif'}
                            </Badge>
                            {isLowStock && (
                                <Badge variant="destructive">Stock bas</Badge>
                            )}
                        </div>
                        <p className="text-muted-foreground font-mono text-sm">
                            {product.code}
                        </p>
                    </div>
                    <div className="flex flex-wrap gap-2">
                        <Button variant="outline" asChild>
                            <Link
                                href={stockMovementsIndex.url({
                                    query: { product_id: product.id },
                                })}
                            >
                                <History />
                                Historique des mouvements
                            </Link>
                        </Button>
                        <Button variant="outline" asChild>
                            <Link href={edit(product.id)}>
                                <Pencil />
                                Modifier
                            </Link>
                        </Button>
                        <Button variant="outline" asChild>
                            <Link href={index.url()}>
                                <ArrowLeft />
                                Retour
                            </Link>
                        </Button>
                    </div>
                </div>

                <div className="grid gap-4 sm:grid-cols-3">
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>
                                Quantité en stock
                            </CardDescription>
                            <CardTitle className="flex items-center gap-2 text-2xl tabular-nums">
                                <Boxes className="size-5 text-muted-foreground" />
                                {product.total_quantity}{' '}
                                {product.unit_of_measure_label}
                            </CardTitle>
                        </CardHeader>
                    </Card>
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Prix de vente</CardDescription>
                            <CardTitle className="text-2xl tabular-nums">
                                {formatCurrency(Number(product.sale_price))}
                            </CardTitle>
                        </CardHeader>
                    </Card>
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Prix d’achat</CardDescription>
                            <CardTitle className="text-2xl tabular-nums">
                                {formatCurrency(Number(product.cost_price))}
                            </CardTitle>
                        </CardHeader>
                    </Card>
                </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">
                                Référence
                            </p>
                            <p className="mt-1 font-mono text-sm font-medium">
                                {product.code}
                            </p>
                        </div>
                        <div>
                            <p className="text-muted-foreground text-xs uppercase tracking-wide">
                                Catégorie
                            </p>
                            <p className="mt-1 text-sm font-medium">
                                {product.category?.name ?? '—'}
                            </p>
                        </div>
                        <div>
                            <p className="text-muted-foreground text-xs uppercase tracking-wide">
                                Unité de mesure
                            </p>
                            <p className="mt-1 text-sm font-medium">
                                {product.unit_of_measure_label}
                            </p>
                        </div>
                        <div>
                            <p className="text-muted-foreground text-xs uppercase tracking-wide">
                                Seuil d’alerte
                            </p>
                            <p className="mt-1 text-sm font-medium">
                                {product.min_stock > 0
                                    ? product.min_stock
                                    : 'Non configuré'}
                            </p>
                        </div>
                        {product.description ? (
                            <div className="sm:col-span-2 lg:col-span-4">
                                <p className="text-muted-foreground text-xs uppercase tracking-wide">
                                    Description
                                </p>
                                <p className="mt-1 text-sm">
                                    {product.description}
                                </p>
                            </div>
                        ) : null}
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader>
                        <CardTitle>Stock par entrepôt</CardTitle>
                        <CardDescription>
                            Quantités disponibles actuellement.
                        </CardDescription>
                    </CardHeader>
                    <CardContent>
                        {product.stock_by_warehouse.length === 0 ? (
                            <p className="text-muted-foreground py-6 text-center text-sm">
                                Aucun stock enregistré pour ce produit.
                            </p>
                        ) : (
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Entrepôt</TableHead>
                                        <TableHead className="text-right">
                                            Quantité
                                        </TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {product.stock_by_warehouse.map((row) => (
                                        <TableRow key={row.warehouse.id}>
                                            <TableCell>
                                                <div className="flex flex-col gap-0.5">
                                                    <span className="text-sm font-medium">
                                                        {row.warehouse.name}
                                                    </span>
                                                    <span className="text-muted-foreground font-mono text-xs">
                                                        {row.warehouse.code}
                                                    </span>
                                                </div>
                                            </TableCell>
                                            <TableCell className="text-right tabular-nums font-medium">
                                                {row.quantity}
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        )}
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader className="flex-row items-center justify-between space-y-0">
                        <div className="space-y-1.5">
                            <CardTitle>Historique des mouvements</CardTitle>
                            <CardDescription>
                                Les 10 mouvements les plus récents.
                            </CardDescription>
                        </div>
                        <Button variant="outline" size="sm" asChild>
                            <Link
                                href={stockMovementsIndex.url({
                                    query: { product_id: product.id },
                                })}
                            >
                                Voir tout
                            </Link>
                        </Button>
                    </CardHeader>
                    <CardContent>
                        {product.recent_movements.length === 0 ? (
                            <p className="text-muted-foreground py-6 text-center text-sm">
                                Aucun mouvement enregistré pour ce produit.
                            </p>
                        ) : (
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Date</TableHead>
                                        <TableHead>Type</TableHead>
                                        <TableHead>Entrepôt</TableHead>
                                        <TableHead className="text-right">
                                            Quantité
                                        </TableHead>
                                        <TableHead>Motif</TableHead>
                                        <TableHead>Par</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {product.recent_movements.map(
                                        (movement) => (
                                            <TableRow key={movement.id}>
                                                <TableCell className="text-sm">
                                                    {formatDate(
                                                        movement.occurred_at,
                                                    )}
                                                </TableCell>
                                                <TableCell>
                                                    <Badge variant="secondary">
                                                        {movement.type_label}
                                                    </Badge>
                                                </TableCell>
                                                <TableCell className="text-sm">
                                                    {movement.warehouse
                                                        ?.name ?? '—'}
                                                </TableCell>
                                                <TableCell className="text-right tabular-nums font-medium">
                                                    {movement.signed_quantity >
                                                    0
                                                        ? '+'
                                                        : ''}
                                                    {movement.signed_quantity}
                                                </TableCell>
                                                <TableCell className="text-muted-foreground text-sm">
                                                    {movement.motif ?? '—'}
                                                </TableCell>
                                                <TableCell className="text-sm">
                                                    {movement.performed_by
                                                        ?.name ?? '—'}
                                                </TableCell>
                                            </TableRow>
                                        ),
                                    )}
                                </TableBody>
                            </Table>
                        )}
                    </CardContent>
                </Card>
            </div>
        </>
    );
}

ProductsShow.layout = {
    breadcrumbs: [
        { title: 'Tableau de bord', href: dashboard() },
        { title: 'Produits', href: index() },
        { title: 'Détail', href: '#' },
    ],
};
