import React, { useState } from "react";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
import { Badge } from "../ui/badge";
import { Checkbox } from "../ui/checkbox";
import { Plus, Search, Filter, Edit, Trash2, Package, ChevronLeft, ChevronRight } from "lucide-react";
import { PageLayout } from "../organisms/PageLayout";
import { PageHeader } from "../organisms/PageHeader";

export interface BasicListTemplateProps {
  // 페이지 정보
  title: string;
  subtitle?: string;
  
  // 탭 정보
  tabs?: {
    value: string;
    label: string;
    count?: number;
    color?: string;
  }[];
  
  // 테이블 컬럼
  columns: {
    key: string;
    label: string;
    width?: string;
    align?: "left" | "center" | "right";
  }[];
  
  // 데이터
  data: any[];
  
  // 체크박스 선택
  selectable?: boolean;
  selectedIds?: Set<string>;
  onSelectionChange?: (ids: Set<string>) => void;
  
  // 액션
  onAdd?: () => void;
  onEdit?: (item: any) => void;
  onDelete?: (item: any) => void;
  onRowClick?: (item: any) => void;
  
  // 검색
  searchable?: boolean;
  onSearch?: (query: string) => void;
  
  // 필터
  filterable?: boolean;
  onFilter?: () => void;
  
  // 페이지네이션
  pagination?: {
    currentPage: number;
    totalPages: number;
    onPageChange: (page: number) => void;
  };
  
  // 커스텀 렌더러
  renderCell?: (item: any, column: { key: string; label: string }) => React.ReactNode;
  renderMobileCard?: (item: any, index: number) => React.ReactNode;
}

