/**
 * ResponsiveDataTable
 * 
 * 아토믹 디자인: Organism
 * 
 * 역할: 반응형 데이터 테이블 시스템
 * - 탭 네비게이션 (TabNavigationMolecule)
 * - 데스크톱: 테이블 뷰 (체크박스 선택 포함)
 * - 모바일: 카드 뷰
 * - 빈 상태 처리 (EmptyStateMolecule)
 * 
 * 재사용성: 모든 목록 페이지에서 동일한 테이블 레이아웃 사용 가능
 * 
 * 사용 예시:
 * <ResponsiveDataTable
 *   tabs={tabs}
 *   activeTab={activeTab}
 *   onTabChange={setActiveTab}
 *   data={filteredData}
 *   columns={tableColumns}
 *   selectedItems={selectedItems}
 *   allSelected={allSelected}
 *   onToggleSelectAll={handleSelectAll}
 *   onToggleSelection={handleToggleSelection}
 *   getItemId={(item) => item.id}
 *   renderTableRow={(item, index, globalIndex) => <TableRow>...</TableRow>}
 *   renderMobileCard={(item, index, globalIndex, isSelected, onToggle) => <Card>...</Card>}
 *   startIndex={0}
 * />
 */

import { ReactNode, Fragment } from "react";
import { Tabs, TabsContent } from "../ui/tabs";
import { Table, TableBody } from "../ui/table";
import { TabNavigationMolecule, TabItem } from "../molecules/TabNavigationMolecule";
import { TableHeaderMolecule, TableColumn } from "../molecules/TableHeaderMolecule";
import { EmptyStateMolecule } from "../molecules/EmptyStateMolecule";

interface ResponsiveDataTableProps<T = any> {
  // 탭 설정
  tabs: TabItem[];
  activeTab: string;
  onTabChange: (value: string) => void;

  // 데이터
  data: T[];
  columns: TableColumn[];

  // 선택 기능
  selectedItems: Set<string>;
  allSelected: boolean;
  onToggleSelectAll: (checked: boolean) => void;
  onToggleSelection: (id: string) => void;
  getItemId: (item: T) => string;

  // 렌더링 함수
  renderTableRow: (item: T, index: number, globalIndex: number) => ReactNode;
  renderMobileCard: (
    item: T,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => ReactNode;

  // 페이지네이션
  startIndex?: number;

  // 빈 상태 메시지
  emptyMessage?: string;
}

export function ResponsiveDataTable<T = any>({
  tabs,
  activeTab,
  onTabChange,
  data,
  columns,
  selectedItems,
  allSelected,
  onToggleSelectAll,
  onToggleSelection,
  getItemId,
  renderTableRow,
  renderMobileCard,
  startIndex = 0,
  emptyMessage = "검색 결과가 없습니다.",
}: ResponsiveDataTableProps<T>) {
  return (
    <Tabs value={activeTab} onValueChange={onTabChange} className="w-full">
      {/* 탭 네비게이션 (데스크톱 + 모바일) */}
      <TabNavigationMolecule
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={onTabChange}
      />

      {/* 탭 컨텐츠 */}
      {tabs.map((tab) => (
        <TabsContent key={tab.value} value={tab.value} className="mt-0">
          {/* 모바일/태블릿 카드 뷰 */}
          <div className="lg:hidden space-y-4">
            {data.length === 0 ? (
              <EmptyStateMolecule message={emptyMessage} variant="card" />
            ) : (
              data.map((item, index) => {
                const itemId = getItemId(item);
                const isSelected = selectedItems.has(itemId);
                const globalIndex = startIndex + index;

                return (
                  <div key={itemId}>
                    {renderMobileCard(
                      item,
                      index,
                      globalIndex,
                      isSelected,
                      () => onToggleSelection(itemId)
                    )}
                  </div>
                );
              })
            )}
          </div>

          {/* 데스크톱 테이블 뷰 */}
          <div className="hidden lg:block rounded-md border">
            <Table className="table-fixed">
              <TableHeaderMolecule
                columns={columns}
                allSelected={allSelected}
                onToggleSelectAll={onToggleSelectAll}
                selectedItemsCount={selectedItems.size}
              />
              <TableBody className="[&_tr]:h-14 [&_tr]:min-h-[56px] [&_tr]:max-h-[56px]">
                {data.length === 0 ? (
                  <EmptyStateMolecule
                    message={emptyMessage}
                    variant="table"
                    colSpan={columns.length + 1}
                  />
                ) : (
                  data.map((item, index) => {
                    const itemId = getItemId(item);
                    const globalIndex = startIndex + index;
                    return (
                      <Fragment key={itemId}>
                        {renderTableRow(item, index, globalIndex)}
                      </Fragment>
                    );
                  })
                )}
              </TableBody>
            </Table>
          </div>
        </TabsContent>
      ))}
    </Tabs>
  );
}
