/**
 * 新增庫存頁面（手動入庫）
 * 用於單一倉庫的手動入庫作業
 */

import { useState, useEffect } from "react";
import { Plus, Trash2, Calendar, ArrowLeft, Save } from "lucide-react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "./ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "./ui/table";
import { InboundItem, InboundReason } from "../types/warehouse";
import { AVAILABLE_PRODUCTS } from "../constants/products";
import { generateBatchNumber, getCurrentDateTime } from "../utils/format";
import { toast } from "sonner@2.0.3";

interface AddInventoryPageProps {
  warehouseId: string;
  warehouseName: string;
  onBack: () => void;
  onSave: (data: {
    inboundDate: string;
    reason: InboundReason;
    notes: string;
    items: InboundItem[];
  }) => void;
}

const INBOUND_REASONS: InboundReason[] = [
  "期初建檔",
  "盤點調整",
  "實際入庫未走採購流程",
  "生產加工成品入庫",
  "其他",
];

const PRODUCT_UNITS: Record<string, string> = {
  "1": "袋",
  "2": "盆",
  "3": "盆",
  "4": "盆",
  "5": "盒",
  "6": "盒",
  "7": "盆",
};

export default function AddInventoryPage({
  warehouseId,
  warehouseName,
  onBack,
  onSave,
}: AddInventoryPageProps) {
  const [inboundDate, setInboundDate] = useState(getCurrentDateTime());
  const [reason, setReason] = useState<InboundReason>("期初建檔");
  const [notes, setNotes] = useState("");
  const [items, setItems] = useState<InboundItem[]>([]);
  const [errors, setErrors] = useState<Record<string, string>>({});

  // 新增明細行
  const handleAddItem = () => {
    const newItem: InboundItem = {
      tempId: `temp-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      productId: AVAILABLE_PRODUCTS[0]?.id || "",
      productName: AVAILABLE_PRODUCTS[0]?.name || "",
      quantity: 0,
      unit: PRODUCT_UNITS[AVAILABLE_PRODUCTS[0]?.id] || "kg",
      expiryDate: "",
      batchNumber: generateBatchNumber(warehouseId, inboundDate.split("T")[0]),
      autoGeneratedBatch: true,
    };
    setItems([...items, newItem]);
  };

  // 刪除明細行
  const handleRemoveItem = (tempId: string) => {
    setItems(items.filter((item) => item.tempId !== tempId));
  };

  // 更新明細行
  const handleUpdateItem = (tempId: string, updates: Partial<InboundItem>) => {
    setItems(
      items.map((item) =>
        item.tempId === tempId ? { ...item, ...updates } : item
      )
    );
  };

  // 處理商品變更
  const handleProductChange = (tempId: string, productId: string) => {
    const product = AVAILABLE_PRODUCTS.find((p) => p.id === productId);
    if (product) {
      handleUpdateItem(tempId, {
        productId,
        productName: product.name,
        unit: PRODUCT_UNITS[productId] || "kg",
      });
    }
  };

  // 處理批號變更
  const handleBatchNumberChange = (tempId: string, value: string) => {
    handleUpdateItem(tempId, {
      batchNumber: value,
      autoGeneratedBatch: false,
    });
  };

  // 驗證表單
  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!reason) {
      newErrors.reason = "請選擇入庫原因";
    }

    if (reason === "其他" && !notes.trim()) {
      newErrors.notes = "原因為「其他」時，備註為必填";
    }

    if (items.length === 0) {
      newErrors.items = "請至少新增一筆庫存明細";
    }

    items.forEach((item, index) => {
      if (!item.productId) {
        newErrors[`item-${index}-product`] = "請選擇商品";
      }
      if (item.quantity <= 0) {
        newErrors[`item-${index}-quantity`] = "數量必須大於 0";
      }
      if (!item.batchNumber.trim()) {
        newErrors[`item-${index}-batch`] = "批號不可為空";
      }
    });

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 處理儲存
  const handleSave = () => {
    if (!validateForm()) {
      toast.error("請檢查表單內容");
      return;
    }

    onSave({
      inboundDate,
      reason,
      notes,
      items,
    });
  };

  return (
    <div className="container mx-auto p-6 max-w-7xl">
      {/* 頁面標題與麵包屑 */}
      <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>
          <Button
            onClick={handleSave}
            className="button-filled-primary"
          >
            <Save className="mr-2 h-4 w-4" />
            儲存
          </Button>
        </div>
      </div>

      {/* 表單內容 */}
      <div className="space-y-6">
        {/* 基本資訊區塊 */}
        <div className="bg-white rounded-lg shadow-sm border p-6 space-y-4">
          <h3 className="font-medium">基本資訊</h3>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* 倉庫 */}
            <div className="space-y-2">
              <Label>倉庫</Label>
              <Input
                value={warehouseName}
                disabled
                className="bg-muted"
              />
            </div>

            {/* 日期時間 */}
            <div className="space-y-2">
              <Label htmlFor="inbound-date">日期時間</Label>
              <div className="relative">
                <Input
                  id="inbound-date"
                  type="datetime-local"
                  value={inboundDate}
                  onChange={(e) => setInboundDate(e.target.value)}
                  className="border-gray-300 pr-10"
                />
                <Calendar className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
              </div>
            </div>

            {/* 入庫原因 */}
            <div className="space-y-2">
              <Label htmlFor="reason">
                入庫原因 <span className="text-destructive">*</span>
              </Label>
              <Select value={reason} onValueChange={(value) => setReason(value as InboundReason)}>
                <SelectTrigger id="reason" className="border-gray-300">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {INBOUND_REASONS.map((r) => (
                    <SelectItem key={r} value={r}>
                      {r}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              {errors.reason && (
                <p className="text-sm text-destructive">{errors.reason}</p>
              )}
            </div>

            {/* 備註 */}
            <div className="space-y-2">
              <Label htmlFor="notes">
                備註 {reason === "其他" && <span className="text-destructive">*</span>}
              </Label>
              <Textarea
                id="notes"
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                placeholder="請輸入備註說明..."
                className="border-gray-300 resize-none"
                rows={3}
              />
              {errors.notes && (
                <p className="text-sm text-destructive">{errors.notes}</p>
              )}
            </div>
          </div>
        </div>

        {/* 庫存明細區塊 */}
        <div className="bg-white rounded-lg shadow-sm border p-6 space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="font-medium">庫存明細</h3>
              <p className="text-sm text-muted-foreground">
                請新增要入庫的商品明細
              </p>
            </div>
            <Button
              type="button"
              onClick={handleAddItem}
              className="button-outlined-primary"
            >
              <Plus className="mr-2 h-4 w-4" />
              新增明細
            </Button>
          </div>

          {errors.items && (
            <p className="text-sm text-destructive">{errors.items}</p>
          )}

          {items.length > 0 ? (
            <div className="border rounded-lg overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[200px]">
                      商品 <span className="text-destructive">*</span>
                    </TableHead>
                    <TableHead className="w-[120px]">
                      數量 <span className="text-destructive">*</span>
                    </TableHead>
                    <TableHead className="w-[80px]">單位</TableHead>
                    <TableHead className="w-[160px]">效期</TableHead>
                    <TableHead className="w-[180px]">進貨編號（自動產生）</TableHead>
                    <TableHead className="w-[60px]"></TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {items.map((item, index) => (
                    <TableRow key={item.tempId}>
                      {/* 商品 */}
                      <TableCell>
                        <Select
                          value={item.productId}
                          onValueChange={(value) =>
                            handleProductChange(item.tempId, value)
                          }
                        >
                          <SelectTrigger className="border-gray-300">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {AVAILABLE_PRODUCTS.map((product) => (
                              <SelectItem key={product.id} value={product.id}>
                                {product.name}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        {errors[`item-${index}-product`] && (
                          <p className="text-xs text-destructive mt-1">
                            {errors[`item-${index}-product`]}
                          </p>
                        )}
                      </TableCell>

                      {/* 數量 */}
                      <TableCell>
                        <Input
                          type="number"
                          min="1"
                          value={item.quantity || ""}
                          onChange={(e) =>
                            handleUpdateItem(item.tempId, {
                              quantity: parseInt(e.target.value) || 0,
                            })
                          }
                          className="border-gray-300"
                        />
                        {errors[`item-${index}-quantity`] && (
                          <p className="text-xs text-destructive mt-1">
                            {errors[`item-${index}-quantity`]}
                          </p>
                        )}
                      </TableCell>

                      {/* 單位 */}
                      <TableCell>
                        <Input
                          value={item.unit}
                          disabled
                          className="bg-muted"
                        />
                      </TableCell>

                      {/* 效期 */}
                      <TableCell>
                        <div className="relative">
                          <Input
                            type="date"
                            value={item.expiryDate}
                            onChange={(e) =>
                              handleUpdateItem(item.tempId, {
                                expiryDate: e.target.value,
                              })
                            }
                            className="border-gray-300 pr-10 [&::-webkit-calendar-picker-indicator]:opacity-0 [&::-webkit-calendar-picker-indicator]:absolute [&::-webkit-calendar-picker-indicator]:right-0 [&::-webkit-calendar-picker-indicator]:w-10 [&::-webkit-calendar-picker-indicator]:h-full [&::-webkit-calendar-picker-indicator]:cursor-pointer"
                          />
                          <Calendar className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-primary pointer-events-none" />
                        </div>
                      </TableCell>

                      {/* 批號 */}
                      <TableCell>
                        <Input
                          value={item.batchNumber}
                          onChange={(e) =>
                            handleBatchNumberChange(item.tempId, e.target.value)
                          }
                          className="border-gray-300"
                          placeholder="系統自動生成"
                        />
                        {errors[`item-${index}-batch`] && (
                          <p className="text-xs text-destructive mt-1">
                            {errors[`item-${index}-batch`]}
                          </p>
                        )}
                      </TableCell>

                      {/* 刪除按鈕 */}
                      <TableCell>
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          onClick={() => handleRemoveItem(item.tempId)}
                          className="hover:bg-red-50 hover:text-red-600"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          ) : (
            <div className="border border-dashed rounded-lg p-8 text-center text-muted-foreground">
              <p>尚無明細，請點擊「新增明細」按鈕加入商品</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}