import { ArrowLeft, Plus, Info, Package } from "lucide-react";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Textarea } from "@/Components/ui/textarea";
import { Alert, AlertDescription } from "@/Components/ui/alert";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link, router, usePage } from "@inertiajs/react";
import { PurchaseReturnItemsTable } from "@/Components/PurchaseReturn/PurchaseReturnItemsTable";
import type { PurchaseReturn } from "@/types/purchase-return";
import type { Supplier } from "@/types/purchase-order";
import type { Warehouse } from "@/types/requester";
import { usePurchaseReturnForm } from "@/hooks/usePurchaseReturnForm";
import { formatCurrency } from "@/utils/format";
import { toast } from "sonner";
import { getEditBreadcrumbs } from "@/utils/breadcrumb";

interface Props {
    purchaseReturn: PurchaseReturn;
    vendors: Supplier[];
    warehouses: Warehouse[];
}

export default function EditPurchaseReturn({
    purchaseReturn,
    vendors,
    warehouses,
}: Props) {
    const { auth } = usePage<any>().props;
    const permissions = auth.user?.permissions || [];
    const isSuperAdmin = auth.user?.roles?.some((r: any) => r.name === 'super-admin');

    const canEdit = isSuperAdmin || permissions.includes('purchase_returns.edit');

    const {
        vendorId,
        warehouseId,
        returnDate,
        items,
        remarks,
        selectedVendor,
        setVendorId,
        setWarehouseId,
        setReturnDate,
        setRemarks,
        addItem,
        removeItem,
        updateItem,
    } = usePurchaseReturnForm({ purchaseReturn, suppliers: vendors });

    const totalAmount = items.reduce((sum, item) => sum + (Number(item.total_amount) || 0), 0);
    const isDraft = purchaseReturn.status === 'draft';

    const handleSave = () => {
        if (!warehouseId) {
            toast.error("請選擇退出的倉庫");
            return;
        }

        if (!vendorId) {
            toast.error("請選擇供應商");
            return;
        }

        if (!returnDate) {
            toast.error("請選擇退回日期");
            return;
        }

        if (items.length === 0) {
            toast.error("請至少新增一項退回商品");
            return;
        }

        const itemsWithQuantity = items.filter(item => item.quantity_returned > 0);
        if (itemsWithQuantity.length === 0) {
            toast.error("請填寫有效的退回數量（必須大於 0）");
            return;
        }

        const itemsWithoutPrice = itemsWithQuantity.filter(item => !item.unit_price || item.unit_price < 0);
        if (itemsWithoutPrice.length > 0) {
            toast.error("單價不能為負數");
            return;
        }

        const validItems = items.filter(i => i.product_id && i.quantity_returned > 0);
        if (validItems.length === 0) {
            toast.error("請確保所有商品都有正確選擇並填寫數量");
            return;
        }

        const data = {
            vendor_id: vendorId,
            warehouse_id: warehouseId,
            return_date: returnDate,
            remarks: remarks,
            items: validItems.map(item => ({
                product_id: item.product_id,
                quantity_returned: item.quantity_returned,
                unit_price: item.unit_price,
                total_amount: item.total_amount,
                batch_number: item.batch_number || null,
            })),
        };

        router.put(`/purchase-returns/${purchaseReturn.id}`, data, {
            onSuccess: () => {
                // Controller 會有 Flash Message
            },
            onError: (errors) => {
                if (errors.items) {
                    toast.error("商品資料有誤,請檢查數量和單價是否正確填寫");
                } else if (errors.error) {
                    toast.error(errors.error);
                } else {
                    toast.error("更新失敗,請檢查輸入內容");
                }
                console.error(errors);
            }
        });
    };

    const hasVendor = !!vendorId;

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

                    <div className="mb-4">
                        <h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
                            <Package className="h-6 w-6 text-primary-main" />
                            編輯採購退回單 {purchaseReturn.code}
                        </h1>
                        <p className="text-gray-500 mt-1">
                            修改退回單的詳細資訊與品項
                        </p>
                    </div>
                </div>

                {!isDraft && (
                    <Alert className="mb-6 bg-amber-50 border-amber-200 text-amber-800">
                        <Info className="h-4 w-4 text-amber-600" />
                        <AlertDescription>
                            此退回單狀態為「{purchaseReturn.status}」，目前無法編輯草稿內容。
                        </AlertDescription>
                    </Alert>
                )}

                <div className={`space-y-6 ${!isDraft ? 'opacity-70 pointer-events-none grayscale-0' : ''}`}>
                    {/* 步驟一：基本資訊 */}
                    <div className="bg-white rounded-lg border shadow-sm overflow-hidden">
                        <div className="p-6 bg-gray-50/50 border-b flex items-center gap-3">
                            <div className="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center font-bold">1</div>
                            <h2 className="text-lg font-bold">基本資訊</h2>
                        </div>

                        <div className="p-6 space-y-6">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                                <div className="space-y-3">
                                    <label className="text-sm font-bold text-gray-700">退出的倉庫 <span className="text-red-500">*</span></label>
                                    <SearchableSelect
                                        value={String(warehouseId)}
                                        onValueChange={setWarehouseId}
                                        options={warehouses.map((w) => ({ label: w.name, value: String(w.id) }))}
                                        placeholder="請選擇倉庫"
                                        searchPlaceholder="搜尋倉庫..."
                                    />
                                </div>

                                <div className="space-y-3">
                                    <label className="text-sm font-bold text-gray-700">退回的供應商 <span className="text-red-500">*</span></label>
                                    <SearchableSelect
                                        value={String(vendorId)}
                                        onValueChange={setVendorId}
                                        options={vendors.map((s) => ({ label: s.name, value: String(s.id) }))}
                                        placeholder="選擇退回廠商"
                                        searchPlaceholder="搜尋廠商..."
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                                <div className="space-y-3">
                                    <label className="text-sm font-bold text-gray-700">
                                        退回日期 <span className="text-red-500">*</span>
                                    </label>
                                    <Input
                                        type="date"
                                        value={returnDate || ""}
                                        onChange={(e) => setReturnDate(e.target.value)}
                                        className="block w-full"
                                    />
                                </div>
                            </div>

                            <div className="space-y-3">
                                <label className="text-sm font-bold text-gray-700">退回原因/備註</label>
                                <Textarea
                                    value={remarks || ""}
                                    onChange={(e) => setRemarks(e.target.value)}
                                    placeholder="描述退回的原因 (如：商品瑕疵，與廠商協商同意退貨...)"
                                    className="min-h-[100px]"
                                />
                            </div>
                        </div>
                    </div>

                    {/* 步驟二：退回品項明細 */}
                    <div className={`bg-white rounded-lg border shadow-sm overflow-hidden transition-all duration-300 ${!hasVendor ? 'opacity-60 saturate-50' : ''}`}>
                        <div className="p-6 bg-gray-50/50 border-b flex items-center justify-between">
                            <div className="flex items-center gap-3">
                                <div className="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center font-bold">2</div>
                                <h2 className="text-lg font-bold">退回明細</h2>
                            </div>
                            <Button
                                onClick={addItem}
                                disabled={!hasVendor || !isDraft}
                                className="button-filled-primary h-10 gap-2"
                            >
                                <Plus className="h-4 w-4" /> 加入退回商品
                            </Button>
                        </div>

                        <div className="p-6">
                            {!hasVendor && (
                                <Alert className="mb-6 bg-amber-50 border-amber-200 text-amber-800">
                                    <Info className="h-4 w-4 text-amber-600" />
                                    <AlertDescription>
                                        請先在步驟一選擇「退回的供應商」，才能從該供應商的常用項目中選取欲退貨的商品。
                                    </AlertDescription>
                                </Alert>
                            )}

                            <PurchaseReturnItemsTable
                                items={items}
                                vendor={selectedVendor}
                                isReadOnly={!isDraft}
                                isDisabled={!hasVendor || !isDraft}
                                onRemoveItem={removeItem}
                                onItemChange={updateItem}
                            />

                            {hasVendor && items.length > 0 && (
                                <div className="mt-6 flex justify-end">
                                    <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(totalAmount)}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                </div>

                {/* 底部按鈕 */}
                <div className="flex items-center justify-end gap-4 py-6 border-t border-gray-100 mt-6">
                    <Link href={`/purchase-returns/${purchaseReturn.id}`}>
                        <Button variant="ghost" className="h-11 px-6 text-gray-500 hover:text-gray-700">
                            取消編輯
                        </Button>
                    </Link>
                    {isDraft && (
                        <Button
                            size="xl"
                            className="bg-primary hover:bg-primary/90 text-white shadow-primary/20"
                            onClick={handleSave}
                            disabled={!canEdit}
                            title={!canEdit ? "您沒有編輯退回單的權限" : ""}
                        >
                            更新儲存
                        </Button>
                    )}
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
