import { useState, useMemo } from "react";
import { ArrowUpDown, ArrowUp, ArrowDown } from "lucide-react";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/Components/ui/table";
import { PurchaseReturnActions } from "./PurchaseReturnActions";
import PurchaseReturnStatusBadge from "./PurchaseReturnStatusBadge";
import CopyButton from "@/Components/shared/CopyButton";
import type { PurchaseReturn } from "@/types/purchase-return";
import { formatCurrency, formatDateTime } from "@/utils/format";

interface PurchaseReturnTableProps {
    purchaseReturns: PurchaseReturn[];
}

type SortField = "code" | "warehouse_name" | "vendor_name" | "return_date" | "total_amount" | "status";
type SortDirection = "asc" | "desc" | null;

export default function PurchaseReturnTable({
    purchaseReturns,
}: PurchaseReturnTableProps) {
    const [sortField, setSortField] = useState<SortField | null>(null);
    const [sortDirection, setSortDirection] = useState<SortDirection>(null);

    // 處理排序
    const handleSort = (field: SortField) => {
        if (sortField === field) {
            if (sortDirection === "asc") {
                setSortDirection("desc");
            } else if (sortDirection === "desc") {
                setSortDirection(null);
                setSortField(null);
            } else {
                setSortDirection("asc");
            }
        } else {
            setSortField(field);
            setSortDirection("asc");
        }
    };

    // 排序後的退回單列表
    const sortedReturns = useMemo(() => {
        if (!sortField || !sortDirection || !purchaseReturns) {
            return purchaseReturns || [];
        }

        return [...purchaseReturns].sort((a, b) => {
            let aValue: string | number;
            let bValue: string | number;

            switch (sortField) {
                case "code":
                    aValue = a.code;
                    bValue = b.code;
                    break;
                case "warehouse_name":
                    aValue = a.warehouse_name || "";
                    bValue = b.warehouse_name || "";
                    break;
                case "vendor_name":
                    aValue = a.vendor?.name || "";
                    bValue = b.vendor?.name || "";
                    break;
                case "return_date":
                    aValue = a.return_date;
                    bValue = b.return_date;
                    break;
                case "total_amount":
                    aValue = a.total_amount;
                    bValue = b.total_amount;
                    break;
                case "status":
                    aValue = a.status;
                    bValue = b.status;
                    break;
                default:
                    return 0;
            }

            if (typeof aValue === "string" && typeof bValue === "string") {
                return sortDirection === "asc"
                    ? aValue.localeCompare(bValue, "zh-TW")
                    : bValue.localeCompare(aValue, "zh-TW");
            } else {
                return sortDirection === "asc"
                    ? (aValue as number) - (bValue as number)
                    : (bValue as number) - (aValue as number);
            }
        });
    }, [purchaseReturns, sortField, sortDirection]);

    const SortIcon = ({ field }: { field: SortField }) => {
        if (sortField !== field) {
            return <ArrowUpDown className="h-4 w-4 text-muted-foreground ml-1" />;
        }
        if (sortDirection === "asc") {
            return <ArrowUp className="h-4 w-4 text-primary ml-1" />;
        }
        if (sortDirection === "desc") {
            return <ArrowDown className="h-4 w-4 text-primary ml-1" />;
        }
        return <ArrowUpDown className="h-4 w-4 text-muted-foreground ml-1" />;
    };

    return (
        <div className="bg-white rounded-lg border shadow-sm overflow-hidden">
            <div className="overflow-x-auto">
                <Table>
                    <TableHeader className="bg-gray-50/50">
                        <TableRow>
                            <TableHead className="w-[50px] text-center">#</TableHead>
                            <TableHead className="w-[180px]">
                                <button
                                    onClick={() => handleSort("code")}
                                    className="flex items-center gap-1 hover:text-foreground transition-colors"
                                >
                                    退回單號
                                    <SortIcon field="code" />
                                </button>
                            </TableHead>
                            <TableHead className="w-[180px]">
                                <button
                                    onClick={() => handleSort("vendor_name")}
                                    className="flex items-center gap-1 hover:text-foreground transition-colors"
                                >
                                    供應商
                                    <SortIcon field="vendor_name" />
                                </button>
                            </TableHead>
                            <TableHead className="w-[150px]">
                                <button
                                    onClick={() => handleSort("return_date")}
                                    className="flex items-center gap-1 hover:text-foreground transition-colors"
                                >
                                    退回日期
                                    <SortIcon field="return_date" />
                                </button>
                            </TableHead>
                            <TableHead className="w-[140px] text-right">
                                <button
                                    onClick={() => handleSort("total_amount")}
                                    className="flex items-center justify-end gap-1 w-full hover:text-foreground transition-colors"
                                >
                                    總計 (未稅)
                                    <SortIcon field="total_amount" />
                                </button>
                            </TableHead>
                            <TableHead className="w-[120px] text-center">
                                <button
                                    onClick={() => handleSort("status")}
                                    className="flex items-center justify-center gap-1 w-full hover:text-foreground transition-colors"
                                >
                                    狀態
                                    <SortIcon field="status" />
                                </button>
                            </TableHead>
                            <TableHead className="text-center">操作</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {!sortedReturns || sortedReturns.length === 0 ? (
                            <TableRow>
                                <TableCell colSpan={7} className="text-center text-muted-foreground py-12">
                                    尚無採購退回單
                                </TableCell>
                            </TableRow>
                        ) : (
                            sortedReturns.map((item, index) => (
                                <TableRow key={item.id}>
                                    <TableCell className="text-gray-500 font-medium text-center">
                                        {index + 1}
                                    </TableCell>
                                    <TableCell>
                                        <div className="flex items-center gap-1.5">
                                            <span className="font-mono text-sm font-medium">{item.code}</span>
                                            <CopyButton text={item.code} label="複製單號" />
                                        </div>
                                    </TableCell>
                                    <TableCell>
                                        <div className="space-y-0.5">
                                            <span className="text-sm text-gray-700">{item.vendor?.name}</span>
                                            <div className="text-xs text-gray-500">{item.user?.name}</div>
                                        </div>
                                    </TableCell>
                                    <TableCell>
                                        <span className="text-sm text-gray-500">{item.return_date}</span>
                                    </TableCell>
                                    <TableCell className="text-right">
                                        <span className="font-semibold text-gray-900">{formatCurrency(item.total_amount)}</span>
                                    </TableCell>
                                    <TableCell className="text-center">
                                        <PurchaseReturnStatusBadge status={item.status} />
                                    </TableCell>
                                    <TableCell className="text-center">
                                        <PurchaseReturnActions
                                            purchaseReturn={item}
                                        />
                                    </TableCell>
                                </TableRow>
                            ))
                        )}
                    </TableBody>
                </Table>
            </div>
        </div>
    );
}
