/**
 * 編輯安全庫存對話框
 */

import { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription,
} from "@/Components/ui/dialog";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { SafetyStockSetting } from "@/types/warehouse";
import { toast } from "sonner";
import { Badge } from "@/Components/ui/badge";

interface EditSafetyStockDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  setting: SafetyStockSetting;
  onSave: (setting: SafetyStockSetting) => void;
}

export default function EditSafetyStockDialog({
  open,
  onOpenChange,
  setting,
  onSave,
}: EditSafetyStockDialogProps) {
  const [safetyStock, setSafetyStock] = useState(setting.safetyStock);

  useEffect(() => {
    setSafetyStock(setting.safetyStock);
  }, [setting]);

  const handleSubmit = () => {
    if (safetyStock <= 0) {
      toast.error("安全庫存量必須大於 0");
      return;
    }

    const updatedSetting: SafetyStockSetting = {
      ...setting,
      safetyStock,
      updatedAt: new Date().toISOString(),
    };

    onSave(updatedSetting);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>編輯安全庫存</DialogTitle>
          <DialogDescription>請輸入新的安全庫存量。</DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="space-y-2">
            <Label>商品名稱</Label>
            <div className="flex items-center gap-2">
              <span className="font-medium">{setting.productName}</span>
              <Badge variant="outline">{setting.productType}</Badge>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="safetyStock">
              安全庫存量 <span className="text-red-500">*</span>
            </Label>
            <Input
              id="safetyStock"
              type="number"
              min="1"
              step="any"
              value={safetyStock}
              onChange={(e) => setSafetyStock(parseInt(e.target.value) || 0)}
              placeholder="請輸入安全庫存量"
            />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleSubmit} className="button-filled-primary">
            儲存
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}