import { Head, Link, router } from '@inertiajs/react';
import { ArrowLeft, Building2, Pencil, Printer } from 'lucide-react';
import { useState } from 'react';
import PurchaseOrderController from '@/actions/App/Http/Controllers/Admin/PurchaseOrderController';
import { ConfirmDialog } from '@/components/confirm-dialog';
import Heading from '@/components/heading';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { useCan } from '@/hooks/use-can';
import { cn, formatCurrency, formatDate } from '@/lib/utils';
import { dashboard } from '@/routes';
import { edit, index, pdf } from '@/routes/admin/purchase-orders';
import { create as createFixedAsset } from '@/routes/admin/fixed-assets';
import { PurchaseOrderStatusBadge } from './status-badge';
import { SupplierInvoiceStatusBadge } from '@/pages/admin/supplier-invoices/status-badge';

type Line = {
    id: number;
    product: { id: number; code: string; name: string } | null;
    description: string;
    quantity: string | number;
    unit_price: string | number;
    line_total: string | number;
};

type SupplierInvoice = {
    id: number;
    code: string;
    reference: string;
    amount: string | number;
    is_fixed_asset: boolean;
    due_date: string | null;
    status: string;
    status_label: string;
    paid_at: string | null;
    payer: { id: number; name: string } | null;
};

type Order = {
    id: number;
    code: string;
    supplier: { id: number; code: string; name: string } | null;
    creator: { id: number; name: string } | null;
    status: string;
    status_label: string;
    order_date: string | null;
    expected_delivery_date: string | null;
    invoice_due_date: string | null;
    total_amount: string | number;
    notes: string | null;
    validated_at: string | null;
    delivered_at: string | null;
    invoiced_at: string | null;
    cancelled_at: string | null;
    supplier_invoice: SupplierInvoice | null;
    lines: Line[];
};

type Transition = { value: string; label: string };
type WarehouseOption = { id: number; code: string; name: string };

