"use client";

import React, { useState, useEffect, useCallback } from "react";
import { Check, ChevronsUpDown, Search } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import { cn } from "@/lib/utils";
import { apiClient } from "@/lib/api/client";

export interface ColumnInfo {
  column_name: string;
  data_type: string;
  column_comment?: string;
}

interface SearchableColumnSelectProps {
  tableName: string;
  value: string;
  onValueChange: (value: string) => void;
  placeholder?: string;
  disabled?: boolean;
  excludeColumns?: string[]; // 이미 선택된 컬럼 제외
  className?: string;
}

export const SearchableColumnSelect: React.FC<SearchableColumnSelectProps> = ({
  tableName,
  value,
  onValueChange,
  placeholder = "컬럼 선택",
  disabled = false,
  excludeColumns = [],
  className,
}) => {
  const [open, setOpen] = useState(false);
  const [columns, setColumns] = useState<ColumnInfo[]>([]);
  const [loading, setLoading] = useState(false);

  // 컬럼 목록 로드
  const loadColumns = useCallback(async () => {
    if (!tableName) {
      setColumns([]);
      return;
    }

    setLoading(true);
    try {
      const response = await apiClient.get(`/table-management/tables/${tableName}/columns?size=200`);

      let columnList: any[] = [];
      if (response.data?.success && response.data?.data?.columns) {
        columnList = response.data.data.columns;
      } else if (Array.isArray(response.data?.data?.columns)) {
        columnList = response.data.data.columns;
      } else if (Array.isArray(response.data?.data)) {
        columnList = response.data.data;
      } else if (Array.isArray(response.data)) {
        columnList = response.data;
      }

      const transformedColumns = columnList.map((c: any) => ({
        column_name: c.columnName ?? c.column_name ?? c.name ?? "",
        data_type: c.dataType ?? c.data_type ?? c.type ?? "",
        column_comment: c.displayName ?? c.column_comment ?? c.label ?? "",
      }));

      setColumns(transformedColumns);
    } catch (error) {
      console.error("컬럼 목록 로드 실패:", error);
      setColumns([]);
    } finally {
      setLoading(false);
    }
  }, [tableName]);

  useEffect(() => {
    loadColumns();
  }, [loadColumns]);

  // 선택된 컬럼 정보 가져오기
  const selectedColumn = columns.find((col) => col.column_name === value);
  const displayValue = selectedColumn
    ? selectedColumn.column_comment || selectedColumn.column_name
    : value || "";

  // 필터링된 컬럼 목록 (이미 선택된 컬럼 제외)
  const filteredColumns = columns.filter(
    (col) => !excludeColumns.includes(col.column_name) || col.column_name === value
  );

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          aria-expanded={open}
          disabled={disabled || loading || !tableName}
          className={cn("w-full justify-between h-9 text-sm", className)}
        >
          {loading ? (
            "로딩 중..."
          ) : !tableName ? (
            "테이블을 먼저 선택하세요"
          ) : (
            <span className="truncate">
              {displayValue || placeholder}
            </span>
          )}
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-full p-0" align="start" style={{ width: "var(--radix-popover-trigger-width)" }}>
        <Command>
          <CommandInput placeholder="컬럼명 또는 라벨 검색..." className="h-9" />
          <CommandList>
            <CommandEmpty>
              {filteredColumns.length === 0 ? "선택 가능한 컬럼이 없습니다" : "검색 결과가 없습니다"}
            </CommandEmpty>
            <CommandGroup>
              {filteredColumns.map((col) => (
                <CommandItem
                  key={col.column_name}
                  value={`${col.column_name} ${col.column_comment || ""}`}
                  onSelect={() => {
                    onValueChange(col.column_name);
                    setOpen(false);
                  }}
                >
                  <Check
                    className={cn(
                      "mr-2 h-4 w-4 shrink-0",
                      value === col.column_name ? "opacity-100" : "opacity-0"
                    )}
                  />
                  <div className="flex flex-col min-w-0">
                    <span className="truncate font-medium">
                      {col.column_comment || col.column_name}
                    </span>
                    <span className="text-xs text-muted-foreground truncate">
                      {col.column_name} ({col.data_type})
                    </span>
                  </div>
                </CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
};

export default SearchableColumnSelect;


