/**
 * ItemManagement 목록 뷰 헬퍼
 * 
 * 데스크톱 테이블과 모바일 카드 목록을 디자인 시스템 컴포넌트로 렌더링
 */

import { ItemMaster } from "./contexts/DataContext";
import { MobileItemListTemplate, MobileItemListItem } from "./templates/MobileItemListTemplate";
import { DataTable, Column } from "./organisms/DataTable";
import { Badge } from "./ui/badge";
import { Edit, Eye, Trash2 } from "lucide-react";
import { TableAction } from "./molecules/TableActions";

interface ListViewHelperProps {
  items: ItemMaster[];
  searchTerm: string;
  filterType: string;
  currentPage: number;
  itemsPerPage: number;
  onSearchChange: (value: string) => void;
  onFilterChange: (value: string) => void;
  onPageChange: (page: number) => void;
  onView: (item: ItemMaster) => void;
  onEdit: (item: ItemMaster) => void;
  onDelete: (itemId: string) => void;
  canViewPrice?: boolean;
}

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

// ItemMaster를 MobileItemListItem으로 변환
function convertToMobileItem(item: ItemMaster): MobileItemListItem {
  return {
    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용 컬럼 정의
function getTableColumns(
  onView: (item: ItemMaster) => void,
  onEdit: (item: ItemMaster) => void,
  onDelete: (itemId: string) => void,
  canViewPrice: boolean
): Column<ItemMaster>[] {
  const columns: 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",
      },
    },
  ];

  // 단가 컬럼 추가 (권한이 있을 경우)
  if (canViewPrice) {
    columns.push({
      key: "purchasePrice",
      label: "구매단가",
      type: "currency",
      width: "120px",
    });
    columns.push({
      key: "salesPrice",
      label: "판매단가",
      type: "currency",
      width: "120px",
    });
  }

  // 액션 컬럼
  columns.push({
    key: "id",
    label: "작업",
    type: "actions",
    width: "150px",
    render: (_, row) => {
      const actions: TableAction[] = [
        {
          label: "상세",
          icon: Eye,
          variant: "ghost",
          onClick: () => onView(row),
        },
        {
          label: "수정",
          icon: Edit,
          variant: "ghost",
          onClick: () => onEdit(row),
        },
        {
          label: "삭제",
          icon: Trash2,
          variant: "ghost",
          onClick: () => onDelete(row.id),
        },
      ];
      return actions;
    },
  });

  return columns;
}

export function ItemListView({
  items,
  searchTerm,
  filterType,
  currentPage,
  itemsPerPage,
  onSearchChange,
  onFilterChange,
  onPageChange,
  onView,
  onEdit,
  onDelete,
  canViewPrice = true,
}: ListViewHelperProps) {
  // MobileItemListItem 형식으로 변환
  const mobileItems = items.map(convertToMobileItem);

  // DataTable용 컬럼
  const tableColumns = getTableColumns(onView, onEdit, onDelete, canViewPrice);

  // 페이지네이션 계산
  const totalPages = Math.ceil(items.length / itemsPerPage);

  return (
    <>
      {/* 모바일 목록 - MobileItemListTemplate 사용 */}
      <div className="md:hidden">
        <MobileItemListTemplate
          items={mobileItems}
          searchValue={searchTerm}
          onSearchChange={onSearchChange}
          filterType={filterType}
          onFilterChange={onFilterChange}
          currentPage={currentPage}
          onPageChange={onPageChange}
          itemsPerPage={itemsPerPage}
          onView={(item) => {
            const original = items.find(i => i.id === item.id);
            if (original) onView(original);
          }}
          onEdit={(item) => {
            const original = items.find(i => i.id === item.id);
            if (original) onEdit(original);
          }}
          onDelete={onDelete}
          showActions={true}
          canViewPrice={canViewPrice}
        />
      </div>

      {/* 데스크톱 테이블 - DataTable 사용 */}
      <div className="hidden md:block">
        <DataTable
          columns={tableColumns}
          data={items}
          keyField="id"
          onRowClick={onView}
          pagination={{
            currentPage,
            totalPages,
            onPageChange,
            showInfo: true,
          }}
          striped
          hoverable
          emptyMessage="품목이 없습니다"
        />
      </div>
    </>
  );
}
