/**
 * 採購單列表表格
 */

import { useState, useMemo } from "react";
import { ArrowUpDown, ArrowUp, ArrowDown } from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "./ui/table";
import { PurchaseOrderActions } from "./purchase-order/PurchaseOrderActions";
import { StatusBadge } from "./shared/StatusBadge";
import { CopyButton } from "./shared/CopyButton";
import type { PurchaseOrder } from "../types/purchase-order";
import { formatCurrency } from "../utils/purchase-order";
import { STATUS_CONFIG } from "../constants/purchase-order";

interface PurchaseOrderTableProps {
  orders: PurchaseOrder[];
  onEdit: (order: PurchaseOrder) => void;
  onView: (order: PurchaseOrder) => void;
}

type SortField = "poNumber" | "requesterName" | "supplierName" | "createdAt" | "totalAmount" | "status";
type SortDirection = "asc" | "desc" | null;

export default function PurchaseOrderTable({
  orders,
  onEdit,
  onView,
}: PurchaseOrderTableProps) {
  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 sortedOrders = useMemo(() => {
    if (!sortField || !sortDirection) {
      return orders;
    }

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

      switch (sortField) {
        case "poNumber":
          aValue = a.poNumber;
          bValue = b.poNumber;
          break;
        case "requesterName":
          aValue = a.requesterName || a.department;
          bValue = b.requesterName || b.department;
          break;
        case "supplierName":
          aValue = a.supplierName;
          bValue = b.supplierName;
          break;
        case "createdAt":
          aValue = a.createdAt;
          bValue = b.createdAt;
          break;
        case "totalAmount":
          aValue = a.totalAmount;
          bValue = b.totalAmount;
          break;
        case "status":
          aValue = STATUS_CONFIG[a.status].label;
          bValue = STATUS_CONFIG[b.status].label;
          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);
      }
    });
  }, [orders, sortField, sortDirection]);

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

  return (
    <div className="bg-card rounded-lg border-2 border-border">
      {/* 表格 */}
      <div className="overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-[140px]">
                <button
                  onClick={() => handleSort("poNumber")}
                  className="flex items-center gap-2 hover:text-foreground transition-colors"
                >
                  採購單編號
                  <SortIcon field="poNumber" />
                </button>
              </TableHead>
              <TableHead className="w-[180px]">
                <button
                  onClick={() => handleSort("requesterName")}
                  className="flex items-center gap-2 hover:text-foreground transition-colors"
                >
                  申請資訊
                  <SortIcon field="requesterName" />
                </button>
              </TableHead>
              <TableHead className="w-[160px]">
                <button
                  onClick={() => handleSort("supplierName")}
                  className="flex items-center gap-2 hover:text-foreground transition-colors"
                >
                  廠商
                  <SortIcon field="supplierName" />
                </button>
              </TableHead>
              <TableHead className="w-[110px]">
                <button
                  onClick={() => handleSort("createdAt")}
                  className="flex items-center gap-2 hover:text-foreground transition-colors"
                >
                  建立日期
                  <SortIcon field="createdAt" />
                </button>
              </TableHead>
              <TableHead className="w-[110px] text-right">
                <button
                  onClick={() => handleSort("totalAmount")}
                  className="flex items-center gap-2 ml-auto hover:text-foreground transition-colors"
                >
                  總金額
                  <SortIcon field="totalAmount" />
                </button>
              </TableHead>
              <TableHead className="w-[140px]">
                <button
                  onClick={() => handleSort("status")}
                  className="flex items-center gap-2 hover:text-foreground transition-colors"
                >
                  狀態
                  <SortIcon field="status" />
                </button>
              </TableHead>
              <TableHead className="text-right">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {sortedOrders.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center text-muted-foreground py-8">
                  尚無採購單
                </TableCell>
              </TableRow>
            ) : (
              sortedOrders.map((order) => (
                <TableRow key={order.id}>
                  {/* 採購單編號 */}
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <span className="font-mono text-sm">{order.poNumber}</span>
                      <CopyButton text={order.poNumber} label="複製採購單編號" />
                    </div>
                  </TableCell>

                  {/* 申請資訊（申請單位 + 申請人） */}
                  <TableCell>
                    <div className="space-y-0.5">
                      <div className="text-sm font-medium">{order.department}</div>
                      <div className="text-xs text-muted-foreground">{order.createdBy}</div>
                    </div>
                  </TableCell>

                  {/* 廠商 */}
                  <TableCell>
                    <span className="text-sm">{order.supplierName}</span>
                  </TableCell>

                  {/* 建立日期 */}
                  <TableCell>
                    <span className="text-sm text-muted-foreground">{order.createdAt}</span>
                  </TableCell>

                  {/* 總金額 */}
                  <TableCell className="text-right">
                    <span className="font-medium">{formatCurrency(order.totalAmount)}</span>
                  </TableCell>

                  {/* 狀態 */}
                  <TableCell>
                    <StatusBadge status={order.status} />
                  </TableCell>

                  {/* 操作 */}
                  <TableCell>
                    <PurchaseOrderActions
                      order={order}
                      onEdit={onEdit}
                      onView={onView}
                    />
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}