import { useState, useEffect } from "react";
import { Plus, Trash2, AlertCircle } from "lucide-react";
import { Button } from "./ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "./ui/dialog";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "./ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "./ui/table";
import { Alert, AlertDescription } from "./ui/alert";
import type {
  PurchaseOrder,
  PurchaseOrderItem,
  Supplier,
} from "./PurchaseOrderManagement";

interface PurchaseOrderDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  order?: PurchaseOrder;
  onSave: (order: PurchaseOrder) => void;
  suppliers: Supplier[];
}

export default function PurchaseOrderDialog({
  open,
  onOpenChange,
  order,
  onSave,
  suppliers,
}: PurchaseOrderDialogProps) {
  const [supplierId, setSupplierId] = useState("");
  const [expectedDate, setExpectedDate] = useState("");
  const [items, setItems] = useState<PurchaseOrderItem[]>([]);
  const [notes, setNotes] = useState("");

  // Load order data when editing
  useEffect(() => {
    if (order) {
      setSupplierId(order.supplierId);
      setExpectedDate(order.expectedDate);
      setItems(order.items);
      setNotes(order.notes || "");
    } else {
      resetForm();
    }
  }, [order, open]);

  const resetForm = () => {
    setSupplierId("");
    setExpectedDate("");
    setItems([]);
    setNotes("");
  };

  const selectedSupplier = suppliers.find((s) => s.id === supplierId);

  // Auto-populate common products when supplier is selected
  const handleSupplierChange = (newSupplierId: string) => {
    setSupplierId(newSupplierId);
    // 不自动填充商品，保持空白
  };

  const handleAddItem = () => {
    if (!selectedSupplier) return;
    setItems([
      ...items,
      {
        productId: "",
        productName: "",
        quantity: 0,
        unit: "",
        unitPrice: 0,
        subtotal: 0,
      },
    ]);
  };

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

  const handleItemChange = (
    index: number,
    field: keyof PurchaseOrderItem,
    value: string | number
  ) => {
    const newItems = [...items];
    newItems[index] = { ...newItems[index], [field]: value };

    // Auto-populate unit price when product is selected
    if (field === "productId" && selectedSupplier) {
      const product = selectedSupplier.commonProducts.find((p) => p.productId === value);
      if (product) {
        newItems[index].productName = product.productName;
        newItems[index].unit = product.unit;
        newItems[index].unitPrice = product.lastPrice;
        newItems[index].previousPrice = product.lastPrice;
      }
    }

    // Calculate subtotal
    if (field === "quantity" || field === "unitPrice") {
      newItems[index].subtotal = newItems[index].quantity * newItems[index].unitPrice;
    }

    setItems(newItems);
  };

  // Check if price increased more than 5%
  const isPriceAlert = (item: PurchaseOrderItem) => {
    if (!item.previousPrice || item.previousPrice === 0) return false;
    const increase = ((item.unitPrice - item.previousPrice) / item.previousPrice) * 100;
    return increase > 5;
  };

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

  const handleSave = () => {
    if (!supplierId || !expectedDate || items.length === 0) {
      return;
    }

    const validItems = items.filter((item) => item.quantity > 0);
    if (validItems.length === 0) {
      return;
    }

    const supplier = suppliers.find((s) => s.id === supplierId);
    if (!supplier) return;

    const newOrder: PurchaseOrder = {
      id: order?.id || `po-${Date.now()}`,
      poNumber: order?.poNumber || `PO${new Date().getFullYear()}${(Date.now() % 100000).toString().padStart(5, "0")}`,
      supplierId,
      supplierName: supplier.name,
      expectedDate,
      status: order?.status || "draft",
      items: validItems,
      totalAmount: validItems.reduce((sum, item) => sum + item.subtotal, 0),
      createdAt: order?.createdAt || new Date().toISOString().split("T")[0],
      notes,
    };

    onSave(newOrder);
    resetForm();
  };

  const isValid =
    supplierId &&
    expectedDate &&
    items.length > 0 &&
    items.some((item) => item.quantity > 0);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{order ? "編輯採購單" : "建立採購單"}</DialogTitle>
          <DialogDescription>
            {order ? "修改採購單資訊" : "填寫採購單資訊並選擇商品"}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          {/* Basic Info */}
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="supplier">廠商 *</Label>
              <Select value={supplierId} onValueChange={handleSupplierChange}>
                <SelectTrigger id="supplier" className="border-2 border-input">
                  <SelectValue placeholder="選擇廠商" />
                </SelectTrigger>
                <SelectContent>
                  {suppliers.map((supplier) => (
                    <SelectItem key={supplier.id} value={supplier.id}>
                      {supplier.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="space-y-2">
              <Label htmlFor="expectedDate">預計到貨日 *</Label>
              <Input
                id="expectedDate"
                type="date"
                value={expectedDate}
                onChange={(e) => setExpectedDate(e.target.value)}
                min={new Date().toISOString().split("T")[0]}
                className="border-2 border-input [&::-webkit-calendar-picker-indicator]:opacity-100 [&::-webkit-calendar-picker-indicator]:cursor-pointer [&::-webkit-calendar-picker-indicator]:contrast-200"
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="notes">備註</Label>
            <Input
              id="notes"
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              placeholder="選填"
              className="border-2 border-input"
            />
          </div>

          {/* Items */}
          {supplierId && (
            <>
              <div className="flex justify-between items-center">
                <Label>採購商品 *</Label>
                <Button 
                  variant="outline" 
                  size="sm" 
                  onClick={handleAddItem} 
                  className="gap-2 hover:bg-accent hover:text-accent-foreground hover:border-primary transition-colors button-outlined-primary"
                >
                  <Plus className="h-3 w-3" />
                  新增商品
                </Button>
              </div>

              <div className="border border-border rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <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>
                      <TableHead className="w-[60px]"></TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {items.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                          請新增商品
                        </TableCell>
                      </TableRow>
                    ) : (
                      items.map((item, index) => (
                        <TableRow key={index}>
                          <TableCell>
                            <Select
                              value={item.productId}
                              onValueChange={(value) =>
                                handleItemChange(index, "productId", value)
                              }
                            >
                              <SelectTrigger className="h-9 border-2 border-input">
                                <SelectValue placeholder="選擇商品" />
                              </SelectTrigger>
                              <SelectContent>
                                {selectedSupplier?.commonProducts.map((product) => (
                                  <SelectItem key={product.productId} value={product.productId}>
                                    {product.productName}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </TableCell>
                          <TableCell>
                            <Input
                              type="number"
                              min="0"
                              value={item.quantity || ""}
                              onChange={(e) =>
                                handleItemChange(index, "quantity", Number(e.target.value))
                              }
                              className="h-9 border-2 border-input"
                            />
                          </TableCell>
                          <TableCell>
                            <span className="text-muted-foreground">{item.unit}</span>
                          </TableCell>
                          <TableCell>
                            <div className="space-y-1">
                              <Input
                                type="number"
                                min="0"
                                step="0.01"
                                value={item.unitPrice || ""}
                                onChange={(e) =>
                                  handleItemChange(index, "unitPrice", Number(e.target.value))
                                }
                                className={`h-9 border-2 ${isPriceAlert(item) ? "border-red-500" : "border-input"}`}
                              />
                              {isPriceAlert(item) && (
                                <p className="text-xs text-red-500">
                                  ⚠️ 上次: ${item.previousPrice}
                                </p>
                              )}
                            </div>
                          </TableCell>
                          <TableCell>
                            <span>${item.subtotal.toLocaleString()}</span>
                          </TableCell>
                          <TableCell>
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleRemoveItem(index)}
                            >
                              <Trash2 className="h-3 w-3" />
                            </Button>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </div>

              {/* Price Alert Summary */}
              {items.some((item) => isPriceAlert(item)) && (
                <Alert variant="destructive">
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>
                    部分商品單價比上次採購價高出超過 5%，請確認是否正確。
                  </AlertDescription>
                </Alert>
              )}

              {/* Total */}
              <div className="flex justify-end items-center gap-4 pt-4 border-t border-border">
                <span className="text-muted-foreground">總金額：</span>
                <span className="text-primary-main">${totalAmount.toLocaleString()}</span>
              </div>
            </>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} className="button-outlined-primary">
            取消
          </Button>
          <Button onClick={handleSave} disabled={!isValid} className="button-filled-primary">
            {order ? "更新" : "建立"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}