/**
 * 採購單商品表格元件
 */

import { Trash2, Plus } from "lucide-react";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../ui/table";
import type { PurchaseOrderItem, Supplier } from "../../types/purchase-order";
import { isPriceAlert, formatCurrency } from "../../utils/purchase-order";

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

export function PurchaseOrderItemsTable({
  items,
  supplier,
  isReadOnly = false,
  isDisabled = false,
  onAddItem,
  onRemoveItem,
  onItemChange,
}: PurchaseOrderItemsTableProps) {
  return (
    <>
      {/* 商品表格 */}
      <div className={`border-2 border-border rounded-lg overflow-hidden ${isDisabled ? "opacity-50 pointer-events-none" : ""}`}>
        <Table>
          <TableHeader>
            <TableRow className="bg-muted/50">
              <TableHead className="w-[200px]">商品</TableHead>
              <TableHead className="w-[100px]">數量</TableHead>
              <TableHead className="w-[80px]">單位</TableHead>
              <TableHead className="w-[120px]">單價</TableHead>
              <TableHead className="w-[120px]">小計</TableHead>
              {!isReadOnly && <TableHead className="w-[60px]"></TableHead>}
            </TableRow>
          </TableHeader>
          <TableBody>
            {items.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={isReadOnly ? 5 : 6}
                  className="text-center text-muted-foreground py-12"
                >
                  {isDisabled ? "請先選擇供應商後才能新增商品" : "尚未新增商品"}
                </TableCell>
              </TableRow>
            ) : (
              items.map((item, index) => (
                <TableRow key={index}>
                  {/* 商品選擇 */}
                  <TableCell>
                    {isReadOnly ? (
                      <span>{item.productName}</span>
                    ) : (
                      <Select
                        value={item.productId}
                        onValueChange={(value) =>
                          onItemChange?.(index, "productId", value)
                        }
                        disabled={isDisabled}
                      >
                        <SelectTrigger className="h-11 border-2 border-input">
                          <SelectValue placeholder="選擇商品" />
                        </SelectTrigger>
                        <SelectContent>
                          {supplier?.commonProducts.map((product) => (
                            <SelectItem key={product.productId} value={product.productId}>
                              {product.productName}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    )}
                  </TableCell>

                  {/* 數量 */}
                  <TableCell>
                    {isReadOnly ? (
                      <span>{item.quantity}</span>
                    ) : (
                      <Input
                        type="number"
                        min="0"
                        value={item.quantity || ""}
                        onChange={(e) =>
                          onItemChange?.(index, "quantity", Number(e.target.value))
                        }
                        disabled={isDisabled}
                        className="h-11 border-2 border-input"
                      />
                    )}
                  </TableCell>

                  {/* 單位 */}
                  <TableCell>
                    <span className="text-muted-foreground">{item.unit}</span>
                  </TableCell>

                  {/* 單價 */}
                  <TableCell>
                    {isReadOnly ? (
                      <span>{formatCurrency(item.unitPrice)}</span>
                    ) : (
                      <div className="space-y-1">
                        <Input
                          type="number"
                          min="0"
                          step="0.01"
                          value={item.unitPrice || ""}
                          onChange={(e) =>
                            onItemChange?.(index, "unitPrice", Number(e.target.value))
                          }
                          disabled={isDisabled}
                          className={`h-11 border-2 ${
                            isPriceAlert(item.unitPrice, item.previousPrice)
                              ? "border-warning"
                              : "border-input"
                          }`}
                        />
                        {isPriceAlert(item.unitPrice, item.previousPrice) && (
                          <p className="caption text-warning">
                            ⚠️ 上次: {formatCurrency(item.previousPrice || 0)}
                          </p>
                        )}
                      </div>
                    )}
                  </TableCell>

                  {/* 小計 */}
                  <TableCell>
                    <span>{formatCurrency(item.subtotal)}</span>
                  </TableCell>

                  {/* 刪除按鈕 */}
                  {!isReadOnly && onRemoveItem && (
                    <TableCell>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => onRemoveItem(index)}
                        className="button-outlined-error"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </TableCell>
                  )}
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>
    </>
  );
}