import { useState, useEffect } from "react";
import { Head, Link, router } from "@inertiajs/react";
import { Phone, Mail, Plus, ArrowLeft, Contact2 } from "lucide-react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Label } from "@/Components/ui/label";
import { Button } from "@/Components/ui/button";
import SupplyProductList from "@/Components/Vendor/SupplyProductList";
import type { Vendor } from "@/Pages/Vendor/Index";
import type { SupplyProduct } from "@/types/vendor";
import { getShowBreadcrumbs } from "@/utils/breadcrumb";
import { toast } from "sonner";

interface Pivot {
    last_price: number | null;
}

interface VendorProduct {
    id: number;
    name: string;
    unit?: string;
    baseUnit?: { name: string };
    base_unit?: { name: string };
    largeUnit?: { name: string };
    large_unit?: { name: string };
    purchaseUnit?: string;
    purchase_unit?: string;
    conversion_rate?: number;
    pivot: Pivot;
}

interface ExtendedVendor extends Vendor {
    products: VendorProduct[];
}

interface ShowProps {
    vendor: ExtendedVendor;
    products: any[];
}

export default function VendorShow({ vendor, products: allProducts }: ShowProps) {
    const [items, setItems] = useState<SupplyProduct[]>([]);

    // 初始化資料
    useEffect(() => {
        const initialItems: SupplyProduct[] = vendor.products.map(p => {
            const baseUnitName = p.baseUnit?.name || p.base_unit?.name;
            const largeUnitName = p.largeUnit?.name || p.large_unit?.name;

            return {
                id: String(p.id) + "_" + Math.random().toString(36).substr(2, 9), // 加上隨機碼以確保 key 唯一
                productId: String(p.id),
                productName: p.name,
                unit: p.purchase_unit || baseUnitName || "個",
                baseUnit: baseUnitName,
                largeUnit: largeUnitName,
                conversionRate: p.conversion_rate,
                lastPrice: p.pivot.last_price || undefined,
            };
        });
        setItems(initialItems);
    }, [vendor.products]);

    const handleAddItem = () => {
        const newItem: SupplyProduct = {
            id: "new_" + Math.random().toString(36).substr(2, 9),
            productId: "",
            productName: "",
            unit: "個",
            lastPrice: undefined,
        };
        setItems([...items, newItem]);
    };

    const handleRemoveItem = (index: number) => {
        const newItems = [...items];
        newItems.splice(index, 1);
        setItems(newItems);
    };

    const handleItemChange = (index: number, field: keyof SupplyProduct, value: any) => {
        const newItems = [...items];
        const item = { ...newItems[index] };

        if (field === "productId") {
            const product = allProducts.find(p => String(p.id) === String(value));
            if (product) {
                item.productId = String(product.id);
                item.productName = product.name;
                item.baseUnit = product.baseUnit?.name || product.base_unit?.name || product.base_unit || "個";
                item.largeUnit = product.largeUnit?.name || product.large_unit?.name;
                item.conversionRate = product.conversion_rate;
                item.unit = item.baseUnit || "個";
            } else {
                item.productId = value;
                item.productName = "";
            }
        } else {
            (item as any)[field] = value;
        }

        newItems[index] = item;
        setItems(newItems);
    };

    const handleSaveAll = () => {
        // 過濾掉沒有選擇商品的項目
        const validItems = items.filter(item => item.productId !== "");

        if (validItems.length === 0 && items.length > 0) {
            toast.error("請至少選擇一個有效的商品，或移除空白列");
            return;
        }

        // 檢查重複商品
        const productIds = validItems.map(i => i.productId);
        if (new Set(productIds).size !== productIds.length) {
            toast.error("供貨清單中有重複的商品，請檢查");
            return;
        }

        router.put(route('vendors.products.sync', vendor.id), {
            products: validItems.map(item => ({
                product_id: item.productId,
                last_price: item.lastPrice,
            }))
        }, {
            onSuccess: () => {
                toast.success("供貨商品已更新");
            },
            onError: () => {
                toast.error("更新失敗，請檢查欄位格式");
            }
        });
    };

    return (
        <AuthenticatedLayout breadcrumbs={getShowBreadcrumbs("vendors", `廠商詳情 (${vendor.name})`)}>
            <Head title={`廠商詳情 - ${vendor.name}`} />
            <div className="container mx-auto p-6 max-w-7xl">
                {/* 返回按鈕 */}
                <div className="mb-6">
                    <Link href="/vendors">
                        <Button
                            variant="outline"
                            className="gap-2 button-outlined-primary mb-6"
                        >
                            <ArrowLeft className="h-4 w-4" />
                            返回廠商資料管理
                        </Button>
                    </Link>
                    <div className="flex items-center justify-between">
                        <div>
                            <h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
                                <Contact2 className="h-6 w-6 text-primary-main" />
                                廠商詳細資訊
                            </h1>
                            <p className="text-gray-500 mt-1">查看並管理供應商的詳細資料與供貨商品</p>
                        </div>
                    </div>
                </div>

                {/* 基本資料 */}
                <div className="bg-white rounded-lg border border-border p-6 mb-6 shadow-sm">
                    <h3 className="mb-4 text-primary font-bold">基本資料</h3>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <Label className="text-muted-foreground text-xs">廠商名稱</Label>
                            <p className="mt-1 font-medium flex items-baseline gap-2">
                                {vendor.name}
                                <span className="text-sm text-muted-foreground">({vendor.code})</span>
                            </p>
                        </div>
                        <div>
                            <Label className="text-muted-foreground text-xs">廠商簡稱</Label>
                            <p className="mt-1 font-medium">{vendor.shortName || "-"}</p>
                        </div>
                        <div>
                            <Label className="text-muted-foreground text-xs">統一編號</Label>
                            <p className="mt-1">{vendor.taxId || "-"}</p>
                        </div>
                        <div>
                            <Label className="text-muted-foreground text-xs">負責人</Label>
                            <p className="mt-1">{vendor.owner || "-"}</p>
                        </div>
                        <div className="md:col-span-2">
                            <Label className="text-muted-foreground text-xs">備註</Label>
                            <p className="mt-1 whitespace-pre-wrap">{vendor.remark || "-"}</p>
                        </div>
                    </div>
                </div>

                {/* 聯絡資料 */}
                <div className="bg-white rounded-lg border border-border p-6 mb-6 shadow-sm">
                    <h3 className="mb-4 text-primary font-bold">聯絡資料</h3>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <Label className="text-muted-foreground text-xs">聯絡人</Label>
                            <p className="mt-1">{vendor.contactName || "-"}</p>
                        </div>
                        <div>
                            <Label className="text-muted-foreground text-xs">聯絡電話</Label>
                            <p className="mt-1 flex items-center gap-2">
                                <Phone className="h-4 w-4 text-muted-foreground" />
                                {vendor.phone || vendor.tel || "-"}
                            </p>
                        </div>
                        <div>
                            <Label className="text-muted-foreground text-xs">Email</Label>
                            <p className="mt-1 flex items-center gap-2">
                                <Mail className="h-4 w-4 text-muted-foreground" />
                                {vendor.email || "-"}</p>
                        </div>
                        <div>
                            <Label className="text-muted-foreground text-xs">地址</Label>
                            <p className="mt-1">{vendor.address || "-"}</p>
                        </div>
                    </div>
                </div>

                {/* 供貨商品列表 */}
                <div className="bg-white rounded-lg border border-border p-6 shadow-sm">
                    <div className="flex items-center justify-between mb-4">
                        <h3 className="font-bold">供貨商品</h3>
                        <Button
                            onClick={handleAddItem}
                            className="gap-2 button-filled-primary"
                            size="sm"
                        >
                            <Plus className="h-4 w-4" />
                            新增供貨商品
                        </Button>
                    </div>

                    <SupplyProductList
                        items={items}
                        allProducts={allProducts}
                        onRemoveItem={handleRemoveItem}
                        onItemChange={handleItemChange}
                    />
                </div>

                {/* 底部按鈕 - 移至容器外 */}
                <div className="mt-6 flex items-center justify-end gap-4 py-6 border-t border-gray-100">
                    <Link href="/vendors">
                        <Button variant="ghost" className="h-11 px-6 text-gray-500 hover:text-gray-700">
                            取消
                        </Button>
                    </Link>
                    <Button
                        onClick={handleSaveAll}
                        className="bg-primary hover:bg-primary/90 text-white shadow-primary/20 h-11 px-8 text-lg font-bold rounded-xl"
                        size="lg"
                    >
                        更新供貨商品
                    </Button>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
