"use client";

import React, { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Search, Database } from "lucide-react";
import { DataFlowAPI, TableDefinition, TableInfo } from "@/lib/api/dataflow";

interface TableSelectorProps {
  companyCode: string;
  onTableAdd: (table: TableDefinition) => void;
  selectedTables?: string[]; // 이미 추가된 테이블들의 이름
}

export const TableSelector: React.FC<TableSelectorProps> = ({ companyCode, onTableAdd, selectedTables = [] }) => {
  const [tables, setTables] = useState<TableInfo[]>([]);
  const [filteredTables, setFilteredTables] = useState<TableInfo[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 테이블 목록 로드
  useEffect(() => {
    loadTables();
  }, []);

  // 검색 필터링
  useEffect(() => {
    if (searchTerm.trim() === "") {
      setFilteredTables(tables);
    } else {
      const filtered = tables.filter(
        (table) =>
          table.tableName.toLowerCase().includes(searchTerm.toLowerCase()) ||
          table.displayName.toLowerCase().includes(searchTerm.toLowerCase()) ||
          (table.description && table.description.toLowerCase().includes(searchTerm.toLowerCase())),
      );
      setFilteredTables(filtered);
    }
  }, [tables, searchTerm]);

  const loadTables = async () => {
    try {
      setLoading(true);
      setError(null);
      const tableList = await DataFlowAPI.getTables();
      setTables(tableList);
    } catch (error) {
      console.error("테이블 목록 로드 실패:", error);
      setError("테이블 목록을 불러오는데 실패했습니다.");
    } finally {
      setLoading(false);
    }
  };

  const handleAddTable = async (tableInfo: TableInfo) => {
    try {
      // 테이블 상세 정보 (컬럼 포함) 조회
      const tableWithColumns = await DataFlowAPI.getTableWithColumns(tableInfo.tableName);
      if (tableWithColumns) {
        onTableAdd(tableWithColumns);
      }
    } catch (error) {
      console.error("테이블 추가 실패:", error);
      setError("테이블을 추가하는데 실패했습니다.");
    }
  };

  const isTableSelected = (tableName: string) => {
    return selectedTables.includes(tableName);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold text-foreground">테이블 선택</h3>
        <Button onClick={loadTables} variant="outline" size="sm" disabled={loading}>
          {loading ? "로딩중..." : "새로고침"}
        </Button>
      </div>

      {/* 검색 입력 */}
      <div className="relative">
        <Search className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-muted-foreground/70" />
        <Input
          placeholder="테이블명으로 검색..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="pl-10"
          disabled={loading}
        />
      </div>

      {/* 오류 메시지 */}
      {error && <div className="rounded-lg bg-destructive/10 p-4 text-sm text-destructive">{error}</div>}

      {/* 테이블 목록 */}
      <div className="max-h-96 space-y-2 overflow-y-auto">
        {loading ? (
          <div className="flex items-center justify-center py-8">
            <div className="text-sm text-muted-foreground">테이블 목록을 불러오는 중...</div>
          </div>
        ) : filteredTables.length === 0 ? (
          <div className="flex items-center justify-center py-8">
            <div className="text-center text-sm text-muted-foreground">
              {searchTerm ? "검색 결과가 없습니다." : "등록된 테이블이 없습니다."}
            </div>
          </div>
        ) : (
          filteredTables.map((table) => {
            const isSelected = isTableSelected(table.tableName);
            return (
              <Card
                key={table.tableName}
                className={`cursor-pointer transition-all hover:shadow-md ${
                  isSelected ? "cursor-not-allowed border-primary bg-accent opacity-60" : "hover:border-input"
                }`}
                onDoubleClick={() => !isSelected && handleAddTable(table)}
              >
                <CardHeader className="pb-2">
                  <div>
                    <CardTitle className="text-sm font-medium">{table.displayName}</CardTitle>
                    <div className="mt-1 text-xs text-muted-foreground">{table.columnCount}개 컬럼</div>
                  </div>
                </CardHeader>
                <CardContent className="pt-0">
                  <div className="space-y-2">
                    <div className="flex items-center gap-2 text-xs text-muted-foreground">
                      <Database className="h-3 w-3" />
                      <span className="font-mono">{table.tableName}</span>
                      {isSelected && <span className="font-medium text-primary">(추가됨)</span>}
                    </div>

                    {table.description && <p className="line-clamp-2 text-xs text-muted-foreground">{table.description}</p>}
                  </div>
                </CardContent>
              </Card>
            );
          })
        )}
      </div>

      {/* 통계 정보 */}
      <div className="rounded-lg bg-muted p-3 text-xs text-muted-foreground">
        <div className="flex items-center justify-between">
          <span>전체 테이블: {tables.length}개</span>
          {searchTerm && <span>검색 결과: {filteredTables.length}개</span>}
        </div>
        {selectedTables.length > 0 && <div className="mt-1">캔버스에 추가된 테이블: {selectedTables.length}개</div>}
      </div>
    </div>
  );
};
