import { ArrowLeft, Package, CheckCircle, XCircle, FileEdit } from "lucide-react";
import { Button } from "@/Components/ui/button";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link, useForm, usePage, router } from "@inertiajs/react";
import CopyButton from "@/Components/shared/CopyButton";
import { PurchaseReturnItemsTable } from "@/Components/PurchaseReturn/PurchaseReturnItemsTable";
import type { PurchaseReturn } from "@/types/purchase-return";
import { formatCurrency, formatDateTime } from "@/utils/format";
import { getShowBreadcrumbs } from "@/utils/breadcrumb";
import { toast } from "sonner";
import { PageProps } from "@/types/global";

interface Props {
    purchaseReturn: PurchaseReturn;
}

export default function ViewPurchaseReturnPage({ purchaseReturn }: Props) {
    const isDraft = purchaseReturn.status === 'draft';

    return (
        <AuthenticatedLayout breadcrumbs={getShowBreadcrumbs("purchaseReturns", `詳情 (${purchaseReturn.code})`)}>
            <Head title={`採購退回單詳情 - ${purchaseReturn.code}`} />
            <div className="container mx-auto p-6 max-w-7xl">
                {/* 返回按鈕 */}
                <div className="mb-6">
                    <Link href="/purchase-returns">
                        <Button
                            variant="outline"
                            className="gap-2 button-outlined-primary"
                        >
                            <ArrowLeft className="h-4 w-4" />
                            返回退回單列表
                        </Button>
                    </Link>
                </div>

                {/* 頁面標題與操作 */}
                <div className="flex flex-col md:flex-row items-center justify-between mb-6 gap-4">
                    <div>
                        <h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
                            <Package className="h-6 w-6 text-primary-main" />
                            採購退回單詳情
                        </h1>
                        <div className="flex items-center gap-2 mt-1">
                            <PurchaseReturnStatusBadge status={purchaseReturn.status} />
                            <span className="text-gray-500 text-sm">單號：{purchaseReturn.code}</span>
                        </div>
                    </div>
                    <div className="flex items-center gap-3">
                        <PurchaseReturnActions purchaseReturn={purchaseReturn} />
                    </div>
                </div>

                <div className="space-y-8">
                    {/* 基本資訊卡片 */}
                    <div className="bg-white rounded-lg border shadow-sm p-6">
                        <div className="flex justify-between items-center mb-6">
                            <h2 className="text-lg font-bold text-gray-900">基本資訊</h2>
                            {isDraft && (
                                <Link href={`/purchase-returns/${purchaseReturn.id}/edit`}>
                                    <Button variant="outline" size="sm" className="button-outlined-primary">
                                        <FileEdit className="h-4 w-4 mr-1" /> 編輯內容
                                    </Button>
                                </Link>
                            )}
                        </div>
                        <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>
                                <div className="flex items-center gap-1.5">
                                    <span className="font-mono font-medium text-gray-900">{purchaseReturn.code}</span>
                                    <CopyButton text={purchaseReturn.code} label="複製單號" />
                                </div>
                            </div>
                            <div>
                                <span className="text-sm text-gray-500 block mb-1">供應商</span>
                                <span className="font-medium text-gray-900">{purchaseReturn.vendor?.name}</span>
                            </div>
                            <div>
                                <span className="text-sm text-gray-500 block mb-1">退貨倉庫</span>
                                <span className="font-medium text-gray-900">
                                    {purchaseReturn.warehouse_name}
                                </span>
                            </div>
                            <div>
                                <span className="text-sm text-gray-500 block mb-1">建立者</span>
                                <span className="font-medium text-gray-900">
                                    {purchaseReturn.user?.name}
                                </span>
                            </div>
                            <div>
                                <span className="text-sm text-gray-500 block mb-1">建立時間</span>
                                <span className="font-medium text-gray-900">{formatDateTime(purchaseReturn.created_at)}</span>
                            </div>
                            <div>
                                <span className="text-sm text-gray-500 block mb-1">退回日期</span>
                                <span className="font-medium text-gray-900">{purchaseReturn.return_date || "-"}</span>
                            </div>
                        </div>
                        {purchaseReturn.remarks && (
                            <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 whitespace-pre-wrap">
                                    {purchaseReturn.remarks}
                                </p>
                            </div>
                        )}
                    </div>

                    {/* 退回項目卡片 */}
                    <div className="bg-white rounded-lg border shadow-sm overflow-hidden">
                        <div className="p-6 border-b border-gray-100">
                            <h2 className="text-lg font-bold text-gray-900">退回項目明細</h2>
                        </div>
                        <div className="p-0 sm:p-6">
                            <PurchaseReturnItemsTable
                                items={purchaseReturn.items || []}
                                isReadOnly={true}
                            />
                            <div className="mt-6 flex justify-end mr-6 sm:mr-0">
                                <div className="w-full max-w-sm bg-primary/5 px-6 py-4 rounded-xl border border-primary/10 flex flex-col gap-3">
                                    <div className="flex justify-between items-center w-full">
                                        <span className="text-sm text-gray-500 font-medium">總退款金額</span>
                                        <span className="text-2xl font-black text-primary">
                                            {formatCurrency(purchaseReturn.total_amount)}
                                        </span>
                                    </div>
                                    {purchaseReturn.tax_amount > 0 && (
                                        <div className="flex justify-between items-center w-full">
                                            <span className="text-sm text-gray-500 font-medium">含稅額</span>
                                            <span className="text-lg text-gray-700">
                                                {formatCurrency(purchaseReturn.tax_amount)}
                                            </span>
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}

function PurchaseReturnStatusBadge({ status }: { status: string }) {
    switch (status) {
        case 'draft':
            return <span className="px-2.5 py-1 bg-yellow-100 text-yellow-800 text-xs font-semibold rounded-full border border-yellow-200">草稿</span>;
        case 'completed':
            return <span className="px-2.5 py-1 bg-green-100 text-green-800 text-xs font-semibold rounded-full border border-green-200">已完成</span>;
        case 'cancelled':
            return <span className="px-2.5 py-1 bg-gray-100 text-gray-800 text-xs font-semibold rounded-full border border-gray-200">已取消</span>;
        default:
            return <span className="px-2.5 py-1 bg-gray-100 text-gray-800 text-xs font-semibold rounded-full border border-gray-200">{status}</span>;
    }
}

function PurchaseReturnActions({ purchaseReturn }: { purchaseReturn: PurchaseReturn }) {
    const { auth } = usePage<PageProps>().props;
    const permissions = auth.user?.permissions || [];
    const { processing } = useForm({});

    const handleAction = (routeUri: string, method: 'post' | 'put' | 'patch' | 'delete', confirmMessage?: string) => {
        if (confirmMessage && !confirm(confirmMessage)) return;

        router[method](routeUri, {}, {
            onSuccess: () => {
                // UI feedback handled by Flash Message toast via Middleware
            },
            onError: (errors: any) => {
                console.error("Action Error:", errors);
                toast.error(errors.error || "操作失敗");
            }
        });
    };

    const isSuperAdmin = auth.user?.roles?.some((r: any) => r.name === 'super-admin');
    const canApprove = isSuperAdmin || permissions.includes('purchase_returns.approve');
    const canCancel = isSuperAdmin || permissions.includes('purchase_returns.cancel');
    const canDelete = isSuperAdmin || permissions.includes('purchase_returns.delete');

    return (
        <div className="flex items-center gap-2">
            {purchaseReturn.status === 'draft' && canDelete && (
                <Button
                    onClick={() => handleAction(`/purchase-returns/${purchaseReturn.id}`, 'delete', '確定要刪除這筆草稿嗎？此操作無法復原。')}
                    disabled={processing}
                    variant="outline"
                    className="button-outlined-error border-red-600 text-red-600 hover:bg-red-50"
                >
                    <XCircle className="h-4 w-4 mr-1" /> 刪除草稿
                </Button>
            )}

            {purchaseReturn.status === 'draft' && canApprove && (
                <Button
                    onClick={() => handleAction(`/purchase-returns/${purchaseReturn.id}/submit`, 'post', '確定要完成此退貨？此步驟會立即扣減實際倉庫庫存，且無法復原。')}
                    disabled={processing}
                    className="button-filled-success shadow-green-600/20"
                >
                    <CheckCircle className="h-4 w-4 mr-1" /> 確認退貨 (扣庫存)
                </Button>
            )}

            {purchaseReturn.status === 'completed' && canCancel && (
                <Button
                    onClick={() => handleAction(`/purchase-returns/${purchaseReturn.id}/cancel`, 'post', '確定要取消此筆退貨？庫存不會自動回補。')}
                    disabled={processing}
                    variant="outline"
                    className="button-outlined-warning"
                >
                    <XCircle className="h-4 w-4 mr-1" /> 作廢紀錄
                </Button>
            )}
        </div>
    );
}