export function BasicListTemplate({
  title,
  subtitle,
  tabs,
  columns,
  data,
  selectable = false,
  selectedIds = new Set(),
  onSelectionChange,
  onAdd,
  onEdit,
  onDelete,
  onRowClick,
  searchable = false,
  onSearch,
  filterable = false,
  onFilter,
  pagination,
  renderCell,
  renderMobileCard,
}: BasicListTemplateProps) {
  const [activeTab, setActiveTab] = useState(tabs?.[0]?.value || "all");
  const [searchQuery, setSearchQuery] = useState("");

  // 전체 선택/해제
  const toggleSelectAll = () => {
    if (!onSelectionChange) return;
    
    if (selectedIds.size === data.length) {
      onSelectionChange(new Set());
    } else {
      onSelectionChange(new Set(data.map(item => item.id)));
    }
  };

  // 개별 선택/해제
  const toggleSelect = (id: string) => {
    if (!onSelectionChange) return;
    
    const newSelected = new Set(selectedIds);
    if (newSelected.has(id)) {
      newSelected.delete(id);
    } else {
      newSelected.add(id);
    }
    onSelectionChange(newSelected);
  };

  // 검색 처리
  const handleSearch = (query: string) => {
    setSearchQuery(query);
    onSearch?.(query);
  };

  // 셀 기본 렌더러
  const defaultRenderCell = (item: any, column: { key: string }) => {
    const value = item[column.key];
    
    // Badge 타입 처리
    if (typeof value === "object" && value?.type === "badge") {
      return (
        <Badge variant={value.variant || "default"} className={value.className}>
          {value.label}
        </Badge>
      );
    }
    
    return value || "-";
  };

  // 기본 모바일 카드 렌더러
  const defaultRenderMobileCard = (item: any, index: number) => (
    <div className="border rounded-lg p-4 space-y-3 bg-white hover:bg-muted/50 transition-colors shadow-sm">
      <div className="flex items-start gap-3">
        {selectable && (
          <Checkbox
            checked={selectedIds.has(item.id)}
            onCheckedChange={() => toggleSelect(item.id)}
            className="mt-1"
          />
        )}
        
        <div className="flex-1 min-w-0 space-y-3">
          {/* 번호 */}
          <div className="flex items-center gap-2 flex-wrap">
            <Badge variant="outline" className="bg-gray-100 text-gray-700 font-mono text-xs">
              #{index + 1}
            </Badge>
          </div>
          
          {/* 내용 */}
          <div className="space-y-2">
            {columns.slice(1).map((column) => (
              <div key={column.key}>
                <span className="text-muted-foreground text-xs">{column.label}</span>
                <div className="mt-1">
                  {renderCell ? renderCell(item, column) : defaultRenderCell(item, column)}
                </div>
              </div>
            ))}
          </div>

          {/* 액션 버튼 */}
          {(onEdit || onDelete) && (
            <div className="flex gap-2 pt-2 border-t">
              {onEdit && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    onEdit(item);
                  }}
                  className="flex-1"
                >
                  <Edit className="h-4 w-4 mr-1" />
                  수정
                </Button>
              )}
              {onDelete && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation();
                    onDelete(item);
                  }}
                  className="flex-1"
                >
                  <Trash2 className="h-4 w-4 mr-1 text-red-500" />
                  삭제
                </Button>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );

  return (
    <PageLayout maxWidth="full">
      <PageHeader
        title={title}
        subtitle={subtitle}
        actions={
          <div className="flex gap-2">
            {searchable && (
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="검색..."
                  value={searchQuery}
                  onChange={(e) => handleSearch(e.target.value)}
                  className="pl-9 w-64"
                />
              </div>
            )}
            {filterable && (
              <Button variant="outline" onClick={onFilter}>
                <Filter className="h-4 w-4 mr-2" />
                필터
              </Button>
            )}
            {onAdd && (
              <Button onClick={onAdd}>
                <Plus className="h-4 w-4 mr-2" />
                등록
              </Button>
            )}
          </div>
        }
      />

      <Card>
        {tabs && tabs.length > 0 && (
          <CardHeader className="border-b pb-0">
            <Tabs value={activeTab} onValueChange={setActiveTab}>
              <TabsList className="w-full justify-start bg-transparent border-b-0 h-auto p-0">
                {tabs.map((tab) => (
                  <TabsTrigger
                    key={tab.value}
                    value={tab.value}
                    className="relative rounded-none border-b-2 border-transparent data-[state=active]:border-blue-600 data-[state=active]:bg-transparent px-6 py-3"
                  >
                    <span className={tab.color || ""}>{tab.label}</span>
                    {tab.count !== undefined && (
                      <Badge
                        variant="secondary"
                        className={`ml-2 ${activeTab === tab.value ? tab.color : ""}`}
                      >
                        {tab.count}
                      </Badge>
                    )}
                  </TabsTrigger>
                ))}
              </TabsList>
            </Tabs>
          </CardHeader>
        )}

        <CardContent className="p-0">
          {/* 데스크톱 테이블 뷰 */}
          <div className="hidden lg:block overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  {selectable && (
                    <TableHead className="w-12">
                      <Checkbox
                        checked={selectedIds.size === data.length && data.length > 0}
                        onCheckedChange={toggleSelectAll}
                      />
                    </TableHead>
                  )}
                  <TableHead className="w-16 text-center">번호</TableHead>
                  {columns.map((column) => (
                    <TableHead
                      key={column.key}
                      className={`${column.width ? `w-[${column.width}]` : ""} ${
                        column.align === "center" ? "text-center" :
                        column.align === "right" ? "text-right" : ""
                      }`}
                    >
                      {column.label}
                    </TableHead>
                  ))}
                  {(onEdit || onDelete) && (
                    <TableHead className="w-32 text-center">작업</TableHead>
                  )}
                </TableRow>
              </TableHeader>
              <TableBody>
                {data.length === 0 ? (
                  <TableRow>
                    <TableCell
                      colSpan={columns.length + (selectable ? 2 : 1) + (onEdit || onDelete ? 1 : 0)}
                      className="text-center py-8 text-muted-foreground"
                    >
                      <Package className="w-12 h-12 mx-auto mb-3 text-muted-foreground opacity-50" />
                      <p>데이터가 없습니다.</p>
                    </TableCell>
                  </TableRow>
                ) : (
                  data.map((item, index) => (
                    <TableRow
                      key={item.id}
                      onClick={() => onRowClick?.(item)}
                      className={onRowClick ? "cursor-pointer hover:bg-muted/50" : ""}
                    >
                      {selectable && (
                        <TableCell>
                          <Checkbox
                            checked={selectedIds.has(item.id)}
                            onCheckedChange={() => toggleSelect(item.id)}
                            onClick={(e) => e.stopPropagation()}
                          />
                        </TableCell>
                      )}
                      <TableCell className="text-center text-muted-foreground">
                        {index + 1}
                      </TableCell>
                      {columns.map((column) => (
                        <TableCell
                          key={column.key}
                          className={
                            column.align === "center" ? "text-center" :
                            column.align === "right" ? "text-right" : ""
                          }
                        >
                          {renderCell ? renderCell(item, column) : defaultRenderCell(item, column)}
                        </TableCell>
                      ))}
                      {(onEdit || onDelete) && (
                        <TableCell>
                          <div className="flex gap-2 justify-center">
                            {onEdit && (
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  onEdit(item);
                                }}
                              >
                                <Edit className="h-4 w-4" />
                              </Button>
                            )}
                            {onDelete && (
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  onDelete(item);
                                }}
                              >
                                <Trash2 className="h-4 w-4 text-red-500" />
                              </Button>
                            )}
                          </div>
                        </TableCell>
                      )}
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>

          {/* 태블릿/모바일 카드 뷰 */}
          <div className="lg:hidden p-4 space-y-3">
            {data.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                <Package className="w-12 h-12 mx-auto mb-3 opacity-50" />
                <p>데이터가 없습니다.</p>
              </div>
            ) : (
              data.map((item, index) => (
                <div key={item.id}>
                  {renderMobileCard ? renderMobileCard(item, index) : defaultRenderMobileCard(item, index)}
                </div>
              ))
            )}
          </div>

          {/* 페이지네이션 */}
          {pagination && pagination.totalPages > 1 && (
            <div className="flex items-center justify-between p-4 border-t">
              <p className="text-sm text-muted-foreground">
                페이지 {pagination.currentPage} / {pagination.totalPages}
              </p>
              <div className="flex gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => pagination.onPageChange(pagination.currentPage - 1)}
                  disabled={pagination.currentPage === 1}
                >
                  <ChevronLeft className="w-4 h-4" />
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => pagination.onPageChange(pagination.currentPage + 1)}
                  disabled={pagination.currentPage === pagination.totalPages}
                >
                  <ChevronRight className="w-4 h-4" />
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </PageLayout>
  );
}
