"use client";

import { useEffect, useState } from "react";
import { cn } from "@/lib/utils";

// Select2 + fnc_getCodeListAppend 대응 - 공통코드 셀렉트박스
interface CodeSelectProps {
  codeId: string;
  value?: string;
  onChange?: (value: string) => void;
  placeholder?: string;
  className?: string;
  disabled?: boolean;
  name?: string;
}

interface CodeOption {
  code_id?: string;
  code_name?: string;
  CODE_ID?: string;
  CODE_NAME?: string;
}

export function CodeSelect({
  codeId,
  value = "",
  onChange,
  placeholder = "선택",
  className,
  disabled,
  name,
}: CodeSelectProps) {
  const [options, setOptions] = useState<CodeOption[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!codeId) return;
    setLoading(true);
    fetch("/api/common/code-list", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ codeId }),
    })
      .then((res) => res.json())
      .then((data) => setOptions(data.data || []))
      .catch(() => setOptions([]))
      .finally(() => setLoading(false));
  }, [codeId]);

  return (
    <select
      name={name}
      value={value}
      onChange={(e) => onChange?.(e.target.value)}
      disabled={disabled || loading}
      className={cn(
        "flex h-9 rounded border border-gray-300 bg-white px-3 py-1 text-sm",
        "focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary/50",
        "disabled:cursor-not-allowed disabled:opacity-50",
        className
      )}
    >
      <option value="">{loading ? "로딩중..." : placeholder}</option>
      {options.map((opt) => {
        const id = opt.code_id || opt.CODE_ID || "";
        const nm = opt.code_name || opt.CODE_NAME || "";
        return (
          <option key={id} value={id}>
            {nm}
          </option>
        );
      })}
    </select>
  );
}
