"use client";

import React, { useState, useEffect } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { WebTypeConfigPanelProps } from "@/lib/registry/types";
import { WidgetComponent, NumberTypeConfig } from "@/types/screen";

export const NumberConfigPanel: React.FC<WebTypeConfigPanelProps> = ({
  component,
  onUpdateComponent,
  onUpdateProperty,
}) => {
  const widget = component as WidgetComponent;
  const config = (widget.webTypeConfig as NumberTypeConfig) || {};

  // 로컬 상태
  const [localConfig, setLocalConfig] = useState<NumberTypeConfig>({
    min: config.min || undefined,
    max: config.max || undefined,
    step: config.step || undefined,
    format: config.format || "integer",
    decimalPlaces: config.decimalPlaces || undefined,
    thousandSeparator: config.thousandSeparator || false,
    placeholder: config.placeholder || "",
    required: config.required || false,
    readonly: config.readonly || false,
  });

  // 컴포넌트 변경 시 로컬 상태 동기화
  useEffect(() => {
    const currentConfig = (widget.webTypeConfig as NumberTypeConfig) || {};
    setLocalConfig({
      min: currentConfig.min || undefined,
      max: currentConfig.max || undefined,
      step: currentConfig.step || undefined,
      format: currentConfig.format || "integer",
      decimalPlaces: currentConfig.decimalPlaces || undefined,
      thousandSeparator: currentConfig.thousandSeparator || false,
      placeholder: currentConfig.placeholder || "",
      required: currentConfig.required || false,
      readonly: currentConfig.readonly || false,
    });
  }, [widget.webTypeConfig]);

  // 설정 업데이트 핸들러
  const updateConfig = (field: keyof NumberTypeConfig, value: any) => {
    const newConfig = { ...localConfig, [field]: value };
    setLocalConfig(newConfig);
    onUpdateProperty("webTypeConfig", newConfig);
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-xs">숫자 설정</CardTitle>
        <CardDescription className="text-xs">숫자 입력 필드의 세부 설정을 관리합니다.</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* 기본 설정 */}
        <div className="space-y-3">
          <h4 className="text-sm font-medium">기본 설정</h4>

          <div className="space-y-2">
            <Label htmlFor="placeholder" className="text-xs">
              플레이스홀더
            </Label>
            <Input
              id="placeholder"
              value={localConfig.placeholder || ""}
              onChange={(e) => updateConfig("placeholder", e.target.value)}
              placeholder="숫자를 입력하세요"
              className="text-xs"
            />
          </div>

          <div className="grid grid-cols-2 gap-2">
            <div className="space-y-2">
              <Label htmlFor="min" className="text-xs">
                최솟값
              </Label>
              <Input
                id="min"
                type="number"
                value={localConfig.min ?? ""}
                onChange={(e) => updateConfig("min", e.target.value ? parseFloat(e.target.value) : undefined)}
                placeholder="0"
                className="text-xs"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="max" className="text-xs">
                최댓값
              </Label>
              <Input
                id="max"
                type="number"
                value={localConfig.max ?? ""}
                onChange={(e) => updateConfig("max", e.target.value ? parseFloat(e.target.value) : undefined)}
                placeholder="100"
                className="text-xs"
              />
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="step" className="text-xs">
              증감 단위
            </Label>
            <Input
              id="step"
              type="number"
              value={localConfig.step ?? ""}
              onChange={(e) => updateConfig("step", e.target.value ? parseFloat(e.target.value) : undefined)}
              placeholder="1"
              min="0"
              step="0.01"
              className="text-xs"
            />
            <p className="text-muted-foreground text-xs">증가/감소 버튼 클릭 시 변경되는 값의 크기</p>
          </div>
        </div>

        {/* 형식 설정 */}
        <div className="space-y-3">
          <h4 className="text-sm font-medium">형식 설정</h4>

          <div className="space-y-2">
            <Label htmlFor="format" className="text-xs">
              숫자 형식
            </Label>
            <Select value={localConfig.format || "integer"} onValueChange={(value) => updateConfig("format", value)}>
              <SelectTrigger className="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>

          {(localConfig.format === "decimal" || localConfig.format === "currency") && (
            <div className="space-y-2">
              <Label htmlFor="decimalPlaces" className="text-xs">
                소수점 자릿수
              </Label>
              <Input
                id="decimalPlaces"
                type="number"
                value={localConfig.decimalPlaces ?? ""}
                onChange={(e) => updateConfig("decimalPlaces", e.target.value ? parseInt(e.target.value) : undefined)}
                placeholder="2"
                min="0"
                max="10"
                className="text-xs"
              />
            </div>
          )}

          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <Label htmlFor="thousandSeparator" className="text-xs">
                천 단위 구분자
              </Label>
              <p className="text-muted-foreground text-xs">1,000 형태로 표시합니다.</p>
            </div>
            <Switch
              id="thousandSeparator"
              checked={localConfig.thousandSeparator || false}
              onCheckedChange={(checked) => updateConfig("thousandSeparator", checked)}
            />
          </div>
        </div>

        {/* 상태 설정 */}
        <div className="space-y-3">
          <h4 className="text-sm font-medium">상태 설정</h4>

          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <Label htmlFor="required" className="text-xs">
                필수 입력
              </Label>
              <p className="text-muted-foreground text-xs">값이 입력되어야 합니다.</p>
            </div>
            <Switch
              id="required"
              checked={localConfig.required || false}
              onCheckedChange={(checked) => updateConfig("required", checked)}
            />
          </div>

          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <Label htmlFor="readonly" className="text-xs">
                읽기 전용
              </Label>
              <p className="text-muted-foreground text-xs">값을 수정할 수 없습니다.</p>
            </div>
            <Switch
              id="readonly"
              checked={localConfig.readonly || false}
              onCheckedChange={(checked) => updateConfig("readonly", checked)}
            />
          </div>
        </div>

        {/* 미리보기 */}
        <div className="space-y-3">
          <h4 className="text-sm font-medium">미리보기</h4>
          <div className="bg-muted/50 rounded-md border p-3">
            <Input
              type="number"
              placeholder={localConfig.placeholder || "숫자 입력 미리보기"}
              disabled={localConfig.readonly}
              required={localConfig.required}
              min={localConfig.min}
              max={localConfig.max}
              step={localConfig.step}
              className="text-xs"
            />
            <div className="text-muted-foreground mt-2 text-xs">
              {localConfig.format === "currency" && "통화 형식으로 표시됩니다."}
              {localConfig.format === "percentage" && "퍼센트 형식으로 표시됩니다."}
              {localConfig.thousandSeparator && "천 단위 구분자가 적용됩니다."}
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
};

NumberConfigPanel.displayName = "NumberConfigPanel";


