/**
 * 應用程式主元件
 */

import { useState } from "react";
import NavigationSidebar from "./components/NavigationSidebar";
import VendorManagement from "./components/VendorManagement/VendorManagement";
import VendorDetail from "./components/VendorManagement/VendorDetail";
import { Toaster } from "./components/ui/sonner";
import { useVendors } from "./hooks/useVendors";
import { mockSuppliers } from "./data/mockSuppliers";
import { mockProducts } from "./data/mockProducts";
import { ROUTES } from "./constants/app";

export default function App() {
  const [currentPage, setCurrentPage] = useState(ROUTES.VENDOR_MANAGEMENT);
  const [selectedVendorId, setSelectedVendorId] = useState<string | null>(null);
  
  const {
    suppliers,
    addSupplier,
    updateSupplier,
    deleteSupplier,
    addSupplyProduct,
    updateSupplyProduct,
    removeSupplyProduct,
  } = useVendors(mockSuppliers, mockProducts);

  // 處理查看廠商詳情
  const handleViewVendorDetail = (vendorId: string) => {
    setSelectedVendorId(vendorId);
    setCurrentPage("vendor-detail");
  };

  // 處理返回廠商列表
  const handleBackToVendorList = () => {
    setSelectedVendorId(null);
    setCurrentPage(ROUTES.VENDOR_MANAGEMENT);
  };

  // 處理導航
  const handleNavigate = (path: string) => {
    setSelectedVendorId(null);
    setCurrentPage(path);
  };

  // 取得選中的廠商
  const selectedVendor = selectedVendorId 
    ? suppliers.find(s => s.id === selectedVendorId) 
    : null;

  // 渲染當前頁面
  const renderPage = () => {
    // 廠商詳情頁
    if (currentPage === "vendor-detail" && selectedVendor) {
      return (
        <VendorDetail
          supplier={selectedVendor}
          products={mockProducts}
          onBack={handleBackToVendorList}
          onAddSupplyProduct={addSupplyProduct}
          onUpdateSupplyProduct={updateSupplyProduct}
          onRemoveSupplyProduct={removeSupplyProduct}
        />
      );
    }

    // 廠商管理頁面
    return (
      <VendorManagement
        suppliers={suppliers}
        products={mockProducts}
        onAddSupplier={addSupplier}
        onUpdateSupplier={updateSupplier}
        onDeleteSupplier={deleteSupplier}
        onViewDetail={handleViewVendorDetail}
      />
    );
  };

  return (
    <div className="flex min-h-screen bg-background">
      {/* 側邊欄導航 */}
      <NavigationSidebar currentPath={currentPage} onNavigate={handleNavigate} />

      {/* 主要內容區 */}
      <main className="flex-1 overflow-auto">{renderPage()}</main>

      {/* Toast 通知 */}
      <Toaster />
    </div>
  );
}
