"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) => ({
          table_name: selectedTable,
          column_name: col.column_name,
          // 우선순위: display_name(라벨) > column_label > column_name
          display_name: col.display_name || col.column_label || col.column_name,
          data_type: col.data_type || "varchar",
          db_type: col.db_type || "",
          web_type: col.web_type || "text",
          is_nullable: col.is_nullable !== "NO" && col.is_nullable !== false,
          is_primary_key: col.is_primary_key || false,
          max_length: col.character_maximum_length,
          is_visible: col.is_visible !== false,
          display_order: col.display_order || 1,
        }));

        setColumns(formattedColumns);
      } catch (error) {
        // console.error("컬럼 정보 조회 실패:", error);
        // API 호출 실패 시 기본 컬럼 정보 사용
        const fallbackColumns: ColumnInfo[] = [
          {
            table_name: selectedTable,
            column_name: "id",
            display_name: "ID",
            data_type: "integer",
            db_type: "integer",
            web_type: "number",
            is_nullable: false,
            is_primary_key: true,
            is_visible: true,
            display_order: 1,
          },
          {
            table_name: selectedTable,
            column_name: "name",
            display_name: "이름",
            data_type: "varchar",
            db_type: "varchar",
            web_type: "text",
            is_nullable: false,
            is_primary_key: false,
            max_length: 100,
            is_visible: true,
            display_order: 2,
          },
          {
            table_name: selectedTable,
            column_name: "status",
            display_name: "상태",
            data_type: "varchar",
            db_type: "varchar",
            web_type: "select",
            is_nullable: true,
            is_primary_key: false,
            max_length: 20,
            is_visible: true,
            display_order: 3,
          },
          {
            table_name: selectedTable,
            column_name: "created_date",
            display_name: "생성일",
            data_type: "timestamp",
            db_type: "timestamp",
            web_type: "date",
            is_nullable: true,
            is_primary_key: false,
            is_visible: true,
            display_order: 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.column_name === columnName ? { ...col, web_type: 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.column_name === columnName ? { ...col, input_type: 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.column_name}>
                    <TableCell className="font-mono text-sm">{column.column_name}</TableCell>
                    <TableCell>{column.display_name}</TableCell>
                    <TableCell>
                      <Badge variant="outline" className="text-xs">
                        {column.data_type}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Select
                        value={column.web_type || "text"}
                        onValueChange={(value) => handleWebTypeChange(column.column_name, 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.input_type || "direct"}
                        onValueChange={(value) => handleInputTypeChange(column.column_name, 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.is_nullable ? "default" : "secondary"}>
                        {!column.is_nullable ? "필수" : "선택"}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant={column.is_visible ? "default" : "secondary"}>
                        {column.is_visible ? "표시" : "숨김"}
                      </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>
  );
}
