"use client";

import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Search, Database, Columns, Plus } from "lucide-react";
import { ColumnInfo, WebType } from "@/types/screen";
import { tableTypeApi } from "@/lib/api/screen";
import { useAuth } from "@/hooks/useAuth";

interface TableTypeSelectorProps {
  selectedTable?: string;
  onTableChange?: (tableName: string) => void;
  onColumnWebTypeChange?: (columnInfo: ColumnInfo) => void;
  className?: string;
}

export default function TableTypeSelector({
  selectedTable: propSelectedTable,
  onTableChange,
  onColumnWebTypeChange,
  className,
}: TableTypeSelectorProps) {
  const { user } = useAuth();
  const [tables, setTables] = useState<
    Array<{ tableName: string; displayName: string; description: string; columnCount: string }>
  >([]);
  const [selectedTable, setSelectedTable] = useState<string>("");
  const [columns, setColumns] = useState<ColumnInfo[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [isLoading, setIsLoading] = useState(false);

  // 테이블 목록 조회
  useEffect(() => {
    const fetchTables = async () => {
      try {
        setIsLoading(true);
        const tableList = await tableTypeApi.getTables();
        setTables(tableList);
      } catch (error) {
        // console.error("테이블 목록 조회 실패:", error);
        // API 호출 실패 시 기본 테이블 목록 사용
        const fallbackTables = [
          { tableName: "user_info", displayName: "사용자 정보", description: "사용자 기본 정보", columnCount: "25" },
          { tableName: "product_info", displayName: "제품 정보", description: "제품 기본 정보", columnCount: "20" },
          { tableName: "order_info", displayName: "주문 정보", description: "주문 기본 정보", columnCount: "15" },
          { tableName: "company_info", displayName: "회사 정보", description: "회사 기본 정보", columnCount: "10" },
          { tableName: "menu_info", displayName: "메뉴 정보", description: "시스템 메뉴 정보", columnCount: "15" },
          { tableName: "auth_group", displayName: "권한 그룹", description: "사용자 권한 그룹", columnCount: "8" },
        ];
        setTables(fallbackTables);
      } finally {
        setIsLoading(false);
      }
    };

    fetchTables();
  }, []);

  // 컬럼 정보 조회
  useEffect(() => {
    if (!selectedTable) {
      setColumns([]);
      return;
    }

    const fetchColumns = async () => {
      try {
        setIsLoading(true);
        const columnList = await tableTypeApi.getColumns(selectedTable);

        // API 응답을 ColumnInfo 형식으로 변환
        const formattedColumns: ColumnInfo[] = columnList.map((col: any) => ({
          tableName: selectedTable,
          columnName: col.column_name || col.columnName,
          // 우선순위: displayName(라벨) > column_label > columnLabel > column_name > columnName
          columnLabel: col.displayName || col.column_label || col.columnLabel || col.column_name || col.columnName,
          dataType: col.data_type || col.dataType || col.dbType || "varchar",
          webType: col.web_type || col.webType || "text",
          isNullable: col.is_nullable || col.isNullable || "YES",
          characterMaximumLength: col.character_maximum_length || col.characterMaximumLength,
          isVisible: col.is_visible !== false,
          displayOrder: col.display_order || col.displayOrder || 1,
        }));

        setColumns(formattedColumns);
      } catch (error) {
        // console.error("컬럼 정보 조회 실패:", error);
        // API 호출 실패 시 기본 컬럼 정보 사용
        const fallbackColumns: ColumnInfo[] = [
          {
            tableName: selectedTable,
            columnName: "id",
            columnLabel: "ID",
            dataType: "integer",
            webType: "number",
            isNullable: "NO",
            isVisible: true,
            displayOrder: 1,
          },
          {
            tableName: selectedTable,
            columnName: "name",
            columnLabel: "이름",
            dataType: "varchar",
            webType: "text",
            isNullable: "NO",
            characterMaximumLength: 100,
            isVisible: true,
            displayOrder: 2,
          },
          {
            tableName: selectedTable,
            columnName: "status",
            columnLabel: "상태",
            dataType: "varchar",
            webType: "select",
            isNullable: "YES",
            characterMaximumLength: 20,
            isVisible: true,
            displayOrder: 3,
          },
          {
            tableName: selectedTable,
            columnName: "created_date",
            columnLabel: "생성일",
            dataType: "timestamp",
            webType: "date",
            isNullable: "YES",
            isVisible: true,
            displayOrder: 4,
          },
        ];
        setColumns(fallbackColumns);
      } finally {
        setIsLoading(false);
      }
    };

    fetchColumns();
  }, [selectedTable]);

  // 테이블 선택
  const handleTableSelect = (tableName: string) => {
    setSelectedTable(tableName);
    if (onTableChange) {
      onTableChange(tableName);
    }
  };

  // 컬럼 선택
  const handleColumnSelect = (column: ColumnInfo) => {
    if (onColumnWebTypeChange) {
      onColumnWebTypeChange(column);
    }
  };

  // 웹 타입 변경
  const handleWebTypeChange = async (columnName: string, webType: WebType) => {
    try {
      await tableTypeApi.setColumnWebType(selectedTable, columnName, webType);

      // 로컬 상태 업데이트
      setColumns((prev) => prev.map((col) => (col.columnName === columnName ? { ...col, webType } : col)));

      // console.log(`컬럼 ${columnName}의 웹 타입을 ${webType}로 변경했습니다.`);
    } catch (error) {
      // console.error("웹 타입 설정 실패:", error);
      alert("웹 타입 설정에 실패했습니다. 다시 시도해주세요.");
    }
  };

  // 입력 타입 변경 (로컬 상태만 - DB에 저장하지 않음)
  const handleInputTypeChange = (columnName: string, inputType: "direct" | "auto") => {
    // 로컬 상태만 업데이트 (DB에는 저장하지 않음 - inputType은 화면 렌더링용)
    setColumns((prev) => prev.map((col) => (col.columnName === columnName ? { ...col, inputType } : col)));
  };

  const filteredTables = tables.filter((table) => table.displayName.toLowerCase().includes(searchTerm.toLowerCase()));

  return (
    <div className={`space-y-4 ${className}`}>
      {/* 테이블 선택 */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="flex items-center gap-2 text-sm font-medium">
            <Database className="h-4 w-4" />
            테이블 선택
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          <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"
            />
          </div>

          <div className="grid max-h-40 grid-cols-2 gap-2 overflow-y-auto">
            {filteredTables.map((table) => (
              <Button
                key={table.tableName}
                variant={selectedTable === table.tableName ? "default" : "outline"}
                size="sm"
                onClick={() => handleTableSelect(table.tableName)}
                className="justify-start text-left"
              >
                <Database className="mr-2 h-3 w-3" />
                <div className="flex flex-col items-start">
                  <span className="font-medium">{table.displayName}</span>
                  <span className="text-xs text-muted-foreground">{table.columnCount}개 컬럼</span>
                </div>
              </Button>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* 컬럼 정보 */}
      {selectedTable && (
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="flex items-center gap-2 text-sm font-medium">
              <Columns className="h-4 w-4" />
              {selectedTable} - 컬럼 정보
            </CardTitle>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>컬럼명</TableHead>
                  <TableHead>라벨</TableHead>
                  <TableHead>데이터 타입</TableHead>
                  <TableHead>웹 타입</TableHead>
                  <TableHead>입력 타입</TableHead>
                  <TableHead>필수</TableHead>
                  <TableHead>표시</TableHead>
                  <TableHead>액션</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {columns.map((column) => (
                  <TableRow key={column.columnName}>
                    <TableCell className="font-mono text-sm">{column.columnName}</TableCell>
                    <TableCell>{column.columnLabel}</TableCell>
                    <TableCell>
                      <Badge variant="outline" className="text-xs">
                        {column.dataType}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Select
                        value={column.webType || "text"}
                        onValueChange={(value) => handleWebTypeChange(column.columnName, value as WebType)}
                      >
                        <SelectTrigger className="w-32">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="text">텍스트</SelectItem>
                          <SelectItem value="number">숫자</SelectItem>
                          <SelectItem value="date">날짜</SelectItem>
                          <SelectItem value="select">선택</SelectItem>
                          <SelectItem value="textarea">텍스트영역</SelectItem>
                          <SelectItem value="checkbox">체크박스</SelectItem>
                          <SelectItem value="radio">라디오</SelectItem>
                        </SelectContent>
                      </Select>
                    </TableCell>
                    <TableCell>
                      <Select
                        value={column.inputType || "direct"}
                        onValueChange={(value) => handleInputTypeChange(column.columnName, value as "direct" | "auto")}
                      >
                        <SelectTrigger className="w-24">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="direct">직접입력</SelectItem>
                          <SelectItem value="auto">자동입력</SelectItem>
                        </SelectContent>
                      </Select>
                    </TableCell>
                    <TableCell>
                      <Badge variant={column.isNullable === "NO" ? "default" : "secondary"}>
                        {column.isNullable === "NO" ? "필수" : "선택"}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant={column.isVisible ? "default" : "secondary"}>
                        {column.isVisible ? "표시" : "숨김"}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Button size="sm" variant="outline" onClick={() => handleColumnSelect(column)}>
                        <Plus className="mr-1 h-3 w-3" />
                        위젯 생성
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
