/**
 * 採購單管理主頁面
 */

import { useState } from "react";
import { Plus } from "lucide-react";
import { Button } from "./ui/button";
import PurchaseOrderTable from "./PurchaseOrderTable";
import { Breadcrumb } from "./shared/Breadcrumb";
import { PurchaseOrderFilters } from "./purchase-order/PurchaseOrderFilters";
import { type DateRange } from "./filters/DateFilter";
import type { PurchaseOrder, PurchaseOrderStatus, PaymentInfo } from "../types/purchase-order";

interface PurchaseOrderManagementProps {
  orders: PurchaseOrder[];
  onNavigateToInspection: (order: PurchaseOrder) => void;
  onNavigateToCreateOrder: () => void;
  onNavigateToEditOrder: (order: PurchaseOrder) => void;
  onNavigateToViewOrder: (order: PurchaseOrder) => void;
  onDeleteOrder: (id: string) => void;
  onStatusChange: (id: string, newStatus: PurchaseOrderStatus, reviewInfo?: any) => void;
  onPayment: (id: string, paymentInfo: PaymentInfo) => void;
}

export default function PurchaseOrderManagement({
  orders,
  onNavigateToInspection,
  onNavigateToCreateOrder,
  onNavigateToEditOrder,
  onNavigateToViewOrder,
  onDeleteOrder,
  onStatusChange,
  onPayment,
}: PurchaseOrderManagementProps) {
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [requesterFilter, setRequesterFilter] = useState<string>("all");
  const [dateRange, setDateRange] = useState<DateRange | null>(null);

  // 取得唯一門市和倉庫列表
  const stores = Array.from(
    new Set(
      orders
        .filter((o) => o.requesterType === "store")
        .map((o) => o.requesterName)
    )
  ).sort();

  const warehouses = Array.from(
    new Set(
      orders
        .filter((o) => o.requesterType === "warehouse")
        .map((o) => o.requesterName)
    )
  ).sort();

  // 篩選訂單
  const filteredOrders = orders.filter((order) => {
    const matchesSearch =
      order.poNumber.toLowerCase().includes(searchQuery.toLowerCase()) ||
      order.supplierName.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = statusFilter === "all" || order.status === statusFilter;
    
    // 申請單位篩選邏輯
    let matchesRequester = true;
    if (requesterFilter === "all") {
      matchesRequester = true;
    } else if (requesterFilter === "all_stores") {
      matchesRequester = order.requesterType === "store";
    } else if (requesterFilter === "all_warehouses") {
      matchesRequester = order.requesterType === "warehouse";
    } else {
      matchesRequester = order.requesterName === requesterFilter;
    }
    
    // 日期範圍篩選
    const matchesDateRange = !dateRange || (
      order.createdAt >= dateRange.start && order.createdAt <= dateRange.end
    );
    
    return matchesSearch && matchesStatus && matchesRequester && matchesDateRange;
  });

  const handleClearFilters = () => {
    setSearchQuery("");
    setStatusFilter("all");
    setRequesterFilter("all");
    setDateRange(null);
  };

  const hasActiveFilters = searchQuery !== "" || statusFilter !== "all" || requesterFilter !== "all" || dateRange !== null;

  return (
    <div className="p-6">
      {/* Header */}
      <div className="mb-6">
        <Breadcrumb
          items={[
            { label: "採購管理" },
            { label: "管理採購單", active: true },
          ]}
        />
        <div className="flex justify-between items-center">
          <h1>管理採購單</h1>
          <Button
            onClick={onNavigateToCreateOrder}
            className="gap-2 button-filled-primary"
          >
            <Plus className="h-4 w-4" />
            建立採購單
          </Button>
        </div>
      </div>

      {/* 搜尋和篩選區塊 - 獨立卡片 */}
      <div className="mb-6">
        <PurchaseOrderFilters
          searchQuery={searchQuery}
          statusFilter={statusFilter}
          requesterFilter={requesterFilter}
          stores={stores}
          warehouses={warehouses}
          onSearchChange={setSearchQuery}
          onStatusChange={setStatusFilter}
          onRequesterChange={setRequesterFilter}
          onClearFilters={handleClearFilters}
          hasActiveFilters={hasActiveFilters}
          dateRange={dateRange}
          onDateRangeChange={setDateRange}
        />
      </div>

      {/* Table */}
      <PurchaseOrderTable
        orders={filteredOrders}
        onEdit={onNavigateToEditOrder}
        onView={onNavigateToViewOrder}
      />
    </div>
  );
}

// Re-export types for backward compatibility
export type { PurchaseOrder, PurchaseOrderItem, PurchaseOrderStatus, Supplier } from "../types/purchase-order";