"use client";

import React, { useState, useEffect } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { NumberTypeConfig } from "@/types/screen";

interface NumberTypeConfigPanelProps {
  config: NumberTypeConfig;
  onConfigChange: (config: NumberTypeConfig) => void;
}

export const NumberTypeConfigPanel: React.FC<NumberTypeConfigPanelProps> = ({ config, onConfigChange }) => {
  // 기본값이 설정된 config 사용
  const safeConfig = {
    format: "integer" as const,
    min: undefined,
    max: undefined,
    step: undefined,
    decimalPlaces: undefined,
    thousandSeparator: false,
    prefix: "",
    suffix: "",
    placeholder: "",
    ...config,
  };

  // 로컬 상태로 실시간 입력 관리
  const [localValues, setLocalValues] = useState({
    format: safeConfig.format,
    min: safeConfig.min?.toString() || "",
    max: safeConfig.max?.toString() || "",
    step: safeConfig.step?.toString() || "",
    decimalPlaces: safeConfig.decimalPlaces?.toString() || "",
    thousandSeparator: safeConfig.thousandSeparator,
    prefix: safeConfig.prefix,
    suffix: safeConfig.suffix,
    placeholder: safeConfig.placeholder,
  });

  // config가 변경될 때 로컬 상태 동기화
  useEffect(() => {
    setLocalValues({
      format: safeConfig.format,
      min: safeConfig.min?.toString() || "",
      max: safeConfig.max?.toString() || "",
      step: safeConfig.step?.toString() || "",
      decimalPlaces: safeConfig.decimalPlaces?.toString() || "",
      thousandSeparator: safeConfig.thousandSeparator,
      prefix: safeConfig.prefix,
      suffix: safeConfig.suffix,
      placeholder: safeConfig.placeholder,
    });
  }, [
    safeConfig.format,
    safeConfig.min,
    safeConfig.max,
    safeConfig.step,
    safeConfig.decimalPlaces,
    safeConfig.thousandSeparator,
    safeConfig.prefix,
    safeConfig.suffix,
    safeConfig.placeholder,
  ]);

  const updateConfig = (key: keyof NumberTypeConfig, value: any) => {
    // 로컬 상태 즉시 업데이트
    if (key === "min" || key === "max" || key === "step" || key === "decimalPlaces") {
      setLocalValues((prev) => ({ ...prev, [key]: value?.toString() || "" }));
    } else {
      setLocalValues((prev) => ({ ...prev, [key]: value }));
    }

    // 실제 config 업데이트 - 현재 로컬 상태를 기반으로 새 객체 생성 (safeConfig 기본값 덮어쓰기 방지)
    const currentValues = {
      format: key === "format" ? value : localValues.format,
      min: key === "min" ? value : localValues.min ? Number(localValues.min) : undefined,
      max: key === "max" ? value : localValues.max ? Number(localValues.max) : undefined,
      step: key === "step" ? value : localValues.step ? Number(localValues.step) : undefined,
      decimalPlaces:
        key === "decimalPlaces" ? value : localValues.decimalPlaces ? Number(localValues.decimalPlaces) : undefined,
      thousandSeparator: key === "thousandSeparator" ? value : localValues.thousandSeparator,
      prefix: key === "prefix" ? value : localValues.prefix,
      suffix: key === "suffix" ? value : localValues.suffix,
      placeholder: key === "placeholder" ? value : localValues.placeholder,
    };

    const newConfig = JSON.parse(JSON.stringify(currentValues));
    // console.log("🔢 NumberTypeConfig 업데이트:", {
    // key,
    // value,
    // oldConfig: safeConfig,
    // newConfig,
    // localValues,
    // timestamp: new Date().toISOString(),
    // });

    // 약간의 지연을 두고 업데이트 (배치 업데이트 방지)
    setTimeout(() => {
      onConfigChange(newConfig);
    }, 0);
  };

  return (
    <div className="space-y-4">
      {/* 숫자 형식 */}
      <div>
        <Label htmlFor="format" className="text-sm font-medium">
          숫자 형식
        </Label>
        <Select value={localValues.format} onValueChange={(value) => updateConfig("format", value)}>
          <SelectTrigger className="mt-1 h-6 w-full px-2 py-0 text-xs">
            <SelectValue placeholder="숫자 형식 선택" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="integer">정수</SelectItem>
            <SelectItem value="decimal">소수</SelectItem>
            <SelectItem value="currency">통화</SelectItem>
            <SelectItem value="percentage">퍼센트</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* 범위 설정 */}
      <div className="grid grid-cols-2 gap-3">
        <div>
          <Label htmlFor="min" className="text-sm font-medium">
            최소값
          </Label>
          <Input
            id="min"
            type="number"
            step="1"
            value={localValues.min}
            onChange={(e) => updateConfig("min", e.target.value ? Number(e.target.value) : undefined)}
            className="mt-1"
            placeholder="최소값"
          />
        </div>

        <div>
          <Label htmlFor="max" className="text-sm font-medium">
            최대값
          </Label>
          <Input
            id="max"
            type="number"
            step="1"
            value={localValues.max}
            onChange={(e) => updateConfig("max", e.target.value ? Number(e.target.value) : undefined)}
            className="mt-1"
            placeholder="최대값"
          />
        </div>
      </div>

      {/* 단계값 */}
      <div>
        <Label htmlFor="step" className="text-sm font-medium">
          단계값 (증감 단위)
        </Label>
        <Input
          id="step"
          type="number"
          step="0.01"
          value={localValues.step}
          onChange={(e) => updateConfig("step", e.target.value ? Number(e.target.value) : undefined)}
          className="mt-1"
          placeholder="1"
        />
      </div>

      {/* 소수점 자릿수 (decimal 형식인 경우) */}
      {localValues.format === "decimal" && (
        <div>
          <Label htmlFor="decimalPlaces" className="text-sm font-medium">
            소수점 자릿수
          </Label>
          <Input
            id="decimalPlaces"
            type="number"
            min="0"
            max="10"
            step="1"
            value={localValues.decimalPlaces}
            onChange={(e) => updateConfig("decimalPlaces", e.target.value ? Number(e.target.value) : undefined)}
            className="mt-1"
            placeholder="2"
          />
        </div>
      )}

      {/* 천 단위 구분자 */}
      <div className="flex items-center justify-between">
        <Label htmlFor="thousandSeparator" className="text-sm font-medium">
          천 단위 구분자 사용
        </Label>
        <Checkbox
          id="thousandSeparator"
          checked={localValues.thousandSeparator}
          onCheckedChange={(checked) => updateConfig("thousandSeparator", !!checked)}
        />
      </div>

      {/* 접두사/접미사 */}
      <div className="grid grid-cols-2 gap-3">
        <div>
          <Label htmlFor="prefix" className="text-sm font-medium">
            접두사
          </Label>
          <Input
            id="prefix"
            value={localValues.prefix}
            onChange={(e) => updateConfig("prefix", e.target.value)}
            className="mt-1"
            placeholder="$, ₩ 등"
          />
        </div>

        <div>
          <Label htmlFor="suffix" className="text-sm font-medium">
            접미사
          </Label>
          <Input
            id="suffix"
            value={localValues.suffix}
            onChange={(e) => updateConfig("suffix", e.target.value)}
            className="mt-1"
            placeholder="%, kg 등"
          />
        </div>
      </div>

      {/* 플레이스홀더 */}
      <div>
        <Label htmlFor="placeholder" className="text-sm font-medium">
          플레이스홀더
        </Label>
        <Input
          id="placeholder"
          value={localValues.placeholder}
          onChange={(e) => updateConfig("placeholder", e.target.value)}
          placeholder="숫자를 입력하세요"
          className="mt-1"
        />
      </div>
    </div>
  );
};