export default function PurchaseOrdersShow({
    order,
    transitions,
    warehouses = [],
    can,
}: {
    order: Order;
    transitions: Transition[];
    warehouses?: WarehouseOption[];
    can: { recordSupplierInvoicePayment: boolean; createFixedAsset: boolean };
}) {
    const canUpdate = useCan('purchase-orders.update');
    const canValidate = useCan('purchase-orders.validate');
    const showStatusActions = canValidate && transitions.length > 0;
    const [deliveryOpen, setDeliveryOpen] = useState(false);
    const [warehouseId, setWarehouseId] = useState<string>('');
    const [deliveryError, setDeliveryError] = useState<string | null>(null);
    const [invoiceOpen, setInvoiceOpen] = useState(false);
    const [invoiceReference, setInvoiceReference] = useState('');
    const [invoiceAmount, setInvoiceAmount] = useState('');
    const [invoiceDueDate, setInvoiceDueDate] = useState('');
    const [invoiceIsFixedAsset, setInvoiceIsFixedAsset] = useState(false);
    const [invoiceErrors, setInvoiceErrors] = useState<
        Record<string, string>
    >({});

    function changeStatus(status: string) {
        if (status === 'delivered') {
            setWarehouseId('');
            setDeliveryError(null);
            setDeliveryOpen(true);
            return;
        }

        if (status === 'invoiced') {
            setInvoiceReference('');
            setInvoiceAmount(String(order.total_amount));
            setInvoiceDueDate('');
            setInvoiceIsFixedAsset(false);
            setInvoiceErrors({});
            setInvoiceOpen(true);
            return;
        }

        router.put(
            PurchaseOrderController.updateStatus.url(order.id),
            { status },
            { preserveScroll: true },
        );
    }

    function confirmInvoicing() {
        router.put(
            PurchaseOrderController.updateStatus.url(order.id),
            {
                status: 'invoiced',
                reference: invoiceReference,
                amount: invoiceAmount,
                due_date: invoiceDueDate,
                is_fixed_asset: invoiceIsFixedAsset,
            },
            {
                preserveScroll: true,
                onSuccess: () => setInvoiceOpen(false),
                onError: (errors) => setInvoiceErrors(errors),
            },
        );
    }

    function markSupplierInvoiceAsPaid() {
        router.post(
            PurchaseOrderController.markSupplierInvoiceAsPaid.url(order.id),
            {},
            { preserveScroll: true },
        );
    }

    function cancelSupplierInvoice() {
        router.post(
            PurchaseOrderController.cancelSupplierInvoice.url(order.id),
            {},
            { preserveScroll: true },
        );
    }

    function confirmDelivery() {
        if (!warehouseId) {
            setDeliveryError('Veuillez sélectionner un entrepôt.');
            return;
        }

        router.put(
            PurchaseOrderController.updateStatus.url(order.id),
            {
                status: 'delivered',
                warehouse_id: Number(warehouseId),
            },
            {
                preserveScroll: true,
                onSuccess: () => setDeliveryOpen(false),
                onError: (errors) => {
                    setDeliveryError(
                        errors.warehouse_id ??
                            errors.status ??
                            'Impossible de livrer la commande.',
                    );
                },
            },
        );
    }

    return (
        <>
            <Head title={order.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">
                    <Heading
                        title={`Commande ${order.code}`}
                        description={
                            order.supplier?.name ?? 'Fournisseur inconnu'
                        }
                    />
                    <div className="flex flex-wrap gap-2">
                        <Button variant="outline" asChild>
                            <Link href={index()}>
                                <ArrowLeft />
                                Retour
                            </Link>
                        </Button>
                        <Button variant="outline" asChild>
                            <a
                                href={pdf(order.id).url}
                                target="_blank"
                                rel="noopener noreferrer"
                            >
                                <Printer />
                                Imprimer (PDF)
                            </a>
                        </Button>
                        {canUpdate &&
                            order.status !== 'invoiced' &&
                            order.status !== 'cancelled' && (
                            <Button variant="outline" asChild>
                                <Link href={edit(order.id)}>
                                    <Pencil />
                                    Modifier
                                </Link>
                            </Button>
                        )}
                    </div>
                </div>

                {showStatusActions && (
                    <Card className="border-border/60 bg-muted/40 shadow-none">
                        <CardHeader className="pb-3">
                            <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                                <div className="space-y-1">
                                    <CardTitle className="text-base">
                                        Changer le statut
                                    </CardTitle>
                                    <CardDescription>
                                        Faites évoluer la commande vers
                                        l&apos;étape suivante.
                                    </CardDescription>
                                </div>
                                <div className="flex items-center gap-2">
                                    <span className="text-sm text-muted-foreground">
                                        Actuel
                                    </span>
                                    <PurchaseOrderStatusBadge
                                        status={order.status}
                                        label={order.status_label}
                                    />
                                </div>
                            </div>
                        </CardHeader>
                        <CardContent>
                            <div className="flex flex-col gap-2 sm:flex-row sm:flex-wrap">
                                {transitions.map((transition) => {
                                    const isCancel =
                                        transition.value === 'cancelled';

                                    return (
                                        <Button
                                            key={transition.value}
                                            size="lg"
                                            variant={
                                                isCancel
                                                    ? 'destructive'
                                                    : 'default'
                                            }
                                            className={cn(
                                                'sm:min-w-[11rem]',
                                                !isCancel &&
                                                    'bg-primary text-primary-foreground hover:bg-primary/90',
                                            )}
                                            onClick={() =>
                                                changeStatus(transition.value)
                                            }
                                        >
                                            {transition.label}
                                        </Button>
                                    );
                                })}
                            </div>
                        </CardContent>
                    </Card>
                )}

                <div className="grid gap-6 lg:grid-cols-3">
                    <Card className="lg:col-span-2">
                        <CardHeader>
                            <CardTitle>Lignes</CardTitle>
                        </CardHeader>
                        <CardContent>
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Produit</TableHead>
                                        <TableHead>Description</TableHead>
                                        <TableHead className="text-right">
                                            Qté
                                        </TableHead>
                                        <TableHead className="text-right">
                                            P.U.
                                        </TableHead>
                                        <TableHead className="text-right">
                                            Total
                                        </TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {order.lines.map((line) => (
                                        <TableRow key={line.id}>
                                            <TableCell className="text-muted-foreground">
                                                {line.product?.code ?? '—'}
                                            </TableCell>
                                            <TableCell>
                                                {line.description}
                                            </TableCell>
                                            <TableCell className="text-right tabular-nums">
                                                {line.quantity}
                                            </TableCell>
                                            <TableCell className="text-right tabular-nums">
                                                {formatCurrency(line.unit_price)}
                                            </TableCell>
                                            <TableCell className="text-right tabular-nums">
                                                {formatCurrency(line.line_total)}
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                    <TableRow>
                                        <TableCell
                                            colSpan={4}
                                            className="text-right font-medium"
                                        >
                                            Total
                                        </TableCell>
                                        <TableCell className="text-right font-semibold tabular-nums">
                                            {formatCurrency(order.total_amount)}
                                        </TableCell>
                                    </TableRow>
                                </TableBody>
                            </Table>

                            {order.notes && (
                                <div className="mt-4 rounded-lg bg-muted/40 p-3 text-sm">
                                    <p className="font-medium">Notes</p>
                                    <p className="text-muted-foreground">
                                        {order.notes}
                                    </p>
                                </div>
                            )}
                        </CardContent>
                    </Card>

                    <div className="space-y-6">
                        <Card>
                            <CardHeader>
                                <CardTitle>Informations</CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-3 text-sm">
                                <div className="flex items-center justify-between">
                                    <span className="text-muted-foreground">
                                        Statut
                                    </span>
                                    <PurchaseOrderStatusBadge
                                        status={order.status}
                                        label={order.status_label}
                                    />
                                </div>
                                <InfoRow
                                    label="Fournisseur"
                                    value={order.supplier?.name ?? '—'}
                                />
                                <InfoRow
                                    label="Date de commande"
                                    value={formatDate(order.order_date)}
                                />
                                <InfoRow
                                    label="Livraison prévue"
                                    value={formatDate(
                                        order.expected_delivery_date,
                                    )}
                                />
                                <InfoRow
                                    label="Échéance facturation"
                                    value={formatDate(order.invoice_due_date)}
                                />
                                <InfoRow
                                    label="Créée par"
                                    value={order.creator?.name ?? '—'}
                                />
                            </CardContent>
                        </Card>

                        <Card>
                            <CardHeader>
                                <CardTitle>Suivi</CardTitle>
                            </CardHeader>
                            <CardContent className="space-y-3 text-sm">
                                <InfoRow
                                    label="Validée le"
                                    value={formatDate(order.validated_at)}
                                />
                                <InfoRow
                                    label="Livrée le"
                                    value={formatDate(order.delivered_at)}
                                />
                                <InfoRow
                                    label="Facturée le"
                                    value={formatDate(order.invoiced_at)}
                                />
                                {order.cancelled_at && (
                                    <InfoRow
                                        label="Annulée le"
                                        value={formatDate(order.cancelled_at)}
                                    />
                                )}
                            </CardContent>
                        </Card>

                        {order.supplier_invoice && (
                            <Card>
                                <CardHeader>
                                    <CardTitle>Facture fournisseur</CardTitle>
                                </CardHeader>
                                <CardContent className="space-y-3 text-sm">
                                    <div className="flex items-center justify-between">
                                        <span className="text-muted-foreground">
                                            Statut
                                        </span>
                                        <SupplierInvoiceStatusBadge
                                            status={
                                                order.supplier_invoice.status
                                            }
                                            label={
                                                order.supplier_invoice
                                                    .status_label
                                            }
                                        />
                                    </div>
                                    <InfoRow
                                        label="Référence"
                                        value={order.supplier_invoice.reference}
                                    />
                                    <InfoRow
                                        label="Montant"
                                        value={formatCurrency(
                                            order.supplier_invoice.amount,
                                        )}
                                    />
                                    <InfoRow
                                        label="Échéance"
                                        value={formatDate(
                                            order.supplier_invoice.due_date,
                                        )}
                                    />
                                    {order.supplier_invoice.is_fixed_asset && (
                                        <InfoRow
                                            label="Type"
                                            value="Immobilisation"
                                        />
                                    )}
                                    {can.createFixedAsset && (
                                        <Button variant="outline" className="w-full" asChild>
                                            <Link
                                                href={createFixedAsset.url({
                                                    query: {
                                                        supplier_invoice_id:
                                                            order.supplier_invoice.id,
                                                    },
                                                })}
                                            >
                                                <Building2 />
                                                Créer une immobilisation
                                            </Link>
                                        </Button>
                                    )}
                                    {order.supplier_invoice.paid_at && (
                                        <InfoRow
                                            label="Payée le"
                                            value={formatDate(
                                                order.supplier_invoice.paid_at,
                                            )}
                                        />
                                    )}
                                    {order.supplier_invoice.payer && (
                                        <InfoRow
                                            label="Payée par"
                                            value={
                                                order.supplier_invoice.payer
                                                    .name
                                            }
                                        />
                                    )}
                                    {can.recordSupplierInvoicePayment &&
                                        order.supplier_invoice.status ===
                                            'pending' && (
                                            <div className="flex flex-col gap-2">
                                                <Button
                                                    className="w-full"
                                                    onClick={
                                                        markSupplierInvoiceAsPaid
                                                    }
                                                >
                                                    Marquer comme payée
                                                </Button>
                                                <ConfirmDialog
                                                    trigger={
                                                        <Button
                                                            variant="outline"
                                                            className="w-full"
                                                        >
                                                            Annuler la facture
                                                        </Button>
                                                    }
                                                    title="Annuler cette facture fournisseur ?"
                                                    description="La facture ne sera plus considérée comme à payer."
                                                    confirmLabel="Annuler la facture"
                                                    onConfirm={
                                                        cancelSupplierInvoice
                                                    }
                                                />
                                            </div>
                                        )}
                                </CardContent>
                            </Card>
                        )}
                    </div>
                </div>
            </div>

            <Dialog open={deliveryOpen} onOpenChange={setDeliveryOpen}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Confirmer la livraison</DialogTitle>
                        <DialogDescription>
                            Sélectionnez l&apos;entrepôt qui reçoit la
                            marchandise. Une réception de stock sera créée
                            automatiquement.
                        </DialogDescription>
                    </DialogHeader>
                    <div className="grid gap-2">
                        <Label>Entrepôt</Label>
                        <Select
                            value={warehouseId || undefined}
                            onValueChange={(value) => {
                                setWarehouseId(value);
                                setDeliveryError(null);
                            }}
                        >
                            <SelectTrigger>
                                <SelectValue placeholder="Choisir un entrepôt" />
                            </SelectTrigger>
                            <SelectContent>
                                {warehouses.map((warehouse) => (
                                    <SelectItem
                                        key={warehouse.id}
                                        value={String(warehouse.id)}
                                    >
                                        {warehouse.code} — {warehouse.name}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        {deliveryError && (
                            <p className="text-destructive text-sm">
                                {deliveryError}
                            </p>
                        )}
                    </div>
                    <DialogFooter>
                        <Button
                            variant="outline"
                            onClick={() => setDeliveryOpen(false)}
                        >
                            Annuler
                        </Button>
                        <Button onClick={confirmDelivery}>
                            Confirmer la livraison
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <Dialog open={invoiceOpen} onOpenChange={setInvoiceOpen}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Confirmer la facturation</DialogTitle>
                        <DialogDescription>
                            Saisissez les informations de la facture reçue du
                            fournisseur.
                        </DialogDescription>
                    </DialogHeader>
                    <div className="grid gap-4">
                        <div className="grid gap-2">
                            <Label htmlFor="invoice_reference">
                                Référence de la facture
                            </Label>
                            <Input
                                id="invoice_reference"
                                value={invoiceReference}
                                onChange={(e) =>
                                    setInvoiceReference(e.target.value)
                                }
                                placeholder="FACT-2026-001"
                            />
                            {invoiceErrors.reference && (
                                <p className="text-destructive text-sm">
                                    {invoiceErrors.reference}
                                </p>
                            )}
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="invoice_amount">Montant</Label>
                            <Input
                                id="invoice_amount"
                                type="number"
                                min="0.01"
                                step="0.01"
                                value={invoiceAmount}
                                onChange={(e) =>
                                    setInvoiceAmount(e.target.value)
                                }
                            />
                            {invoiceErrors.amount && (
                                <p className="text-destructive text-sm">
                                    {invoiceErrors.amount}
                                </p>
                            )}
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="invoice_due_date">
                                Échéance de paiement
                            </Label>
                            <Input
                                id="invoice_due_date"
                                type="date"
                                value={invoiceDueDate}
                                onChange={(e) =>
                                    setInvoiceDueDate(e.target.value)
                                }
                            />
                            {invoiceErrors.due_date && (
                                <p className="text-destructive text-sm">
                                    {invoiceErrors.due_date}
                                </p>
                            )}
                        </div>
                        <div className="flex items-center gap-2">
                            <Checkbox
                                id="invoice_is_fixed_asset"
                                checked={invoiceIsFixedAsset}
                                onCheckedChange={(checked) =>
                                    setInvoiceIsFixedAsset(checked === true)
                                }
                            />
                            <Label htmlFor="invoice_is_fixed_asset">
                                Facture d'immobilisation (comptes 218 / 4454)
                            </Label>
                        </div>
                        {invoiceErrors.status && (
                            <p className="text-destructive text-sm">
                                {invoiceErrors.status}
                            </p>
                        )}
                    </div>
                    <DialogFooter>
                        <Button
                            variant="outline"
                            onClick={() => setInvoiceOpen(false)}
                        >
                            Annuler
                        </Button>
                        <Button onClick={confirmInvoicing}>
                            Confirmer la facturation
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </>
    );
}

function InfoRow({ label, value }: { label: string; value: string }) {
    return (
        <div className="flex items-center justify-between gap-4">
            <span className="text-muted-foreground">{label}</span>
            <span className="text-right font-medium">{value}</span>
        </div>
    );
}

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