/**
 * 編輯庫存頁面
 * 用於編輯單一庫存品項的詳細資訊
 */

import { useState } from "react";
import { ArrowLeft, Save, Trash2, AlertTriangle } from "lucide-react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { WarehouseInventory } from "../types/warehouse";
import { toast } from "sonner@2.0.3";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "./ui/alert-dialog";

interface EditInventoryPageProps {
  inventory: WarehouseInventory & { inventoryId: string };
  warehouseName: string;
  onBack: () => void;
  onSave: (inventory: WarehouseInventory & { inventoryId: string }) => void;
  onDelete: (inventoryId: string) => void;
}

export default function EditInventoryPage({
  inventory,
  warehouseName,
  onBack,
  onSave,
  onDelete,
}: EditInventoryPageProps) {
  const [formData, setFormData] = useState(inventory);
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);

  const handleChange = (field: keyof WarehouseInventory, value: any) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const handleSave = () => {
    // 驗證必填欄位
    if (!formData.productName) {
      toast.error("商品名稱不可為空");
      return;
    }
    if (formData.quantity < 0) {
      toast.error("庫存數量不可為負數");
      return;
    }

    onSave(formData);
    toast.success("庫存資料已更新");
  };

  const handleDelete = () => {
    onDelete(formData.inventoryId);
    toast.success("庫存品項已刪除");
  };

  return (
    <div className="container mx-auto p-6 max-w-4xl">
      {/* 頁面標題與麵包屑 */}
      <div className="mb-6">
        <Button
          onClick={onBack}
          variant="ghost"
          className="mb-4 -ml-2 hover:bg-background-light"
        >
          <ArrowLeft className="mr-2 h-4 w-4" />
          返回庫存管理
        </Button>

        <div className="flex items-center gap-2 text-sm text-grey-2 mb-2">
          <span>商品與庫存管理</span>
          <span>/</span>
          <span>倉庫管理</span>
          <span>/</span>
          <span>庫存管理</span>
          <span>/</span>
          <span className="text-grey-0">編輯庫存品項</span>
        </div>

        <div className="flex items-center justify-between">
          <div>
            <h1 className="mb-2">編輯庫存品項</h1>
            <p className="text-gray-600">
              倉庫：<span className="font-medium">{warehouseName}</span>
            </p>
          </div>
          <div className="flex gap-3">
            <Button
              onClick={() => setShowDeleteDialog(true)}
              variant="outline"
              className="group border-destructive text-destructive hover:bg-destructive hover:text-white"
            >
              <Trash2 className="mr-2 h-4 w-4 group-hover:text-white" />
              刪除品項
            </Button>
            <Button onClick={handleSave} className="button-filled-primary">
              <Save className="mr-2 h-4 w-4" />
              儲存變更
            </Button>
          </div>
        </div>
      </div>

      {/* 表單內容 */}
      <div className="bg-white rounded-lg shadow-sm border p-6">
        <div className="space-y-6">
          {/* 商品基本資訊 */}
          <div className="space-y-4">
            <h3 className="font-medium border-b pb-2">商品基本資訊</h3>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="productName">
                  商品名稱 <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="productName"
                  value={formData.productName}
                  disabled
                  className="bg-muted"
                />
                <p className="text-sm text-muted-foreground">
                  商品名稱無法修改
                </p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="batchNumber">批號</Label>
                <Input
                  id="batchNumber"
                  type="text"
                  value={formData.batchNumber}
                  onChange={(e) => handleChange("batchNumber", e.target.value)}
                  placeholder="例：FL20251101"
                  className="button-outlined-primary"
                />
              </div>
            </div>
          </div>

          {/* 庫存數量 */}
          <div className="space-y-4">
            <h3 className="font-medium border-b pb-2">庫存數量</h3>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="quantity">
                  庫存數量 <span className="text-destructive">*</span>
                </Label>
                <Input
                  id="quantity"
                  type="number"
                  min="0"
                  value={formData.quantity}
                  onChange={(e) =>
                    handleChange("quantity", parseInt(e.target.value) || 0)
                  }
                  placeholder="0"
                  className="button-outlined-primary"
                />
                <p className="text-sm text-muted-foreground">
                  批號層級的庫存數量，安全庫存請至「安全庫存設定」頁面進行商品層級設定
                </p>
              </div>
            </div>
          </div>

          {/* 日期資訊 */}
          <div className="space-y-4">
            <h3 className="font-medium border-b pb-2">日期資訊</h3>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="expiryDate">保存期限</Label>
                <Input
                  id="expiryDate"
                  type="date"
                  value={formData.expiryDate}
                  onChange={(e) => handleChange("expiryDate", e.target.value)}
                  className="button-outlined-primary"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="lastInboundDate">最新入庫時間</Label>
                <Input
                  id="lastInboundDate"
                  type="date"
                  value={formData.lastInboundDate}
                  onChange={(e) =>
                    handleChange("lastInboundDate", e.target.value)
                  }
                  className="button-outlined-primary"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="lastOutboundDate">最新出庫時間</Label>
                <Input
                  id="lastOutboundDate"
                  type="date"
                  value={formData.lastOutboundDate}
                  onChange={(e) =>
                    handleChange("lastOutboundDate", e.target.value)
                  }
                  className="button-outlined-primary"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 刪除確認對話框 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>確認刪除庫存品項</AlertDialogTitle>
            <AlertDialogDescription>
              您確定要刪除「{formData.productName}」（批號：
              {formData.batchNumber || "無"}）嗎？此操作無法復原。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel className="button-outlined-primary">
              取消
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              className="bg-destructive text-white hover:bg-destructive/90"
            >
              確認刪除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}