import { ReactNode, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
import { Button } from "../ui/button";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { MobileCard } from "../organisms/MobileCard";

export interface TabConfig {
  value: string;
  label: string;
  count: number;
  color?: 'blue' | 'purple' | 'orange' | 'cyan' | 'green' | 'gray';
}

export interface TableColumn {
  key: string;
  label: string;
  className?: string;
  hidden?: 'md' | 'lg' | 'xl' | '2xl';
}

export interface TabbedTableTemplateProps<T> {
  title?: string;
  tabs: TabConfig[];
  defaultTab: string;
  data: T[];
  columns: TableColumn[];
  itemsPerPage?: number;
  
  // 렌더링 함수
  renderMobileCard: (item: T, index: number) => ReactNode;
  renderTableRow: (item: T, index: number, globalIndex: number) => ReactNode;
  
  // 빈 상태 메시지
  emptyMessage?: string;
  
  // 페이지네이션 표시 여부
  showPagination?: boolean;
  
  // 외부에서 탭 변경 감지
  onTabChange?: (tab: string) => void;
}

const colorClasses = {
  blue: {
    active: "border-blue-500 bg-blue-50 shadow-sm",
    inactive: "border-gray-200 hover:border-gray-300 hover:bg-gray-50",
    labelActive: "text-blue-700",
    labelInactive: "text-gray-700",
    countActive: "text-blue-600",
    countInactive: "text-gray-900"
  },
  purple: {
    active: "border-purple-500 bg-purple-50 shadow-sm",
    inactive: "border-gray-200 hover:border-gray-300 hover:bg-gray-50",
    labelActive: "text-purple-700",
    labelInactive: "text-gray-700",
    countActive: "text-purple-600",
    countInactive: "text-gray-900"
  },
  orange: {
    active: "border-orange-500 bg-orange-50 shadow-sm",
    inactive: "border-gray-200 hover:border-gray-300 hover:bg-gray-50",
    labelActive: "text-orange-700",
    labelInactive: "text-gray-700",
    countActive: "text-orange-600",
    countInactive: "text-gray-900"
  },
  cyan: {
    active: "border-cyan-500 bg-cyan-50 shadow-sm",
    inactive: "border-gray-200 hover:border-gray-300 hover:bg-gray-50",
    labelActive: "text-cyan-700",
    labelInactive: "text-gray-700",
    countActive: "text-cyan-600",
    countInactive: "text-gray-900"
  },
  green: {
    active: "border-green-500 bg-green-50 shadow-sm",
    inactive: "border-gray-200 hover:border-gray-300 hover:bg-gray-50",
    labelActive: "text-green-700",
    labelInactive: "text-gray-700",
    countActive: "text-green-600",
    countInactive: "text-gray-900"
  },
  gray: {
    active: "border-gray-500 bg-gray-50 shadow-sm",
    inactive: "border-gray-200 hover:border-gray-300 hover:bg-gray-50",
    labelActive: "text-gray-700",
    labelInactive: "text-gray-700",
    countActive: "text-gray-900",
    countInactive: "text-gray-900"
  }
};

export function TabbedTableTemplate<T>({
  title,
  tabs,
  defaultTab,
  data,
  columns,
  itemsPerPage = 20,
  renderMobileCard,
  renderTableRow,
  emptyMessage = "데이터가 없습니다.",
  showPagination = true,
  onTabChange
}: TabbedTableTemplateProps<T>) {
  const [activeTab, setActiveTab] = useState(defaultTab);
  const [currentPage, setCurrentPage] = useState(1);

  // 탭 변경 핸들러
  const handleTabChange = (tab: string) => {
    setActiveTab(tab);
    setCurrentPage(1); // 탭 변경 시 첫 페이지로
    onTabChange?.(tab);
  };

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

  // 총 카운트 계산
  const totalCount = tabs.reduce((sum, tab) => sum + tab.count, 0);

  // 숨김 클래스 생성
  const getHiddenClass = (hidden?: 'md' | 'lg' | 'xl' | '2xl') => {
    if (!hidden) return '';
    return `hidden ${hidden}:table-cell`;
  };

  return (
    <Card>
      {title && (
        <CardHeader>
          <CardTitle className="text-sm md:text-base">
            {title} ({data.length}개)
          </CardTitle>
        </CardHeader>
      )}
      <CardContent>
        <Tabs value={activeTab} onValueChange={handleTabChange} className="w-full">
          {/* 데스크톱 - 기본 테이블 탭 */}
          <div className="hidden lg:block mb-6">
            <TabsList>
              {tabs.map((tab) => (
                <TabsTrigger key={tab.value} value={tab.value}>
                  {tab.label} ({tab.count})
                </TabsTrigger>
              ))}
            </TabsList>
          </div>

          {/* 모바일 - 커스텀 버튼 탭 */}
          <div className="lg:hidden mb-6">
            <div className="flex flex-wrap gap-2">
              {tabs.map((tab) => {
                const colors = colorClasses[tab.color || 'blue'];
                const isActive = activeTab === tab.value;
                
                return (
                  <button
                    key={tab.value}
                    onClick={() => handleTabChange(tab.value)}
                    className={`flex items-center gap-2 px-4 py-2 rounded-lg border-2 transition-all ${
                      isActive ? colors.active : colors.inactive
                    }`}
                  >
                    <span className={`text-sm font-medium ${
                      isActive ? colors.labelActive : colors.labelInactive
                    }`}>
                      {tab.label}
                    </span>
                    <span className={`text-lg font-semibold ${
                      isActive ? colors.countActive : colors.countInactive
                    }`}>
                      {tab.count}
                    </span>
                  </button>
                );
              })}
            </div>
          </div>

          {/* 탭 컨텐츠 */}
          {tabs.map((tab) => (
            <TabsContent key={tab.value} value={tab.value} className="mt-0">
              {/* 모바일/태블릿 카드 뷰 */}
              <div className="lg:hidden space-y-3">
                {data.length === 0 ? (
                  <div className="text-center py-8 text-muted-foreground border rounded-lg">
                    {emptyMessage}
                  </div>
                ) : (
                  paginatedData.map((item, index) => renderMobileCard(item, index))
                )}
              </div>

              {/* 데스크톱 테이블 뷰 */}
              <div className="hidden lg:block rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      {columns.map((col) => (
                        <TableHead 
                          key={col.key} 
                          className={`${col.className || ''} ${getHiddenClass(col.hidden)}`}
                        >
                          {col.label}
                        </TableHead>
                      ))}
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {data.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={columns.length} className="text-center py-8 text-muted-foreground">
                          {emptyMessage}
                        </TableCell>
                      </TableRow>
                    ) : (
                      paginatedData.map((item, index) => 
                        renderTableRow(item, index, startIndex + index)
                      )
                    )}
                  </TableBody>
                </Table>
              </div>

              {/* 페이지네이션 */}
              {showPagination && totalPages > 1 && (
                <div className="flex items-center justify-between mt-4">
                  <div className="text-sm text-muted-foreground">
                    전체 {data.length}개 중 {startIndex + 1}-{Math.min(endIndex, data.length)}개 표시
                  </div>
                  <div className="flex items-center gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setCurrentPage(1)}
                      disabled={currentPage === 1}
                    >
                      처음
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                      disabled={currentPage === 1}
                    >
                      <ChevronLeft className="h-4 w-4" />
                    </Button>
                    <span className="text-sm">
                      {currentPage} / {totalPages}
                    </span>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                      disabled={currentPage === totalPages}
                    >
                      <ChevronRight className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setCurrentPage(totalPages)}
                      disabled={currentPage === totalPages}
                    >
                      마지막
                    </Button>
                  </div>
                </div>
              )}
            </TabsContent>
          ))}
        </Tabs>
      </CardContent>
    </Card>
  );
}
