/**
 * 新增供貨商品對話框
 */

import { useState, useMemo } from "react";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Label } from "../ui/label";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "../ui/dialog";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "../ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "../ui/popover";
import { Check, ChevronsUpDown } from "lucide-react";
import { cn } from "../ui/utils";
import type { Product } from "../../types/product";
import type { SupplyProduct } from "../../types/vendor";

interface AddSupplyProductDialogProps {
  open: boolean;
  products: Product[];
  existingSupplyProducts: SupplyProduct[];
  onClose: () => void;
  onAdd: (productId: string, lastPrice?: number) => void;
}

export default function AddSupplyProductDialog({
  open,
  products,
  existingSupplyProducts,
  onClose,
  onAdd,
}: AddSupplyProductDialogProps) {
  const [selectedProductId, setSelectedProductId] = useState<string>("");
  const [lastPrice, setLastPrice] = useState<string>("");
  const [openCombobox, setOpenCombobox] = useState(false);

  // 過濾掉已經在供貨列表中的商品
  const availableProducts = useMemo(() => {
    const existingIds = new Set(existingSupplyProducts.map(sp => sp.productId));
    return products.filter(p => !existingIds.has(p.id));
  }, [products, existingSupplyProducts]);

  const selectedProduct = availableProducts.find(p => p.id === selectedProductId);

  const handleAdd = () => {
    if (!selectedProductId) return;
    
    const price = lastPrice ? parseFloat(lastPrice) : undefined;
    onAdd(selectedProductId, price);
    
    // 重置表單
    setSelectedProductId("");
    setLastPrice("");
  };

  const handleCancel = () => {
    setSelectedProductId("");
    setLastPrice("");
    onClose();
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-xl">
        <DialogHeader>
          <DialogTitle>新增供貨商品</DialogTitle>
          <DialogDescription>選擇該廠商可供應的商品並設定採購價格。</DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {/* 商品選擇 */}
          <div>
            <Label className="text-muted-foreground text-xs">商品名稱</Label>
            <Popover open={openCombobox} onOpenChange={setOpenCombobox}>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  role="combobox"
                  aria-expanded={openCombobox}
                  className="w-full justify-between mt-1"
                >
                  {selectedProduct ? selectedProduct.name : "選擇商品..."}
                  <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-[500px] p-0">
                <Command>
                  <CommandInput placeholder="搜尋商品..." />
                  <CommandList>
                    <CommandEmpty>找不到商品</CommandEmpty>
                    <CommandGroup>
                      {availableProducts.map((product) => (
                        <CommandItem
                          key={product.id}
                          value={product.name}
                          onSelect={() => {
                            setSelectedProductId(product.id);
                            setOpenCombobox(false);
                          }}
                        >
                          <Check
                            className={cn(
                              "mr-2 h-4 w-4",
                              selectedProductId === product.id ? "opacity-100" : "opacity-0"
                            )}
                          />
                          <div className="flex items-center justify-between flex-1">
                            <span>{product.name}</span>
                            <span className="text-xs text-muted-foreground ml-2">
                              ({product.unit})
                            </span>
                          </div>
                        </CommandItem>
                      ))}
                    </CommandGroup>
                  </CommandList>
                </Command>
              </PopoverContent>
            </Popover>
          </div>

          {/* 單位（自動帶入） */}
          {selectedProduct && (
            <div>
              <Label className="text-muted-foreground text-xs">單位</Label>
              <Input
                value={selectedProduct.unit}
                disabled
                className="mt-1 bg-muted"
              />
            </div>
          )}

          {/* 上次採購價格 */}
          <div>
            <Label className="text-muted-foreground text-xs">上次採購單價（選填）</Label>
            <Input
              type="number"
              placeholder="輸入價格"
              value={lastPrice}
              onChange={(e) => setLastPrice(e.target.value)}
              className="mt-1"
            />
          </div>
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            size="sm"
            onClick={handleCancel}
            className="gap-2 button-outlined-primary"
          >
            取消
          </Button>
          <Button
            size="sm"
            onClick={handleAdd}
            disabled={!selectedProductId}
            className="gap-2 button-filled-primary"
          >
            新增
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
