/**
 * 품목관리 - 디자인 시스템 적용 예제
 * 
 * ItemManagement.tsx의 목록 뷰를 디자인 시스템의 유기체/템플릿으로 재구성한 예제입니다.
 * - 검색 필터: SearchFilter 유기체
 * - 통계 카드: StatCards 유기체  
 * - 데스크톱 테이블: DataTable 유기체
 * - 모바일 목록: MobileItemListTemplate 템플릿
 */

import { useState } from "react";
import { Package, Edit, Eye, Trash2 } from "lucide-react";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { StatCards } from "./organisms/StatCards";
import { SearchFilter } from "./organisms/SearchFilter";
import { ListActions } from "./organisms/ListActions";
import { DataTable, Column } from "./organisms/DataTable";
import { MobileItemListTemplate, MobileItemListItem } from "./templates/MobileItemListTemplate";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { useData, ItemMaster } from "./contexts/DataContext";
import { TableAction } from "./molecules/TableActions";
import { toast } from "sonner@2.0.3";

const itemTypeLabels: Record<string, string> = {
  FG: "제품",
  PT: "부품",
  SM: "부자재",
  RM: "원자재",
  CS: "소모품",
};

export function ItemManagement_DesignSystemExample() {
  const { itemMasters, deleteItemMaster } = useData();
  const [searchTerm, setSearchTerm] = useState("");
  const [filterType, setFilterType] = useState<string>("all");
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  // 필터링된 품목
  const filteredItems = itemMasters.filter((item) => {
    const matchesSearch =
      item.itemCode?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.itemName?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.specification?.toLowerCase().includes(searchTerm.toLowerCase());

    const matchesType = filterType === "all" || item.itemType === filterType;

    return matchesSearch && matchesType;
  });

  // 페이지네이션
  const totalPages = Math.ceil(filteredItems.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const paginatedItems = filteredItems.slice(startIndex, endIndex);

  // 통계 데이터
  const stats = [
    {
      label: "전체 품목",
      value: itemMasters.length,
      icon: Package,
      iconColor: "text-blue-600",
    },
    {
      label: "제품",
      value: itemMasters.filter((i) => i.itemType === "FG").length,
      icon: Package,
      iconColor: "text-purple-600",
    },
    {
      label: "부품",
      value: itemMasters.filter((i) => i.itemType === "PT").length,
      icon: Package,
      iconColor: "text-orange-600",
    },
    {
      label: "부자재",
      value: itemMasters.filter((i) => i.itemType === "SM").length,
      icon: Package,
      iconColor: "text-green-600",
    },
    {
      label: "원자재",
      value: itemMasters.filter((i) => i.itemType === "RM").length,
      icon: Package,
      iconColor: "text-cyan-600",
    },
    {
      label: "소모품",
      value: itemMasters.filter((i) => i.itemType === "CS").length,
      icon: Package,
      iconColor: "text-gray-600",
    },
  ];

  // 핸들러
  const handleView = (item: ItemMaster) => {
    toast.info(`상세: ${item.itemName}`);
  };

  const handleEdit = (item: ItemMaster) => {
    toast.info(`수정: ${item.itemName}`);
  };

  const handleDelete = (itemId: string) => {
    const item = itemMasters.find((i) => i.id === itemId);
    if (item && confirm(`${item.itemName}을(를) 삭제하시겠습니까?`)) {
      deleteItemMaster(itemId);
      toast.success("품목이 삭제되었습니다");
    }
  };

  // MobileItemListItem 형식으로 변환
  const mobileItems: MobileItemListItem[] = paginatedItems.map((item) => ({
    id: item.id,
    itemCode: item.itemCode,
    itemName: item.itemName,
    itemType: item.itemType,
    specification: item.specification,
    unit: item.unit,
    purchasePrice: item.purchasePrice,
    salesPrice: item.salesPrice,
    isActive: item.isActive,
  }));

  // DataTable용 컬럼 정의
  const tableColumns: Column<ItemMaster>[] = [
    {
      key: "itemCode",
      label: "품목코드",
      type: "text",
      width: "150px",
    },
    {
      key: "itemType",
      label: "품목유형",
      type: "badge",
      width: "100px",
      render: (value) => itemTypeLabels[value as string] || value,
      badgeConfig: {
        variant: "secondary",
      },
    },
    {
      key: "itemName",
      label: "품목명",
      type: "text",
      width: "200px",
    },
    {
      key: "specification",
      label: "규격",
      type: "text",
      width: "150px",
    },
    {
      key: "unit",
      label: "단위",
      type: "badge",
      width: "80px",
      badgeConfig: {
        variant: "outline",
      },
    },
    {
      key: "purchasePrice",
      label: "구매단가",
      type: "currency",
      width: "120px",
    },
    {
      key: "salesPrice",
      label: "판매단가",
      type: "currency",
      width: "120px",
    },
    {
      key: "id",
      label: "작업",
      type: "actions",
      width: "150px",
      render: (_, row) => {
        const actions: TableAction[] = [
          {
            label: "상세",
            icon: Eye,
            variant: "ghost",
            onClick: () => handleView(row),
          },
          {
            label: "수정",
            icon: Edit,
            variant: "ghost",
            onClick: () => handleEdit(row),
          },
          {
            label: "삭제",
            icon: Trash2,
            variant: "ghost",
            onClick: () => handleDelete(row.id),
          },
        ];
        return actions;
      },
    },
  ];

  return (
    <PageLayout maxWidth="full">
      <PageHeader
        title="품목 관리 (디자인 시스템)"
        description="디자인 시스템의 유기체와 템플릿을 활용한 품목관리 예제"
        icon={Package}
        actions={
          <ListActions
            onAdd={() => toast.info("품목 등록")}
            addText="품목 등록"
          />
        }
      />

      {/* 통계 카드 - StatCards 유기체 */}
      <StatCards stats={stats} />

      {/* 검색 및 필터 - SearchFilter 유기체 */}
      <Card>
        <CardContent className="p-4 md:p-6">
          <SearchFilter
            searchValue={searchTerm}
            onSearchChange={setSearchTerm}
            searchPlaceholder="품목코드, 품목명, 규격 검색..."
            filterButton={false}
            extraActions={
              <Select value={filterType} onValueChange={setFilterType}>
                <SelectTrigger className="w-[180px]">
                  <SelectValue placeholder="품목 유형" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">전체 ({itemMasters.length})</SelectItem>
                  <SelectItem value="FG">
                    제품 ({itemMasters.filter((i) => i.itemType === "FG").length})
                  </SelectItem>
                  <SelectItem value="PT">
                    부품 ({itemMasters.filter((i) => i.itemType === "PT").length})
                  </SelectItem>
                  <SelectItem value="SM">
                    부자재 ({itemMasters.filter((i) => i.itemType === "SM").length})
                  </SelectItem>
                  <SelectItem value="RM">
                    원자재 ({itemMasters.filter((i) => i.itemType === "RM").length})
                  </SelectItem>
                  <SelectItem value="CS">
                    소모품 ({itemMasters.filter((i) => i.itemType === "CS").length})
                  </SelectItem>
                </SelectContent>
              </Select>
            }
          />
        </CardContent>
      </Card>

      {/* 품목 목록 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-sm md:text-base">
            {filterType === "all" && `전체 목록 (${filteredItems.length}개)`}
            {filterType === "FG" && `제품 목록 (${filteredItems.length}개)`}
            {filterType === "PT" && `부품 목록 (${filteredItems.length}개)`}
            {filterType === "RM" && `원자재 목록 (${filteredItems.length}개)`}
            {filterType === "SM" && `부자재 목록 (${filteredItems.length}개)`}
            {filterType === "CS" && `소모품 목록 (${filteredItems.length}개)`}
          </CardTitle>
        </CardHeader>
        <CardContent>
          {/* 모바일 목록 - MobileItemListTemplate 템플릿 */}
          <div className="md:hidden">
            <MobileItemListTemplate
              items={mobileItems}
              searchValue={searchTerm}
              onSearchChange={setSearchTerm}
              filterType={filterType}
              onFilterChange={setFilterType}
              currentPage={currentPage}
              onPageChange={setCurrentPage}
              itemsPerPage={itemsPerPage}
              onView={(item) => {
                const original = paginatedItems.find((i) => i.id === item.id);
                if (original) handleView(original);
              }}
              onEdit={(item) => {
                const original = paginatedItems.find((i) => i.id === item.id);
                if (original) handleEdit(original);
              }}
              onDelete={handleDelete}
              showActions={true}
              canViewPrice={true}
            />
          </div>

          {/* 데스크톱 테이블 - DataTable 유기체 */}
          <div className="hidden md:block">
            <DataTable
              columns={tableColumns}
              data={paginatedItems}
              keyField="id"
              onRowClick={handleView}
              pagination={{
                currentPage,
                totalPages,
                onPageChange: setCurrentPage,
                showInfo: true,
              }}
              striped
              hoverable
              emptyMessage="품목이 없습니다"
            />
          </div>
        </CardContent>
      </Card>
    </PageLayout>
  );
}
