/**
 * 반응형 목록 템플릿 (데스크톱/태블릿/모바일)
 * 
 * 품목관리를 기반으로 한 완전한 반응형 목록 템플릿입니다.
 * - 데스크톱: 탭 + DataTable
 * - 태블릿: 탭 + DataTable (축소)
 * - 모바일: 커스텀 버튼 탭 + 카드 리스트
 * 
 * 사용된 컴포넌트:
 * - Atoms: Badge, Button, Checkbox, Input
 * - Molecules: SearchFilter, TableActionButtons
 * - Organisms: PageLayout, PageHeader, StatCards, DataTable
 * - Templates: ResponsiveListTemplate
 */

import { ReactNode, useState } from "react";
import { LucideIcon } from "lucide-react";
import { PageLayout } from "../organisms/PageLayout";
import { PageHeader } from "../organisms/PageHeader";
import { StatCards, StatCardProps } from "../organisms/StatCards";
import { SearchFilter } from "../organisms/SearchFilter";
import { DataTable, Column } from "../organisms/DataTable";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
import { Badge } from "../ui/badge";
import { Checkbox } from "../ui/checkbox";

// 탭 구성
export interface TabConfig {
  value: string;
  label: string;
  count?: number;
  color?: "blue" | "purple" | "orange" | "cyan" | "green" | "gray" | "red" | "indigo";
}

// 모바일 카드 필드
export interface MobileCardField {
  label: string;
  value: string | ReactNode;
  badge?: boolean;
  badgeVariant?: "default" | "secondary" | "outline" | "destructive";
}

// Props
export interface ResponsiveListTemplateProps<T> {
  // 페이지 헤더
  title: string;
  description?: string;
  icon?: LucideIcon;
  headerActions?: ReactNode;

  // 통계 카드
  stats?: StatCardProps[];

  // 검색 및 필터
  searchValue?: string;
  onSearchChange?: (value: string) => void;
  searchPlaceholder?: string;
  extraFilters?: ReactNode;

  // 탭 구성
  tabs: TabConfig[];
  currentTab: string;
  onTabChange: (value: string) => void;

  // 데이터
  data: T[];
  keyField: keyof T;

  // 데스크톱 테이블
  columns: Column<T>[];
  onRowClick?: (row: T) => void;

  // 모바일 카드
  renderMobileCard?: (item: T, index: number) => ReactNode;

  // 선택 기능
  selectable?: boolean;
  selectedIds?: Set<string>;
  onToggleSelection?: (id: string) => void;

  // 카드 제목
  cardTitle?: string | ((currentTab: string, count: number) => string);

  // 메시지
  emptyMessage?: string;

  // 레이아웃
  maxWidth?: "sm" | "md" | "lg" | "xl" | "full";
}

