"use client";

import React, { useState, useEffect } from "react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { TextInputConfig } from "./types";
import { AutoGenerationType, AutoGenerationConfig } from "@/types/screen";
import { AutoGenerationUtils } from "@/lib/utils/autoGeneration";
import { getAvailableNumberingRules, getAvailableNumberingRulesForScreen } from "@/lib/api/numberingRule";
import { NumberingRuleConfig } from "@/types/numbering-rule";

export interface TextInputConfigPanelProps {
  config: TextInputConfig;
  onChange: (config: Partial<TextInputConfig>) => void;
  screenTableName?: string; // 🆕 현재 화면의 테이블명
  menuObjid?: number; // 🆕 메뉴 OBJID (사용자 선택)
}

/**
 * TextInput 설정 패널
 * 컴포넌트의 설정값들을 편집할 수 있는 UI 제공
 */
export const TextInputConfigPanel: React.FC<TextInputConfigPanelProps> = ({ config, onChange, screenTableName, menuObjid }) => {
  // 채번 규칙 목록 상태
  const [numberingRules, setNumberingRules] = useState<NumberingRuleConfig[]>([]);
  const [loadingRules, setLoadingRules] = useState(false);
  
  // 부모 메뉴 목록 상태 (채번규칙 사용을 위한 선택)
  const [parentMenus, setParentMenus] = useState<any[]>([]);
  
  // useState 초기값에서 저장된 값 복원 (우선순위: 저장된 값 > menuObjid prop)
  const [selectedMenuObjid, setSelectedMenuObjid] = useState<number | undefined>(() => {
    return config.autoGeneration?.selectedMenuObjid || menuObjid;
  });
  
  const [loadingMenus, setLoadingMenus] = useState(false);

  // 부모 메뉴 목록 로드 (사용자 메뉴의 레벨 2만)
  useEffect(() => {
    const loadMenus = async () => {
      setLoadingMenus(true);
      try {
        const { apiClient } = await import("@/lib/api/client");
        const response = await apiClient.get("/admin/menus");
        
        if (response.data.success && response.data.data) {
          const allMenus = response.data.data;
          
          // 사용자 메뉴(menu_type='1')의 레벨 2만 필터링
          const level2UserMenus = allMenus.filter((menu: any) => 
            menu.menu_type === '1' && menu.lev === 2
          );
          
          setParentMenus(level2UserMenus);
        }
      } catch (error) {
        console.error("부모 메뉴 로드 실패:", error);
      } finally {
        setLoadingMenus(false);
      }
    };
    loadMenus();
  }, []);

  // 채번 규칙 목록 로드 (선택된 메뉴 기준)
  useEffect(() => {
    const loadRules = async () => {
      // autoGeneration.type이 numbering_rule이 아니면 로드하지 않음
      if (config.autoGeneration?.type !== "numbering_rule") {
        return;
      }

      // 메뉴가 선택되지 않았으면 로드하지 않음
      if (!selectedMenuObjid) {
        setNumberingRules([]);
        return;
      }
      
      setLoadingRules(true);
      try {
        const response = await getAvailableNumberingRules(selectedMenuObjid);
        
        if (response.success && response.data) {
          setNumberingRules(response.data);
        }
      } catch (error) {
        console.error("채번 규칙 목록 로드 실패:", error);
        setNumberingRules([]);
      } finally {
        setLoadingRules(false);
      }
    };

    loadRules();
  }, [selectedMenuObjid, config.autoGeneration?.type]);

  const handleChange = (key: keyof TextInputConfig, value: any) => {
    onChange({ [key]: value });
  };

  return (
    <div className="space-y-4">
      <div className="text-sm font-medium">text-input 설정</div>

      {/* 텍스트 관련 설정 */}
      <div className="space-y-2">
        <Label htmlFor="placeholder">플레이스홀더</Label>
        <Input
          id="placeholder"
          value={config.placeholder || ""}
          onChange={(e) => handleChange("placeholder", e.target.value)}
        />
      </div>

      <div className="space-y-2">
        <Label htmlFor="maxLength">최대 길이</Label>
        <Input
          id="maxLength"
          type="number"
          value={config.maxLength || ""}
          onChange={(e) => handleChange("maxLength", parseInt(e.target.value) || undefined)}
        />
      </div>

      {/* 구분선 */}
      <div className="border-t pt-4">
        <div className="mb-3 text-sm font-medium">고급 기능</div>

        {/* 숨김 기능 */}
        <div className="space-y-2">
          <Label htmlFor="hidden">숨김</Label>
          <Checkbox
            id="hidden"
            checked={config.hidden || false}
            onCheckedChange={(checked) => handleChange("hidden", checked)}
          />
        </div>

        {/* 자동생성 기능 */}
        <div className="space-y-2">
          <Label htmlFor="autoGeneration">자동생성 활성화</Label>
          <Checkbox
            id="autoGeneration"
            checked={config.autoGeneration?.enabled || false}
            onCheckedChange={(checked) => {
              const currentConfig = config.autoGeneration || { type: "none", enabled: false };
              handleChange("autoGeneration", {
                ...currentConfig,
                enabled: checked as boolean,
              });
            }}
          />
        </div>

        {/* 자동생성 타입 선택 */}
        {config.autoGeneration?.enabled && (
          <div className="space-y-2">
            <Label htmlFor="autoGenerationType">자동생성 타입</Label>
            <Select
              value={config.autoGeneration?.type || "none"}
              onValueChange={(value: AutoGenerationType) => {
                const currentConfig = config.autoGeneration || { type: "none", enabled: false };
                handleChange("autoGeneration", {
                  ...currentConfig,
                  type: value,
                });
              }}
            >
              <SelectTrigger>
                <SelectValue placeholder="자동생성 타입 선택" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="none">자동생성 없음</SelectItem>
                <SelectItem value="uuid">UUID 생성</SelectItem>
                <SelectItem value="current_user">현재 사용자 ID</SelectItem>
                <SelectItem value="current_time">현재 시간</SelectItem>
                <SelectItem value="sequence">순차 번호</SelectItem>
                <SelectItem value="numbering_rule">채번 규칙</SelectItem>
                <SelectItem value="random_string">랜덤 문자열</SelectItem>
                <SelectItem value="random_number">랜덤 숫자</SelectItem>
                <SelectItem value="company_code">회사 코드</SelectItem>
                <SelectItem value="department">부서 코드</SelectItem>
              </SelectContent>
            </Select>

            {/* 선택된 타입 설명 */}
            {config.autoGeneration?.type && config.autoGeneration.type !== "none" && (
              <div className="text-xs text-gray-500">
                {AutoGenerationUtils.getTypeDescription(config.autoGeneration.type)}
              </div>
            )}

            {/* 채번 규칙 선택 */}
            {config.autoGeneration?.type === "numbering_rule" && (
              <>
                {/* 부모 메뉴 선택 */}
                <div className="space-y-2">
                  <Label htmlFor="targetMenu">
                    대상 메뉴 선택 <span className="text-destructive">*</span>
                  </Label>
                  <Select
                    value={selectedMenuObjid?.toString() || ""}
                    onValueChange={(value) => {
                      const menuObjid = parseInt(value);
                      setSelectedMenuObjid(menuObjid);
                      
                      // 컴포넌트 설정에 저장하여 언마운트 시에도 유지
                      handleChange("autoGeneration", {
                        ...config.autoGeneration,
                        selectedMenuObjid: menuObjid,
                      });
                    }}
                    disabled={loadingMenus}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder={loadingMenus ? "메뉴 로딩 중..." : "채번규칙을 사용할 메뉴 선택"} />
                    </SelectTrigger>
                    <SelectContent>
                      {parentMenus.length === 0 ? (
                        <SelectItem value="no-menus" disabled>
                          사용 가능한 메뉴가 없습니다
                        </SelectItem>
                      ) : (
                        parentMenus.map((menu) => (
                          <SelectItem key={menu.objid} value={menu.objid.toString()}>
                            {menu.menu_name_kor}
                            {menu.menu_name_eng && (
                              <span className="text-muted-foreground ml-2 text-xs">
                                ({menu.menu_name_eng})
                              </span>
                            )}
                          </SelectItem>
                        ))
                      )}
                    </SelectContent>
                  </Select>
                  <p className="text-muted-foreground text-xs">
                    이 입력 필드가 어느 메뉴에 속할지 선택하세요 (해당 메뉴의 채번규칙이 적용됩니다)
                  </p>
                </div>

                {/* 채번 규칙 선택 (메뉴 선택 후) */}
                {selectedMenuObjid ? (
                  <div className="space-y-2">
                    <Label htmlFor="numberingRuleId">
                      채번 규칙 선택 <span className="text-destructive">*</span>
                    </Label>
                    <Select
                      value={config.autoGeneration?.options?.numberingRuleId || ""}
                      onValueChange={(value) => {
                        const currentConfig = config.autoGeneration!;
                        handleChange("autoGeneration", {
                          ...currentConfig,
                          options: {
                            ...currentConfig.options,
                            numberingRuleId: value,
                          },
                        });
                      }}
                      disabled={loadingRules}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder={loadingRules ? "규칙 로딩 중..." : "채번 규칙 선택"} />
                      </SelectTrigger>
                      <SelectContent>
                        {numberingRules.length === 0 ? (
                          <SelectItem value="no-rules" disabled>
                            선택된 메뉴에 사용 가능한 규칙이 없습니다
                          </SelectItem>
                        ) : (
                          numberingRules.map((rule) => (
                            <SelectItem key={rule.ruleId} value={rule.ruleId}>
                              {rule.ruleName}
                              {rule.description && (
                                <span className="text-muted-foreground ml-2 text-xs">
                                  - {rule.description}
                                </span>
                              )}
                            </SelectItem>
                          ))
                        )}
                      </SelectContent>
                    </Select>
                    <p className="text-muted-foreground text-xs">
                      선택된 메뉴 및 형제 메뉴에서 사용 가능한 채번 규칙만 표시됩니다
                    </p>
                  </div>
                ) : (
                  <div className="rounded-md border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800">
                    먼저 대상 메뉴를 선택하세요
                  </div>
                )}
              </>
            )}
          </div>
        )}

        {/* 자동생성 옵션 */}
        {config.autoGeneration?.enabled &&
          config.autoGeneration?.type &&
          ["random_string", "random_number", "sequence"].includes(config.autoGeneration.type) && (
            <div className="space-y-2">
              <Label>자동생성 옵션</Label>

              {/* 길이 설정 (랜덤 문자열/숫자용) */}
              {["random_string", "random_number"].includes(config.autoGeneration.type) && (
                <div className="space-y-1">
                  <Label htmlFor="autoGenLength" className="text-xs">
                    길이
                  </Label>
                  <Input
                    id="autoGenLength"
                    type="number"
                    min="1"
                    max="50"
                    value={
                      config.autoGeneration?.options?.length || (config.autoGeneration.type === "random_string" ? 8 : 6)
                    }
                    onChange={(e) => {
                      const currentConfig = config.autoGeneration!;
                      handleChange("autoGeneration", {
                        ...currentConfig,
                        options: {
                          ...currentConfig.options,
                          length: parseInt(e.target.value) || 8,
                        },
                      });
                    }}
                  />
                </div>
              )}

              {/* 접두사 */}
              <div className="space-y-1">
                <Label htmlFor="autoGenPrefix" className="text-xs">
                  접두사
                </Label>
                <Input
                  id="autoGenPrefix"
                  value={config.autoGeneration?.options?.prefix || ""}
                  onChange={(e) => {
                    const currentConfig = config.autoGeneration!;
                    handleChange("autoGeneration", {
                      ...currentConfig,
                      options: {
                        ...currentConfig.options,
                        prefix: e.target.value,
                      },
                    });
                  }}
                />
              </div>

              {/* 접미사 */}
              <div className="space-y-1">
                <Label htmlFor="autoGenSuffix" className="text-xs">
                  접미사
                </Label>
                <Input
                  id="autoGenSuffix"
                  value={config.autoGeneration?.options?.suffix || ""}
                  onChange={(e) => {
                    const currentConfig = config.autoGeneration!;
                    handleChange("autoGeneration", {
                      ...currentConfig,
                      options: {
                        ...currentConfig.options,
                        suffix: e.target.value,
                      },
                    });
                  }}
                />
              </div>

              {/* 미리보기 */}
              <div className="space-y-1">
                <Label className="text-xs">미리보기</Label>
                <div className="rounded border bg-gray-100 p-2 text-xs">
                  {AutoGenerationUtils.generatePreviewValue(config.autoGeneration)}
                </div>
              </div>
            </div>
          )}
      </div>
    </div>
  );
};
