"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 { Textarea } from "@/components/ui/textarea";
// import { Switch } from "@/components/ui/switch";
// import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { WebTypeConfigPanelProps } from "@/lib/registry/types";
import { WidgetComponent, TextTypeConfig } from "@/types/screen";

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

  // 로컬 상태
  const [localConfig, setLocalConfig] = useState<TextTypeConfig>({
    minLength: config.minLength || undefined,
    maxLength: config.maxLength || undefined,
    pattern: config.pattern || "",
    placeholder: config.placeholder || "",
    autoComplete: config.autoComplete || "off",
    format: config.format || "none",
    required: config.required || false,
    readonly: config.readonly || false,
  });

  // 컴포넌트 변경 시 로컬 상태 동기화
  useEffect(() => {
    const currentConfig = (widget.webTypeConfig as TextTypeConfig) || {};
    setLocalConfig({
      minLength: currentConfig.minLength || undefined,
      maxLength: currentConfig.maxLength || undefined,
      pattern: currentConfig.pattern || "",
      placeholder: currentConfig.placeholder || "",
      autoComplete: currentConfig.autoComplete || "off",
      format: currentConfig.format || "none",
      required: currentConfig.required || false,
      readonly: currentConfig.readonly || false,
    });
  }, [widget.webTypeConfig]);

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

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-xs" style={{ fontSize: "12px" }}>텍스트 설정</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" style={{ fontSize: "12px" }}
            />
          </div>

          <div className="grid grid-cols-2 gap-2">
            <div className="space-y-2">
              <Label htmlFor="minLength" className="text-xs">
                최소 길이
              </Label>
              <Input
                id="minLength"
                type="number"
                value={localConfig.minLength || ""}
                onChange={(e) => updateConfig("minLength", e.target.value ? parseInt(e.target.value) : undefined)}
                placeholder="0"
                min="0"
                className="text-xs" style={{ fontSize: "12px" }}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="maxLength" className="text-xs">
                최대 길이
              </Label>
              <Input
                id="maxLength"
                type="number"
                value={localConfig.maxLength || ""}
                onChange={(e) => updateConfig("maxLength", e.target.value ? parseInt(e.target.value) : undefined)}
                placeholder="100"
                min="1"
                className="text-xs" style={{ fontSize: "12px" }}
              />
            </div>
          </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
              id="format"
              value={localConfig.format || "none"}
              onChange={(e) => updateConfig("format", e.target.value)}
              className="border-input placeholder:text-muted-foreground focus-visible:ring-ring flex h-9 w-full rounded-md border bg-transparent px-3 py-1 text-xs shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:ring-1 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
            >
              <option value="none">제한 없음</option>
              <option value="email">이메일</option>
              <option value="phone">전화번호</option>
              <option value="url">URL</option>
              <option value="korean">한글만</option>
              <option value="english">영문만</option>
              <option value="alphanumeric">영숫자만</option>
            </select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="pattern" className="text-xs">
              정규식 패턴
            </Label>
            <Input
              id="pattern"
              value={localConfig.pattern || ""}
              onChange={(e) => updateConfig("pattern", e.target.value)}
              placeholder="예: [A-Za-z0-9]+"
              className="font-mono text-xs" style={{ fontSize: "12px" }}
            />
            <p className="text-muted-foreground text-xs">JavaScript 정규식 패턴을 입력하세요.</p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="autoComplete" className="text-xs">
              자동완성
            </Label>
            <select
              id="autoComplete"
              value={localConfig.autoComplete || "off"}
              onChange={(e) => updateConfig("autoComplete", e.target.value)}
              className="border-input placeholder:text-muted-foreground focus-visible:ring-ring flex h-9 w-full rounded-md border bg-transparent px-3 py-1 text-xs shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:ring-1 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
            >
              <option value="off">사용 안함</option>
              <option value="on">사용</option>
              <option value="name">이름</option>
              <option value="email">이메일</option>
              <option value="username">사용자명</option>
              <option value="current-password">현재 비밀번호</option>
              <option value="new-password">새 비밀번호</option>
              <option value="organization">조직명</option>
              <option value="street-address">주소</option>
              <option value="tel">전화번호</option>
            </select>
          </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>
            <input
              type="checkbox"
              id="required"
              checked={localConfig.required || false}
              onChange={(e) => updateConfig("required", e.target.checked)}
              className="border-input bg-background text-primary focus:ring-ring h-4 w-4 rounded border focus:ring-2 focus:ring-offset-2"
            />
          </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>
            <input
              type="checkbox"
              id="readonly"
              checked={localConfig.readonly || false}
              onChange={(e) => updateConfig("readonly", e.target.checked)}
              className="border-input bg-background text-primary focus:ring-ring h-4 w-4 rounded border focus:ring-2 focus:ring-offset-2"
            />
          </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
              placeholder={localConfig.placeholder || "미리보기"}
              disabled={localConfig.readonly}
              required={localConfig.required}
              maxLength={localConfig.maxLength}
              minLength={localConfig.minLength}
              pattern={localConfig.pattern}
              autoComplete={localConfig.autoComplete}
              className="text-xs" style={{ fontSize: "12px" }}
            />
          </div>
        </div>
      </CardContent>
    </Card>
  );
};

TextConfigPanel.displayName = "TextConfigPanel";
