/**
 * 查看進貨單詳情頁面
 */

import { ArrowLeft, Package } from "lucide-react";
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link, usePage, useForm } from "@inertiajs/react";
import { useState } from "react";
import GoodsReceiptStatusBadge from "@/Components/Inventory/GoodsReceiptStatusBadge";

import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/Components/ui/table";
import {
    AlertDialog,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from "@/Components/ui/alert-dialog";
import { formatCurrency, formatDate, formatDateTime } from "@/utils/format";
import { PageProps } from "@/types/global";
import { toast } from "sonner";

// ... (省略中間介面定義)

interface GoodsReceiptItem {
    id: number;
    product_id: number;
    product: {
        id: number;
        name: string;
        code: string;
        baseUnit?: {
            name: string;
        };
    };
    quantity_received: string | number;
    unit_price: string | number;
    total_amount: string | number;
    batch_number?: string;
    expiry_date?: string;
}

interface GoodsReceipt {
    id: number;
    code: string;
    type: string;
    received_date: string;
    status: string;
    remark?: string;
    warehouse?: {
        name: string;
    };
    vendor?: {
        name: string;
    };
    items: GoodsReceiptItem[];
    items_sum_total_amount: number;
    created_at: string;
}

interface Props {
    receipt: GoodsReceipt;
    navigation?: {
        from?: string;
        from_id?: string;
        from_label?: string;
    };
}

export default function ViewGoodsReceiptPage({ receipt, navigation }: Props) {
    const typeMap: Record<string, string> = {
        standard: "標準採購進貨",
        miscellaneous: "雜項入庫",
        other: "其他入庫",
    };

    const breadcrumbs: any[] = [
        { label: "庫存管理", href: "#" },
        { label: "進貨單管理", href: route("goods-receipts.index") },
    ];

    let backUrl = route("goods-receipts.index");
    let backLabel = "返回進貨單列表";

    if (navigation?.from === 'account-payables' && navigation.from_id) {
        breadcrumbs.push({
            label: `應付帳款: ${navigation.from_label || navigation.from_id}`,
            href: route('account-payables.show', [navigation.from_id])
        });
        backUrl = route('account-payables.show', [navigation.from_id]);
        backLabel = `返回應付帳款 (${navigation.from_label || navigation.from_id})`;
    }

    breadcrumbs.push({ label: `單據詳情 (#${receipt.code})`, isPage: true });

    return (
        <AuthenticatedLayout breadcrumbs={breadcrumbs}>
            <Head title={`進貨單詳情 - ${receipt.code}`} />
            <div className="container mx-auto p-6 max-w-7xl">
                {/* Header */}
                <div className="mb-6">
                    <Link href={backUrl}>
                        <Button
                            variant="outline"
                            className="gap-2 button-outlined-primary"
                        >
                            <ArrowLeft className="h-4 w-4" />
                            {backLabel}
                        </Button>
                    </Link>
                </div>

                {/* 頁面標題與操作 */}
                <div className="flex flex-col md:flex-row md:items-start justify-between gap-4 mb-6">
                    <div className="space-y-2">
                        <div className="flex items-center gap-2">
                            <h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
                                <Package className="h-6 w-6 text-primary-main" />
                                進貨單: {receipt.code}
                            </h1>
                            <GoodsReceiptStatusBadge status={receipt.status} />
                        </div>
                        <p className="text-sm text-gray-500 font-medium flex flex-wrap items-center gap-2">
                            入庫類型: {typeMap[receipt.type] || receipt.type} <span className="mx-1">|</span>
                            倉庫: {receipt.warehouse?.name || "-"} <span className="mx-1">|</span>
                            供應商: {receipt.vendor?.name || "-"} <span className="mx-1">|</span>
                            進貨日期: {formatDate(receipt.received_date)}
                        </p>
                    </div>
                    <div className="flex flex-wrap items-center gap-2">
                        <GoodsReceiptActions receipt={receipt} />
                    </div>
                </div>

                <div className="grid grid-cols-1 gap-8">
                    {/* 進階資訊卡片 */}
                    <div className="bg-white rounded-lg border shadow-sm p-6">
                        <h2 className="text-lg font-bold text-gray-900 mb-6 border-b pb-4">進階資訊</h2>
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-6">
                            <div>
                                <span className="text-sm text-gray-500 block mb-1">建立時間</span>
                                <span className="font-medium text-gray-900">{formatDateTime(receipt.created_at)}</span>
                            </div>
                        </div>
                        {receipt.remark && (
                            <div className="mt-8 pt-6 border-t border-gray-100">
                                <span className="text-sm text-gray-500 block mb-2">備註</span>
                                <p className="text-sm text-gray-700 bg-gray-50 p-4 rounded-lg leading-relaxed">
                                    {receipt.remark}
                                </p>
                            </div>
                        )}
                    </div>

                    {/* 品項清單卡片 */}
                    <div className="bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
                        <div className="p-6 border-b border-gray-100 bg-gray-50/30">
                            <h2 className="text-lg font-bold text-gray-900">進貨品項清單</h2>
                        </div>
                        <div className="p-6">
                            <div className="border rounded-lg overflow-hidden">
                                <Table>
                                    <TableHeader>
                                        <TableRow className="bg-gray-50 hover:bg-gray-50">
                                            <TableHead className="w-[80px] text-center">#</TableHead>
                                            <TableHead>商品名稱</TableHead>
                                            <TableHead className="text-right">進貨數量</TableHead>
                                            <TableHead className="text-center">單位</TableHead>
                                            <TableHead className="text-right">單價</TableHead>
                                            <TableHead className="text-right">小計</TableHead>
                                            <TableHead>批號</TableHead>
                                            <TableHead>效期</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {receipt.items.length === 0 ? (
                                            <TableRow>
                                                <TableCell colSpan={8} className="h-24 text-center text-gray-500">
                                                    無品項資料
                                                </TableCell>
                                            </TableRow>
                                        ) : (
                                            receipt.items.map((item, index) => (
                                                <TableRow key={item.id}>
                                                    <TableCell className="text-center text-gray-500">{index + 1}</TableCell>
                                                    <TableCell>
                                                        <div className="flex flex-col">
                                                            <span className="font-medium text-gray-900">{item.product.name}</span>
                                                            <span className="text-xs text-gray-500 font-mono">{item.product.code}</span>
                                                        </div>
                                                    </TableCell>
                                                    <TableCell className="text-right font-medium">
                                                        {Number(item.quantity_received).toLocaleString()}
                                                    </TableCell>
                                                    <TableCell className="text-center">
                                                        {item.product.baseUnit?.name || "個"}
                                                    </TableCell>
                                                    <TableCell className="text-right">
                                                        {formatCurrency(Number(item.unit_price))}
                                                    </TableCell>
                                                    <TableCell className="text-right font-bold text-primary">
                                                        {formatCurrency(Number(item.total_amount))}
                                                    </TableCell>
                                                    <TableCell>
                                                        <span className="text-sm font-mono">{item.batch_number || "-"}</span>
                                                    </TableCell>
                                                    <TableCell>
                                                        <span className="text-sm">{item.expiry_date ? formatDate(item.expiry_date) : "-"}</span>
                                                    </TableCell>
                                                </TableRow>
                                            ))
                                        )}
                                    </TableBody>
                                </Table>
                            </div>

                            {/* 總計 */}
                            <div className="p-6 border-t border-gray-100 flex justify-end">
                                <div className="w-full max-w-xs bg-gray-50/50 px-6 py-4 rounded-xl border border-gray-100 flex flex-col gap-3">
                                    <div className="flex justify-between items-end w-full">
                                        <span className="text-sm text-gray-500 font-medium mb-1">總計金額</span>
                                        <span className="text-2xl font-black text-primary">
                                            {formatCurrency(receipt.items_sum_total_amount)}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}

function GoodsReceiptActions({ receipt }: { receipt: GoodsReceipt }) {
    const { auth } = usePage<PageProps>().props;
    const permissions = auth.user?.permissions || [];
    const roles = auth.user?.roles || [];
    const isSuperAdmin = roles.includes('super-admin');

    // 權限判斷
    const canView = isSuperAdmin || permissions.includes('goods_receipts.view');
    const canEdit = isSuperAdmin || permissions.includes('goods_receipts.edit');
    const canDelete = isSuperAdmin || permissions.includes('goods_receipts.delete');

    const canSubmit = canEdit || canView;

    // 對話框狀態
    const [dialogType, setDialogType] = useState<"submit" | "delete" | null>(null);

    const { post, delete: destroy, processing } = useForm({});

    const handleAction = () => {
        if (!dialogType) return;

        const options = {
            onSuccess: () => {
                toast.success('操作成功');
                setDialogType(null);
            },
            onError: (errors: any) => toast.error(errors.error || '操作失敗')
        };

        switch (dialogType) {
            case "submit":
                post(route('goods-receipts.submit', receipt.id), options);
                break;
            case "delete":
                destroy(route('goods-receipts.destroy', receipt.id), options);
                break;
        }
    };

    return (
        <div className="flex items-center gap-2">
            {receipt.status === 'draft' && canDelete && (
                <Button
                    onClick={() => setDialogType("delete")}
                    variant="outline"
                    className="button-outlined-error border-red-600 text-red-600 hover:bg-red-50"
                    disabled={processing}
                >
                    刪除
                </Button>
            )}

            {receipt.status === 'draft' && canSubmit && (
                <Button
                    onClick={() => setDialogType("submit")}
                    className="button-filled-primary shadow-primary/20"
                    disabled={processing}
                >
                    確認點收
                </Button>
            )}

            {/* 統一確認對話框 */}
            <AlertDialog open={dialogType !== null} onOpenChange={(open) => !open && setDialogType(null)}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>
                            {dialogType === "submit" && "確認點收"}
                            {dialogType === "delete" && "刪除進貨單"}
                        </AlertDialogTitle>
                        <AlertDialogDescription>
                            {dialogType === "submit" && "確定已點收無誤嗎？送出後將會更新庫存、關聯單據數量，並自動產生應付帳款，且無法再次退回。"}
                            {dialogType === "delete" && `將刪除進貨單「${receipt.code}」。注意：此操作無法復原。`}
                        </AlertDialogDescription>
                    </AlertDialogHeader>

                    <AlertDialogFooter>
                        <AlertDialogCancel disabled={processing}>取消</AlertDialogCancel>
                        <Button
                            onClick={handleAction}
                            disabled={processing}
                            className={dialogType === "delete" ? "button-filled-error" : "button-filled-primary"}
                        >
                            {processing ? "處理中..." : "確定"}
                        </Button>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </div>
    );
}
