import { Trash2 } from "lucide-react";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { SearchableSelect } from "@/Components/ui/searchable-select";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/Components/ui/table";
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from "@/Components/ui/alert-dialog";
import type { PurchaseReturnItem } from "@/types/purchase-return";
import type { Supplier } from "@/types/purchase-order";
import { formatCurrency } from "@/utils/format";

interface PurchaseReturnItemsTableProps {
    items: PurchaseReturnItem[];
    vendor?: Supplier;
    isReadOnly?: boolean;
    isDisabled?: boolean;
    onRemoveItem?: (index: number) => void;
    onItemChange?: (index: number, field: keyof PurchaseReturnItem, value: string | number) => void;
}

export function PurchaseReturnItemsTable({
    items,
    vendor,
    isReadOnly = false,
    isDisabled = false,
    onRemoveItem,
    onItemChange,
}: PurchaseReturnItemsTableProps) {
    return (
        <div className={`border rounded-lg overflow-hidden ${isDisabled ? "opacity-50 pointer-events-none grayscale" : ""}`}>
            <Table>
                <TableHeader>
                    <TableRow className="bg-gray-50 hover:bg-gray-50">
                        <TableHead className="w-[30%] text-left">退回商品</TableHead>
                        <TableHead className="w-[15%] text-left">退回數量</TableHead>
                        <TableHead className="w-[15%] text-left">退回單價</TableHead>
                        <TableHead className="w-[15%] text-left">總退款金額</TableHead>
                        <TableHead className="w-[20%] text-left">批號 / 備註</TableHead>
                        {!isReadOnly && <TableHead className="w-[5%]"></TableHead>}
                    </TableRow>
                </TableHeader>
                <TableBody>
                    {items.length === 0 ? (
                        <TableRow>
                            <TableCell
                                colSpan={isReadOnly ? 5 : 6}
                                className="text-center text-gray-400 py-12 italic"
                            >
                                {isDisabled ? "請先選擇供應商後才能加入退回商品" : "尚未新增任何退回品項"}
                            </TableCell>
                        </TableRow>
                    ) : (
                        items.map((item, index) => {
                            return (
                                <TableRow key={index}>
                                    {/* 商品選擇 */}
                                    <TableCell>
                                        {isReadOnly ? (
                                            <span className="font-medium">{item.product?.name || item.product_name}</span>
                                        ) : (
                                            <SearchableSelect
                                                value={String(item.product_id)}
                                                onValueChange={(value) =>
                                                    onItemChange?.(index, "product_id", value)
                                                }
                                                disabled={isDisabled}
                                                options={vendor?.commonProducts?.map((p) => ({ label: p.productName, value: String(p.productId) })) || []}
                                                placeholder="選擇退回商品"
                                                searchPlaceholder="搜尋商品..."
                                                emptyText="此供應商無可用商品"
                                                className="w-full"
                                            />
                                        )}
                                    </TableCell>

                                    {/* 數量 */}
                                    <TableCell className="text-left">
                                        {isReadOnly ? (
                                            <span>{item.quantity_returned}</span>
                                        ) : (
                                            <Input
                                                type="number"
                                                min="0.01"
                                                step="any"
                                                value={item.quantity_returned || ""}
                                                onChange={(e) =>
                                                    onItemChange?.(index, "quantity_returned", Number(e.target.value))
                                                }
                                                disabled={isDisabled}
                                                className="text-right w-full"
                                            />
                                        )}
                                    </TableCell>

                                    {/* 單價 */}
                                    <TableCell className="text-left">
                                        {isReadOnly ? (
                                            <span>{formatCurrency(item.unit_price)}</span>
                                        ) : (
                                            <Input
                                                type="number"
                                                min="0"
                                                step="any"
                                                value={item.unit_price === 0 ? "" : item.unit_price}
                                                onChange={(e) =>
                                                    onItemChange?.(index, "unit_price", Number(e.target.value))
                                                }
                                                disabled={isDisabled}
                                                className="text-right w-full"
                                            />
                                        )}
                                    </TableCell>

                                    {/* 總退款金額 */}
                                    <TableCell className="text-left">
                                        {isReadOnly ? (
                                            <span className="font-bold text-primary">{formatCurrency(item.total_amount)}</span>
                                        ) : (
                                            <div className="space-y-1">
                                                <Input
                                                    type="number"
                                                    min="0"
                                                    step="any"
                                                    value={item.total_amount || ""}
                                                    onChange={(e) =>
                                                        onItemChange?.(index, "total_amount", Number(e.target.value))
                                                    }
                                                    disabled={isDisabled}
                                                    className={`text-right w-full ${item.quantity_returned > 0 && (!item.total_amount || item.total_amount <= 0)
                                                        ? "border-red-400 bg-red-50 focus-visible:ring-red-500"
                                                        : ""
                                                        }`}
                                                />
                                            </div>
                                        )}
                                    </TableCell>

                                    {/* 批號 */}
                                    <TableCell className="text-left">
                                        {isReadOnly ? (
                                            <span className="text-gray-500">{item.batch_number}</span>
                                        ) : (
                                            <Input
                                                type="text"
                                                value={item.batch_number || ""}
                                                onChange={(e) =>
                                                    onItemChange?.(index, "batch_number", e.target.value)
                                                }
                                                disabled={isDisabled}
                                                className="w-full"
                                                placeholder="輸入批號或備註..."
                                            />
                                        )}
                                    </TableCell>

                                    {/* 刪除按鈕 */}
                                    {!isReadOnly && onRemoveItem && (
                                        <TableCell className="text-center">
                                            <AlertDialog>
                                                <AlertDialogTrigger asChild>
                                                    <Button
                                                        variant="outline"
                                                        size="sm"
                                                        className="button-outlined-error"
                                                        title="移除項目"
                                                    >
                                                        <Trash2 className="h-4 w-4" />
                                                    </Button>
                                                </AlertDialogTrigger>
                                                <AlertDialogContent>
                                                    <AlertDialogHeader>
                                                        <AlertDialogTitle>確定要移除此退回項嗎？</AlertDialogTitle>
                                                        <AlertDialogDescription>
                                                            此動作將從退回清單中移除該商品。
                                                        </AlertDialogDescription>
                                                    </AlertDialogHeader>
                                                    <AlertDialogFooter>
                                                        <AlertDialogCancel>取消</AlertDialogCancel>
                                                        <AlertDialogAction
                                                            onClick={() => onRemoveItem(index)}
                                                            className="bg-red-600 hover:bg-red-700"
                                                        >
                                                            確定移除
                                                        </AlertDialogAction>
                                                    </AlertDialogFooter>
                                                </AlertDialogContent>
                                            </AlertDialog>
                                        </TableCell>
                                    )}
                                </TableRow>
                            );
                        })
                    )}
                </TableBody>
            </Table>
        </div>
    );
}
