"use client";

import React, { useState, useEffect } from "react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { getCategoryValues } from "@/lib/api/tableCategoryValue";
import { TableCategoryValue } from "@/types/tableCategoryValue";
import { Loader2 } from "lucide-react";
import { getAdaptiveLabelColor } from "@/lib/utils/darkModeColor";

interface CategorySelectComponentProps {
  component?: any;
  value?: string;
  onChange?: (value: string) => void;
  placeholder?: string;
  disabled?: boolean;
  required?: boolean;
  className?: string;
  readonly?: boolean;
  tableName?: string;
  columnName?: string;
  // 🔧 높이 조절을 위한 props 추가
  style?: React.CSSProperties & {
    labelDisplay?: boolean;
    labelFontSize?: string | number;
    labelColor?: string;
    labelFontWeight?: string | number;
    labelMarginBottom?: string | number;
  };
  size?: { width?: number | string; height?: number | string };
  // 🔧 라벨 표시를 위한 props 추가
  label?: string;
  id?: string;
  // 🔧 디자인 모드 처리
  isDesignMode?: boolean;
}

/**
 * 카테고리 셀렉트 컴포넌트
 * - 테이블의 카테고리 타입 컬럼에 연결된 카테고리 값들을 표시
 * - 실시간으로 카테고리 값 목록 조회
 */
export const CategorySelectComponent: React.FC<
  CategorySelectComponentProps
> = ({
  component,
  value = "",
  onChange,
  placeholder = "선택하세요",
  disabled = false,
  required = false,
  className = "",
  readonly = false,
  tableName: propTableName,
  columnName: propColumnName,
  style,
  size,
  label: propLabel,
  id: propId,
  isDesignMode = false,
}) => {
  // 🔧 높이 계산: size.height > style.height > 기본값(40px)
  const componentHeight = size?.height || style?.height;
  const heightStyle: React.CSSProperties = componentHeight 
    ? { height: componentHeight } 
    : {};

  // 🔧 라벨 관련 계산
  const label = propLabel || component?.label;
  const id = propId || component?.id;
  const showLabel = label && style?.labelDisplay !== false;
  
  // 라벨 높이 계산 (기본 20px)
  const labelFontSize = style?.labelFontSize ? parseInt(String(style.labelFontSize)) : 14;
  const labelMarginBottom = style?.labelMarginBottom ? parseInt(String(style.labelMarginBottom)) : 4;
  const estimatedLabelHeight = labelFontSize + labelMarginBottom + 2;
  const [categoryValues, setCategoryValues] = useState<TableCategoryValue[]>(
    []
  );
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 테이블명과 컬럼명 추출
  const tableName = propTableName || component?.tableName;
  const columnName = propColumnName || component?.columnName;

  useEffect(() => {
    if (!tableName || !columnName) {
      return;
    }

    loadCategoryValues();
  }, [tableName, columnName]);

  const loadCategoryValues = async () => {
    if (!tableName || !columnName) return;

    setIsLoading(true);
    setError(null);

    try {
      const response = await getCategoryValues(tableName, columnName);

      if (response.success && response.data) {
        // 활성화된 값만 필터링
        const activeValues = response.data.filter((v) => v.isActive !== false);
        setCategoryValues(activeValues);
      } else {
        setError("카테고리 값을 불러올 수 없습니다");
        console.error("❌ 카테고리 값 조회 실패:", response);
      }
    } catch (err: any) {
      setError("카테고리 값 조회 중 오류가 발생했습니다");
      console.error("❌ 카테고리 값 조회 예외:", err);
    } finally {
      setIsLoading(false);
    }
  };

  const handleValueChange = (newValue: string) => {
    onChange?.(newValue);
  };

  // 🔧 공통 라벨 렌더링 함수
  const renderLabel = () => {
    if (!showLabel) return null;
    return (
      <Label
        htmlFor={id}
        style={{
          position: "absolute",
          top: `-${estimatedLabelHeight}px`,
          left: 0,
          fontSize: style?.labelFontSize || "14px",
          color: getAdaptiveLabelColor(style?.labelColor),
          fontWeight: style?.labelFontWeight || "500",
        }}
        className="text-sm font-medium whitespace-nowrap"
      >
        {label}
        {required && <span className="text-amber-500 ml-0.5">*</span>}
      </Label>
    );
  };

  // 🔧 공통 wrapper 스타일
  const wrapperStyle: React.CSSProperties = {
    width: size?.width || style?.width,
    height: componentHeight,
  };

  // 🔧 디자인 모드일 때 클릭 방지
  const designModeClass = isDesignMode ? "pointer-events-none" : "";

  // 로딩 중
  if (isLoading) {
    return (
      <div id={id} className={`relative ${designModeClass}`} style={wrapperStyle}>
        {renderLabel()}
        <div 
          className="flex h-full w-full items-center justify-center rounded-md border bg-background px-3 text-sm text-muted-foreground"
          style={heightStyle}
        >
          <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          로딩 중...
        </div>
      </div>
    );
  }

  // 에러
  if (error) {
    return (
      <div id={id} className={`relative ${designModeClass}`} style={wrapperStyle}>
        {renderLabel()}
        <div 
          className="flex h-full w-full items-center rounded-md border border-destructive bg-destructive/10 px-3 text-sm text-destructive"
          style={heightStyle}
        >
          ⚠️ {error}
        </div>
      </div>
    );
  }

  // 카테고리 값이 없음
  if (categoryValues.length === 0) {
    return (
      <div id={id} className={`relative ${designModeClass}`} style={wrapperStyle}>
        {renderLabel()}
        <div 
          className="flex h-full w-full items-center rounded-md border bg-muted px-3 text-sm text-muted-foreground"
          style={heightStyle}
        >
          설정된 카테고리 값이 없습니다
        </div>
      </div>
    );
  }

  return (
    <div id={id} className={`relative ${designModeClass}`} style={wrapperStyle}>
      {renderLabel()}
      <div className="h-full w-full">
        <Select
          value={value}
          onValueChange={handleValueChange}
          disabled={disabled || readonly || isDesignMode}
          required={required}
        >
          <SelectTrigger className={`w-full h-full ${className}`} style={heightStyle}>
            <SelectValue placeholder={placeholder} />
          </SelectTrigger>
          <SelectContent>
            {categoryValues.map((categoryValue) => (
              <SelectItem
                key={categoryValue.valueId}
                value={categoryValue.valueCode}
              >
                {categoryValue.valueLabel}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
    </div>
  );
};

CategorySelectComponent.displayName = "CategorySelectComponent";

