/**
 * 倉庫庫存頁面元件
 * 重構後：邏輯更清晰，元件更模組化
 */

import { useState, useMemo, useEffect } from "react";
import { ArrowLeft, PackagePlus, AlertTriangle, Shield } from "lucide-react";
import { Button } from "./ui/button";
import { WarehouseInventory, SafetyStockSetting } from "../types/warehouse";
import InventoryStats from "./inventory/InventoryStats";
import InventoryToolbar from "./inventory/InventoryToolbar";
import InventoryTable, { InventoryItemWithId, ProductGroup } from "./inventory/InventoryTable";
import { AVAILABLE_PRODUCTS } from "../constants/products";
import { useInventoryFilter } from "../hooks/useInventoryFilter";
import { calculateLowStockCount } from "../utils/inventory";

interface WarehouseInventoryPageProps {
  warehouseId: string;
  warehouseName: string;
  inventories: WarehouseInventory[];
  safetyStockSettings: SafetyStockSetting[];
  onBack: () => void;
  onNavigateToAddInventory: () => void;
  onNavigateToEditInventory: (inventoryId: string) => void;
  onNavigateToSafetyStock: () => void;
}

export default function WarehouseInventoryPage({
  warehouseId,
  warehouseName,
  inventories,
  safetyStockSettings,
  onBack,
  onNavigateToAddInventory,
  onNavigateToEditInventory,
  onNavigateToSafetyStock,
}: WarehouseInventoryPageProps) {
  // 初始化庫存項目（加入唯一 ID）
  const initializeItems = (items: WarehouseInventory[]): InventoryItemWithId[] => {
    return items.map((item, index) => ({
      ...item,
      inventoryId: `inv-${Date.now()}-${index}`,
    }));
  };

  const [items, setItems] = useState<InventoryItemWithId[]>(
    initializeItems(inventories)
  );
  const [searchTerm, setSearchTerm] = useState("");
  const [typeFilter, setTypeFilter] = useState<string>("all");

  // 合併有庫存的商品和只有安全庫存設定的商品
  const mergedProductGroups = useMemo(() => {
    const productGroups: ProductGroup[] = [];
    
    // 取得該倉庫的安全庫存設定
    const warehouseSettings = safetyStockSettings.filter(
      (s) => s.warehouseId === warehouseId
    );
    
    // 建立商品 ID 到商品資訊的映射
    const processedProductIds = new Set<string>();
    
    // 先處理有庫存的商品
    const groupedByProduct: { [productId: string]: InventoryItemWithId[] } = {};
    items.forEach((item) => {
      if (!groupedByProduct[item.productId]) {
        groupedByProduct[item.productId] = [];
      }
      groupedByProduct[item.productId].push(item);
    });
    
    Object.entries(groupedByProduct).forEach(([productId, productItems]) => {
      const safetySetting = warehouseSettings.find((s) => s.productId === productId);
      productGroups.push({
        productId,
        productName: productItems[0].productName,
        items: productItems,
        safetySetting,
      });
      processedProductIds.add(productId);
    });
    
    // 再處理沒有庫存但有安全庫存設定的商品
    warehouseSettings.forEach((setting) => {
      if (!processedProductIds.has(setting.productId)) {
        productGroups.push({
          productId: setting.productId,
          productName: setting.productName,
          items: [], // 沒有任何批號
          safetySetting: setting,
        });
      }
    });
    
    return productGroups;
  }, [items, safetyStockSettings, warehouseId]);

  // 使用篩選 Hook
  const filteredItems = useInventoryFilter(items, searchTerm, typeFilter);

  // 篩選合併後的商品群組
  const filteredProductGroups = useMemo(() => {
    if (!searchTerm && typeFilter === "all") {
      return mergedProductGroups;
    }
    
    return mergedProductGroups.filter((group) => {
      // 搜尋條件
      const matchesSearch = !searchTerm || 
        group.productName.toLowerCase().includes(searchTerm.toLowerCase());
      
      // 類型篩選
      const matchesType = typeFilter === "all" || 
        (group.safetySetting && group.safetySetting.productType === typeFilter);
      
      return matchesSearch && matchesType;
    });
  }, [mergedProductGroups, searchTerm, typeFilter]);

  // 計算統計資訊
  const totalItems = items.length;
  const totalQuantity = items.reduce((sum, item) => sum + item.quantity, 0);
  const lowStockItems = calculateLowStockCount(items, warehouseId, safetyStockSettings);

  // 獲取當前庫存中的商品列表（用於篩選器）
  const productsInInventory = useMemo(() => {
    const uniqueProductIds = Array.from(new Set(items.map((item) => item.productId)));
    return uniqueProductIds
      .map((productId) => AVAILABLE_PRODUCTS.find((p) => p.id === productId))
      .filter((p) => p !== undefined);
  }, [items]);

  // 同步更新本地狀態
  useEffect(() => {
    setItems(initializeItems(inventories));
  }, [inventories]);

  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 className="text-grey-0">庫存管理</span>
        </div>

        <div className="flex items-center justify-between">
          <div>
            <h1 className="mb-2">庫存管理 - {warehouseName}</h1>
            <p className="text-gray-600">設定此倉庫內的商品庫存數量與存放位置</p>
          </div>
          <div className="flex items-center gap-3">
            {/* 安全庫存設定按鈕 */}
            <Button
              onClick={onNavigateToSafetyStock}
              variant="outline"
              className="button-outlined-primary"
            >
              <Shield className="mr-2 h-4 w-4" />
              安全庫存設定
            </Button>

            {/* 庫存警告按鈕 */}
            <Button
              variant="outline"
              className={`button-outlined-primary ${
                lowStockItems > 0
                  ? "border-red-500 text-red-600 hover:bg-red-50"
                  : "border-green-500 text-green-600 hover:bg-green-50"
              }`}
            >
              <AlertTriangle className="mr-2 h-4 w-4" />
              庫存警告：{lowStockItems} 項
            </Button>
            
            {/* 新增庫存按鈕 */}
            <Button
              onClick={onNavigateToAddInventory}
              className="button-filled-primary"
            >
              <PackagePlus className="mr-2 h-4 w-4" />
              新增庫存
            </Button>
          </div>
        </div>
      </div>

      {/* 篩選工具列 */}
      {(items.length > 0 || safetyStockSettings.some(s => s.warehouseId === warehouseId)) && (
        <div className="mb-4">
          <InventoryToolbar
            searchTerm={searchTerm}
            onSearchChange={setSearchTerm}
            typeFilter={typeFilter}
            onTypeFilterChange={setTypeFilter}
          />
        </div>
      )}

      {/* 庫存表格 */}
      <div className="bg-white rounded-lg shadow-sm border overflow-hidden">
        {mergedProductGroups.length === 0 ? (
          <div className="text-center py-12 text-gray-400">
            <p>尚無庫存品項或安全庫存設定</p>
            <p className="text-sm mt-1">點擊「新增庫存」或「安全庫存設定」開始設定</p>
          </div>
        ) : (
          <InventoryTable
            productGroups={filteredProductGroups}
            onEdit={onNavigateToEditInventory}
          />
        )}
      </div>

    </div>
  );
}