import { useState, useEffect } from "react";
import { ArrowLeft, Plus, Trash2, Package, Info, Calculator } from "lucide-react";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Textarea } from "@/Components/ui/textarea";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, Link, router } from "@inertiajs/react";
import { toast } from "sonner";
import axios from "axios";

interface Product {
    id: number;
    name: string;
    code: string;
    unit_name: string;
}

interface Item {
    product_id: number | null;
    product_name?: string;
    product_code?: string;
    unit_name?: string;
    batch_number: string;
    quantity: number;
    unit_price: number;
    subtotal: number;
    remark: string;
    available_batches: any[];
}

interface Props {
    order?: any;
    warehouses: { id: number; name: string }[];
    products: Product[];
}

export default function ShippingOrderCreate({ order, warehouses, products }: Props) {
    const isEdit = !!order;
    const [warehouseId, setWarehouseId] = useState<string>(order?.warehouse_id?.toString() || "");
    const [customerName, setCustomerName] = useState(order?.customer_name || "");
    const [shippingDate, setShippingDate] = useState(order?.shipping_date || new Date().toISOString().split('T')[0]);
    const [remarks, setRemarks] = useState(order?.remarks || "");
    const [items, setItems] = useState<Item[]>(order?.items?.map((item: any) => ({
        product_id: item.product_id,
        batch_number: item.batch_number,
        quantity: Number(item.quantity),
        unit_price: Number(item.unit_price),
        subtotal: Number(item.subtotal),
        remark: item.remark || "",
        available_batches: [],
    })) || []);

    const [taxAmount, setTaxAmount] = useState(Number(order?.tax_amount) || 0);

    const totalAmount = items.reduce((sum, item) => sum + item.subtotal, 0);
    const grandTotal = totalAmount + taxAmount;

    // 當品項變動時，自動計算稅額 (預設 5%)
    useEffect(() => {
        if (!isEdit || (isEdit && order.status === 'draft')) {
            setTaxAmount(Math.round(totalAmount * 0.05));
        }
    }, [totalAmount]);

    const addItem = () => {
        setItems([...items, {
            product_id: null,
            batch_number: "",
            quantity: 1,
            unit_price: 0,
            subtotal: 0,
            remark: "",
            available_batches: [],
        }]);
    };

    const removeItem = (index: number) => {
        setItems(items.filter((_, i) => i !== index));
    };

    const updateItem = (index: number, updates: Partial<Item>) => {
        const newItems = [...items];
        newItems[index] = { ...newItems[index], ...updates };

        // 計算小計
        if ('quantity' in updates || 'unit_price' in updates) {
            newItems[index].subtotal = Number(newItems[index].quantity) * Number(newItems[index].unit_price);
        }

        setItems(newItems);

        // 如果商品變動，抓取批號
        if ('product_id' in updates && updates.product_id && warehouseId) {
            fetchBatches(index, updates.product_id, warehouseId);
        }
    };

    const fetchBatches = async (index: number, productId: number, wId: string) => {
        try {
            const response = await axios.get(route('api.warehouses.inventory.batches', { warehouse: wId, productId }));
            const newItems = [...items];
            newItems[index].available_batches = response.data;
            setItems(newItems);
        } catch (error) {
            console.error("Failed to fetch batches", error);
        }
    };

    const handleSave = () => {
        if (!warehouseId) {
            toast.error("請選擇出貨倉庫");
            return;
        }
        if (!shippingDate) {
            toast.error("請選擇出貨日期");
            return;
        }
        if (items.length === 0) {
            toast.error("請至少新增一個品項");
            return;
        }

        const data = {
            warehouse_id: warehouseId,
            customer_name: customerName,
            shipping_date: shippingDate,
            remarks: remarks,
            total_amount: totalAmount,
            tax_amount: taxAmount,
            grand_total: grandTotal,
            items: items.map(item => ({
                product_id: item.product_id,
                batch_number: item.batch_number,
                quantity: item.quantity,
                unit_price: item.unit_price,
                subtotal: item.subtotal,
                remark: item.remark,
            })),
        };

        if (isEdit) {
            router.put(route('delivery-notes.update', order.id), data);
        } else {
            router.post(route('delivery-notes.store'), data);
        }
    };

    return (
        <AuthenticatedLayout breadcrumbs={[
            { label: '供應鏈管理', href: '#' },
            { label: '出貨單管理', href: route('delivery-notes.index') },
            { label: isEdit ? '編輯出貨單' : '建立出貨單', isPage: true }
        ] as any}>
            <Head title={isEdit ? "編輯出貨單" : "建立出貨單"} />

            <div className="container mx-auto p-6 max-w-7xl">
                <div className="mb-6">
                    <Link href={route('delivery-notes.index')}>
                        <Button variant="outline" className="gap-2 button-outlined-primary mb-4">
                            <ArrowLeft className="h-4 w-4" /> 返回列表
                        </Button>
                    </Link>
                    <h1 className="text-2xl font-bold flex items-center gap-2">
                        <Package className="h-6 w-6 text-primary-main" />
                        {isEdit ? `編輯出貨單 ${order.doc_no}` : "建立新出貨單"}
                    </h1>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    {/* 左側：基本資訊 */}
                    <div className="lg:col-span-2 space-y-6">
                        <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
                            <h2 className="text-lg font-bold mb-4 flex items-center gap-2">
                                <Info className="h-5 w-5 text-primary-main" /> 基本資料
                            </h2>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <label className="text-sm font-medium">出貨倉庫 *</label>
                                    <SearchableSelect
                                        value={warehouseId}
                                        onValueChange={setWarehouseId}
                                        options={warehouses.map(w => ({ label: w.name, value: w.id.toString() }))}
                                        placeholder="選擇倉庫"
                                    />
                                </div>
                                <div className="space-y-2">
                                    <label className="text-sm font-medium">出貨日期 *</label>
                                    <Input
                                        type="date"
                                        value={shippingDate}
                                        onChange={e => setShippingDate(e.target.value)}
                                    />
                                </div>
                                <div className="space-y-2 md:col-span-2">
                                    <label className="text-sm font-medium">客戶名稱</label>
                                    <Input
                                        placeholder="輸入客戶或專案名稱"
                                        value={customerName}
                                        onChange={e => setCustomerName(e.target.value)}
                                    />
                                </div>
                                <div className="space-y-2 md:col-span-2">
                                    <label className="text-sm font-medium">備註</label>
                                    <Textarea
                                        placeholder="其他說明..."
                                        value={remarks}
                                        onChange={e => setRemarks(e.target.value)}
                                        rows={3}
                                    />
                                </div>
                            </div>
                        </div>

                        {/* 品項明細 */}
                        <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200">
                            <div className="flex items-center justify-between mb-4">
                                <h2 className="text-lg font-bold flex items-center gap-2">
                                    <Package className="h-5 w-5 text-primary-main" /> 商品明細
                                </h2>
                                <Button onClick={addItem} size="sm" className="button-filled-primary gap-1">
                                    <Plus className="h-4 w-4" /> 新增商品
                                </Button>
                            </div>

                            <div className="overflow-x-auto">
                                <table className="w-full text-sm">
                                    <thead>
                                        <tr className="border-b bg-gray-50">
                                            <th className="p-2 text-left w-[250px]">商品</th>
                                            <th className="p-2 text-left w-[180px]">批號</th>
                                            <th className="p-2 text-left w-[120px]">數量</th>
                                            <th className="p-2 text-left w-[120px]">單價</th>
                                            <th className="p-2 text-left">小計</th>
                                            <th className="p-2 text-right">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y">
                                        {items.map((item, index) => (
                                            <tr key={index}>
                                                <td className="p-2">
                                                    <SearchableSelect
                                                        value={item.product_id?.toString() || ""}
                                                        onValueChange={(val) => updateItem(index, { product_id: parseInt(val) })}
                                                        options={products.map(p => ({ label: `[${p.code}] ${p.name}`, value: p.id.toString() }))}
                                                        placeholder="選擇商品"
                                                    />
                                                </td>
                                                <td className="p-2">
                                                    <SearchableSelect
                                                        value={item.batch_number}
                                                        disabled={!item.product_id || !warehouseId}
                                                        onValueChange={(val) => updateItem(index, { batch_number: val })}
                                                        options={item.available_batches.map(b => ({ label: `${b.batch_number} (剩餘 ${b.quantity})`, value: b.batch_number }))}
                                                        placeholder="選擇批號"
                                                    />
                                                </td>
                                                <td className="p-2">
                                                    <Input
                                                        type="number"
                                                        value={item.quantity}
                                                        onChange={e => updateItem(index, { quantity: parseFloat(e.target.value) || 0 })}
                                                        min={0}
                                                        step="any"
                                                        className="text-right"
                                                    />
                                                </td>
                                                <td className="p-2">
                                                    <Input
                                                        type="number"
                                                        value={item.unit_price}
                                                        onChange={e => updateItem(index, { unit_price: parseFloat(e.target.value) || 0 })}
                                                        min={0}
                                                        step="any"
                                                        className="text-right"
                                                    />
                                                </td>
                                                <td className="p-2 font-medium">
                                                    ${item.subtotal.toLocaleString()}
                                                </td>
                                                <td className="p-2 text-right">
                                                    <Button variant="ghost" size="sm" onClick={() => removeItem(index)} className="text-red-500 hover:text-red-700">
                                                        <Trash2 className="h-4 w-4" />
                                                    </Button>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                                {items.length === 0 && (
                                    <div className="text-center py-8 text-gray-500">尚無商品明細</div>
                                )}
                            </div>
                        </div>
                    </div>

                    {/* 右側：金額總計 */}
                    <div className="space-y-6">
                        <div className="bg-white p-6 rounded-lg shadow-sm border border-gray-200 sticky top-6">
                            <h2 className="text-lg font-bold mb-4 flex items-center gap-2">
                                <Calculator className="h-5 w-5 text-primary-main" /> 結算金額
                            </h2>
                            <div className="space-y-4">
                                <div className="flex justify-between text-sm text-gray-600">
                                    <span>未稅金額</span>
                                    <span>${totalAmount.toLocaleString()}</span>
                                </div>
                                <div className="flex justify-between items-center text-sm text-gray-600">
                                    <span>稅額 (5%)</span>
                                    <div className="w-24">
                                        <Input
                                            type="number"
                                            value={taxAmount}
                                            onChange={e => setTaxAmount(parseFloat(e.target.value) || 0)}
                                            step="any"
                                            className="h-8 text-right p-1"
                                        />
                                    </div>
                                </div>
                                <div className="border-t pt-4 flex justify-between font-bold text-lg">
                                    <span>總計金額</span>
                                    <span className="text-primary-main">${grandTotal.toLocaleString()}</span>
                                </div>
                                <Button onClick={handleSave} className="w-full button-filled-primary mt-4 py-6 text-lg font-bold">
                                    {isEdit ? "更新出貨單" : "建立出貨單"}
                                </Button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