export function ResponsiveListTemplate<T extends { id: string }>({
  title,
  description,
  icon,
  headerActions,
  stats,
  searchValue,
  onSearchChange,
  searchPlaceholder = "검색...",
  extraFilters,
  tabs,
  currentTab,
  onTabChange,
  data,
  keyField,
  columns,
  onRowClick,
  renderMobileCard,
  selectable = false,
  selectedIds = new Set(),
  onToggleSelection,
  cardTitle,
  emptyMessage = "데이터가 없습니다",
  maxWidth = "full",
}: ResponsiveListTemplateProps<T>) {
  // 탭 색상 매핑
  const getTabColorClasses = (color: TabConfig["color"], isActive: boolean) => {
    const colorMap = {
      blue: {
        border: isActive ? "border-blue-500 bg-blue-50" : "border-gray-200",
        text: isActive ? "text-blue-700" : "text-gray-700",
        count: isActive ? "text-blue-600" : "text-gray-900",
      },
      purple: {
        border: isActive ? "border-purple-500 bg-purple-50" : "border-gray-200",
        text: isActive ? "text-purple-700" : "text-gray-700",
        count: isActive ? "text-purple-600" : "text-gray-900",
      },
      orange: {
        border: isActive ? "border-orange-500 bg-orange-50" : "border-gray-200",
        text: isActive ? "text-orange-700" : "text-gray-700",
        count: isActive ? "text-orange-600" : "text-gray-900",
      },
      cyan: {
        border: isActive ? "border-cyan-500 bg-cyan-50" : "border-gray-200",
        text: isActive ? "text-cyan-700" : "text-gray-700",
        count: isActive ? "text-cyan-600" : "text-gray-900",
      },
      green: {
        border: isActive ? "border-green-500 bg-green-50" : "border-gray-200",
        text: isActive ? "text-green-700" : "text-gray-700",
        count: isActive ? "text-green-600" : "text-gray-900",
      },
      gray: {
        border: isActive ? "border-gray-500 bg-gray-50" : "border-gray-200",
        text: isActive ? "text-gray-700" : "text-gray-700",
        count: isActive ? "text-gray-900" : "text-gray-900",
      },
      red: {
        border: isActive ? "border-red-500 bg-red-50" : "border-gray-200",
        text: isActive ? "text-red-700" : "text-gray-700",
        count: isActive ? "text-red-600" : "text-gray-900",
      },
      indigo: {
        border: isActive ? "border-indigo-500 bg-indigo-50" : "border-gray-200",
        text: isActive ? "text-indigo-700" : "text-gray-700",
        count: isActive ? "text-indigo-600" : "text-gray-900",
      },
    };

    return colorMap[color || "blue"] || colorMap.blue;
  };

  // 카드 제목 생성
  const getCardTitle = () => {
    if (typeof cardTitle === "function") {
      return cardTitle(currentTab, data.length);
    }
    if (cardTitle) {
      return cardTitle;
    }
    const currentTabConfig = tabs.find((t) => t.value === currentTab);
    return `${currentTabConfig?.label || "목록"} (${data.length}개)`;
  };

  return (
    <PageLayout maxWidth={maxWidth}>
      {/* 페이지 헤더 */}
      <PageHeader
        title={title}
        description={description}
        icon={icon}
        actions={headerActions}
      />

      {/* 통계 카드 - 태블릿/데스크톱 */}
      {stats && stats.length > 0 && (
        <div className="hidden md:block">
          <StatCards stats={stats} />
        </div>
      )}

      {/* 검색 및 필터 */}
      {(onSearchChange || extraFilters) && (
        <Card>
          <CardContent className="p-4 md:p-6">
            <SearchFilter
              searchValue={searchValue || ""}
              onSearchChange={onSearchChange || (() => {})}
              searchPlaceholder={searchPlaceholder}
              filterButton={false}
              extraActions={extraFilters}
            />
          </CardContent>
        </Card>
      )}

      {/* 목록 카드 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-sm md:text-base">{getCardTitle()}</CardTitle>
        </CardHeader>
        <CardContent>
          <Tabs value={currentTab} onValueChange={onTabChange} className="w-full">
            {/* 데스크톱 (1280px+) - 기본 테이블 탭 */}
            <div className="hidden xl:block mb-6">
              <TabsList>
                {tabs.map((tab) => (
                  <TabsTrigger key={tab.value} value={tab.value}>
                    {tab.label} {tab.count !== undefined && `(${tab.count})`}
                  </TabsTrigger>
                ))}
              </TabsList>
            </div>

            {/* 모바일/태블릿/소형 노트북 (~1279px) - 커스텀 버튼 탭 */}
            <div className="xl:hidden mb-6">
              <div className="flex flex-wrap gap-2">
                {tabs.map((tab) => {
                  const isActive = currentTab === tab.value;
                  const colorClasses = getTabColorClasses(tab.color, isActive);

                  return (
                    <button
                      key={tab.value}
                      onClick={() => onTabChange(tab.value)}
                      className={`flex items-center gap-2 px-4 py-2 rounded-lg border-2 transition-all ${
                        colorClasses.border
                      } ${
                        isActive ? "shadow-sm" : "hover:border-gray-300 hover:bg-gray-50"
                      }`}
                    >
                      <span className={`text-sm font-medium ${colorClasses.text}`}>
                        {tab.label}
                      </span>
                      {tab.count !== undefined && (
                        <span className={`text-lg font-semibold ${colorClasses.count}`}>
                          {tab.count}
                        </span>
                      )}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* 탭 컨텐츠 */}
            <TabsContent value={currentTab} className="mt-0">
              {/* 데스크톱 (1280px+) - DataTable */}
              <div className="hidden xl:block overflow-x-auto">
                <DataTable
                  columns={columns}
                  data={data}
                  keyField={keyField as string}
                  onRowClick={onRowClick}
                  striped
                  hoverable
                  emptyMessage={emptyMessage}
                />
              </div>

              {/* 모바일/태블릿/소형 노트북 (~1279px) - 카드 리스트 */}
              <div className="xl:hidden space-y-3 md:space-y-0 md:grid md:grid-cols-2 md:gap-4 lg:grid-cols-3">
                {data.length === 0 ? (
                  <div className="text-center py-8 text-muted-foreground border rounded-lg">
                    {emptyMessage}
                  </div>
                ) : (
                  data.map((item, index) =>
                    renderMobileCard ? (
                      <div key={String(item[keyField])}>{renderMobileCard(item, index)}</div>
                    ) : (
                      <div
                        key={String(item[keyField])}
                        className="border rounded-lg p-4 space-y-3 bg-white dark:bg-card hover:bg-muted/50 transition-colors shadow-sm"
                      >
                        {selectable && onToggleSelection && (
                          <Checkbox
                            checked={selectedIds.has(item.id)}
                            onCheckedChange={() => onToggleSelection(item.id)}
                            onClick={(e) => e.stopPropagation()}
                          />
                        )}
                        <div className="text-sm">
                          기본 모바일 카드 - renderMobileCard prop을 제공하세요
                        </div>
                      </div>
                    )
                  )
                )}
              </div>
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>
    </PageLayout>
  );
}

// 헬퍼: 기본 모바일 카드 렌더러 생성
export function createMobileCardRenderer<T extends { id: string }>(config: {
  getTitle: (item: T) => string;
  getSubtitle?: (item: T) => string;
  getBadge?: (item: T) => { label: string; variant?: "default" | "secondary" | "outline" | "destructive" };
  getFields: (item: T) => MobileCardField[];
  getActions?: (item: T) => ReactNode;
  selectable?: boolean;
  selectedIds?: Set<string>;
  onToggleSelection?: (id: string) => void;
  getNumber?: (item: T, index: number, total: number) => string | number;
}) {
  return (item: T, index: number, total?: number) => {
    const badge = config.getBadge?.(item);
    const fields = config.getFields(item);

    return (
      <div className="border rounded-lg p-4 space-y-3 bg-white dark:bg-card hover:bg-muted/50 transition-colors shadow-sm">
        {/* 번호와 체크박스 */}
        <div className="flex items-start gap-3">
          {config.selectable && config.onToggleSelection && config.selectedIds && (
            <Checkbox
              checked={config.selectedIds.has(item.id)}
              onCheckedChange={() => config.onToggleSelection!(item.id)}
              onClick={(e) => e.stopPropagation()}
              className="mt-1"
            />
          )}
          <div className="flex-1 min-w-0 space-y-3">
            {/* 번호 */}
            {config.getNumber && total && (
              <Badge variant="outline" className="bg-gray-100 text-gray-700 font-mono text-xs">
                #{config.getNumber(item, index, total)}
              </Badge>
            )}

            {/* 제목 */}
            <div className="font-semibold text-base">{config.getTitle(item)}</div>

            {/* 부제목 */}
            {config.getSubtitle && (
              <div className="text-sm text-muted-foreground">{config.getSubtitle(item)}</div>
            )}

            {/* 뱃지 */}
            {badge && (
              <Badge variant={badge.variant || "default"}>{badge.label}</Badge>
            )}

            {/* 필드 */}
            <div className="grid grid-cols-2 gap-2 text-sm">
              {fields.map((field, idx) => (
                <div key={idx} className="space-y-1">
                  <div className="text-xs text-muted-foreground">{field.label}</div>
                  {field.badge ? (
                    <Badge variant={field.badgeVariant || "default"}>{field.value}</Badge>
                  ) : (
                    <div className="font-medium">{field.value}</div>
                  )}
                </div>
              ))}
            </div>

            {/* 액션 */}
            {config.getActions && <div className="pt-2">{config.getActions(item)}</div>}
          </div>
        </div>
      </div>
    );
  };
}