"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 { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Radio, Plus, Trash2 } from "lucide-react";
import { WebTypeConfigPanelProps } from "@/lib/registry/types";
import { WidgetComponent, RadioTypeConfig } from "@/types/screen";

interface RadioOption {
  label: string;
  value: string;
  disabled?: boolean;
}

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

  // 로컬 상태
  const [localConfig, setLocalConfig] = useState<RadioTypeConfig>({
    options: config.options || [
      { label: "옵션 1", value: "option1" },
      { label: "옵션 2", value: "option2" },
    ],
    groupName: config.groupName || "",
    defaultValue: config.defaultValue || "",
    required: config.required || false,
    readonly: config.readonly || false,
    inline: config.inline !== false, // 기본값 true
    groupLabel: config.groupLabel || "",
  });

  // 새 옵션 추가용 상태
  const [newOptionLabel, setNewOptionLabel] = useState("");
  const [newOptionValue, setNewOptionValue] = useState("");
  const [bulkOptions, setBulkOptions] = useState("");
  
  // 입력 필드용 로컬 상태
  const [localInputs, setLocalInputs] = useState({
    groupLabel: config.groupLabel || "",
    groupName: config.groupName || "",
  });

  // 컴포넌트 변경 시 로컬 상태 동기화
  useEffect(() => {
    const currentConfig = (widget.webTypeConfig as RadioTypeConfig) || {};
    setLocalConfig({
      options: currentConfig.options || [
        { label: "옵션 1", value: "option1" },
        { label: "옵션 2", value: "option2" },
      ],
      groupName: currentConfig.groupName || "",
      defaultValue: currentConfig.defaultValue || "",
      required: currentConfig.required || false,
      readonly: currentConfig.readonly || false,
      inline: currentConfig.inline !== false,
      groupLabel: currentConfig.groupLabel || "",
    });
    
    // 입력 필드 로컬 상태도 동기화
    setLocalInputs({
      groupLabel: currentConfig.groupLabel || "",
      groupName: currentConfig.groupName || "",
    });
  }, [widget.webTypeConfig]);

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

  // 옵션 추가
  const addOption = () => {
    if (!newOptionLabel.trim() || !newOptionValue.trim()) return;

    const newOption: RadioOption = {
      label: newOptionLabel.trim(),
      value: newOptionValue.trim(),
    };

    const newOptions = [...localConfig.options, newOption];
    updateConfig("options", newOptions);
    setNewOptionLabel("");
    setNewOptionValue("");
  };

  // 옵션 제거
  const removeOption = (index: number) => {
    const newOptions = localConfig.options.filter((_, i) => i !== index);
    updateConfig("options", newOptions);

    // 삭제된 옵션이 기본값이었다면 기본값 초기화
    const removedOption = localConfig.options[index];
    if (removedOption && localConfig.defaultValue === removedOption.value) {
      updateConfig("defaultValue", "");
    }
  };

  // 옵션 업데이트 (입력 필드용 - 로컬 상태만)
  const updateOptionLocal = (index: number, field: keyof RadioOption, value: any) => {
    const newOptions = [...localConfig.options];
    const oldValue = newOptions[index].value;
    newOptions[index] = { ...newOptions[index], [field]: value };
    
    // 값이 변경되고 해당 값이 기본값이었다면 기본값도 업데이트
    const newConfig = { ...localConfig, options: newOptions };
    if (field === "value" && localConfig.defaultValue === oldValue) {
      newConfig.defaultValue = value;
    }
    
    setLocalConfig(newConfig);
  };

  // 옵션 업데이트 완료 (onBlur)
  const handleOptionBlur = () => {
    onUpdateProperty("webTypeConfig", localConfig);
  };

  // 벌크 옵션 추가
  const addBulkOptions = () => {
    if (!bulkOptions.trim()) return;

    const lines = bulkOptions.trim().split("\n");
    const newOptions: RadioOption[] = [];

    lines.forEach((line) => {
      const trimmed = line.trim();
      if (!trimmed) return;

      if (trimmed.includes("|")) {
        // "라벨|값" 형식
        const [label, value] = trimmed.split("|").map((s) => s.trim());
        if (label && value) {
          newOptions.push({ label, value });
        }
      } else {
        // 라벨과 값이 같은 경우
        newOptions.push({ label: trimmed, value: trimmed });
      }
    });

    if (newOptions.length > 0) {
      const combinedOptions = [...localConfig.options, ...newOptions];
      updateConfig("options", combinedOptions);
      setBulkOptions("");
    }
  };

  // 기본 옵션 세트
  const defaultOptionSets = {
    yesno: [
      { label: "예", value: "Y" },
      { label: "아니오", value: "N" },
    ],
    gender: [
      { label: "남성", value: "M" },
      { label: "여성", value: "F" },
    ],
    agreement: [
      { label: "동의", value: "agree" },
      { label: "비동의", value: "disagree" },
    ],
    rating: [
      { label: "매우 좋음", value: "5" },
      { label: "좋음", value: "4" },
      { label: "보통", value: "3" },
      { label: "나쁨", value: "2" },
      { label: "매우 나쁨", value: "1" },
    ],
  };

  const applyDefaultSet = (setName: keyof typeof defaultOptionSets) => {
    updateConfig("options", defaultOptionSets[setName]);
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-xs">
          <Radio className="h-4 w-4" />
          라디오버튼 설정
        </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="groupLabel" className="text-xs">
              그룹 라벨
            </Label>
            <Input
              id="groupLabel"
              value={localInputs.groupLabel}
              onChange={(e) => setLocalInputs({ ...localInputs, groupLabel: e.target.value })}
              onBlur={() => updateConfig("groupLabel", localInputs.groupLabel)}
              placeholder="라디오버튼 그룹 제목"
              className="text-xs"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="groupName" className="text-xs">
              그룹 이름 (name 속성)
            </Label>
            <Input
              id="groupName"
              value={localInputs.groupName}
              onChange={(e) => setLocalInputs({ ...localInputs, groupName: e.target.value })}
              onBlur={() => updateConfig("groupName", localInputs.groupName)}
              placeholder="자동 생성 (필드명 기반)"
              className="text-xs"
            />
            <p className="text-muted-foreground text-xs">비워두면 필드명을 기반으로 자동 생성됩니다.</p>
          </div>

          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <Label htmlFor="inline" className="text-xs">
                가로 배열
              </Label>
              <p className="text-muted-foreground text-xs">라디오버튼들을 가로로 배열합니다.</p>
            </div>
            <Switch
              id="inline"
              checked={localConfig.inline !== false}
              onCheckedChange={(checked) => updateConfig("inline", checked)}
            />
          </div>
        </div>

        {/* 기본 옵션 세트 */}
        <div className="space-y-3">
          <h4 className="text-sm font-medium">기본 옵션 세트</h4>
          <div className="grid grid-cols-2 gap-2">
            <Button size="sm" variant="outline" onClick={() => applyDefaultSet("yesno")} className="text-xs">
              예/아니오
            </Button>
            <Button size="sm" variant="outline" onClick={() => applyDefaultSet("gender")} className="text-xs">
              성별
            </Button>
            <Button size="sm" variant="outline" onClick={() => applyDefaultSet("agreement")} className="text-xs">
              동의/비동의
            </Button>
            <Button size="sm" variant="outline" onClick={() => applyDefaultSet("rating")} className="text-xs">
              평점
            </Button>
          </div>
        </div>

        {/* 옵션 관리 */}
        <div className="space-y-3">
          <h4 className="text-sm font-medium">옵션 관리</h4>

          {/* 개별 옵션 추가 */}
          <div className="space-y-2">
            <Label className="text-xs">개별 옵션 추가</Label>
            <div className="flex gap-2">
              <Input
                value={newOptionLabel}
                onChange={(e) => setNewOptionLabel(e.target.value)}
                placeholder="라벨"
                className="flex-1 text-xs"
              />
              <Input
                value={newOptionValue}
                onChange={(e) => setNewOptionValue(e.target.value)}
                placeholder="값"
                className="flex-1 text-xs"
              />
              <Button
                size="sm"
                onClick={addOption}
                disabled={!newOptionLabel.trim() || !newOptionValue.trim()}
                className="text-xs"
              >
                <Plus className="h-3 w-3" />
              </Button>
            </div>
          </div>

          {/* 벌크 옵션 추가 */}
          <div className="space-y-2">
            <Label className="text-xs">벌크 옵션 추가</Label>
            <Textarea
              value={bulkOptions}
              onChange={(e) => setBulkOptions(e.target.value)}
              placeholder="한 줄당 하나씩 입력하세요.&#10;라벨만 입력하면 값과 동일하게 설정됩니다.&#10;라벨|값 형식으로 입력하면 별도 값을 설정할 수 있습니다.&#10;&#10;예시:&#10;서울&#10;부산&#10;대구시|daegu"
              className="h-20 text-xs"
            />
            <Button size="sm" onClick={addBulkOptions} disabled={!bulkOptions.trim()} className="text-xs">
              옵션 추가
            </Button>
          </div>

          {/* 현재 옵션 목록 */}
          <div className="space-y-2">
            <Label className="text-xs">현재 옵션 ({localConfig.options.length}개)</Label>
            <div className="max-h-40 space-y-2 overflow-y-auto">
              {localConfig.options.map((option, index) => (
                <div key={`${option.value}-${index}`} className="flex items-center gap-2 rounded border p-2">
                  <Input
                    value={option.label}
                    onChange={(e) => updateOptionLocal(index, "label", e.target.value)}
                    onBlur={handleOptionBlur}
                    placeholder="라벨"
                    className="flex-1 text-xs"
                  />
                  <Input
                    value={option.value}
                    onChange={(e) => updateOptionLocal(index, "value", e.target.value)}
                    onBlur={handleOptionBlur}
                    placeholder="값"
                    className="flex-1 text-xs"
                  />
                  <Switch
                    checked={!option.disabled}
                    onCheckedChange={(checked) => {
                      const newOptions = [...localConfig.options];
                      newOptions[index] = { ...newOptions[index], disabled: !checked };
                      const newConfig = { ...localConfig, options: newOptions };
                      setLocalConfig(newConfig);
                      onUpdateProperty("webTypeConfig", newConfig);
                    }}
                  />
                  <Button size="sm" variant="destructive" onClick={() => removeOption(index)} className="p-1 text-xs">
                    <Trash2 className="h-3 w-3" />
                  </Button>
                </div>
              ))}
            </div>
          </div>
        </div>

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

          <div className="space-y-2">
            <Label htmlFor="defaultValue" className="text-xs">
              기본 선택값
            </Label>
            <select
              id="defaultValue"
              value={localConfig.defaultValue || ""}
              onChange={(e) => updateConfig("defaultValue", e.target.value)}
              className="w-full rounded-md border px-3 py-1 text-xs"
            >
              <option value="">선택하지 않음</option>
              {localConfig.options.map((option, index) => (
                <option key={index} value={option.value} disabled={option.disabled}>
                  {option.label}
                </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>
            <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">
            <div className="space-y-2">
              {localConfig.groupLabel && <Label className="text-xs font-medium">{localConfig.groupLabel}</Label>}
              <div className={`space-y-1 ${localConfig.inline ? "flex flex-wrap gap-4" : ""}`}>
                {localConfig.options.map((option, index) => (
                  <div key={index} className="flex items-center space-x-2">
                    <input
                      type="radio"
                      id={`preview-radio-${index}`}
                      name="preview-radio-group"
                      value={option.value}
                      disabled={localConfig.readonly || option.disabled}
                      required={localConfig.required && index === 0} // 첫 번째에만 required 표시
                      defaultChecked={localConfig.defaultValue === option.value}
                      className="text-xs"
                    />
                    <Label htmlFor={`preview-radio-${index}`} className="text-xs">
                      {option.label}
                    </Label>
                  </div>
                ))}
              </div>
            </div>
            <div className="text-muted-foreground mt-2 text-xs">
              {localConfig.options.length}개 옵션
              {localConfig.inline && " • 가로 배열"}
              {localConfig.required && " • 필수 선택"}
              {localConfig.defaultValue &&
                ` • 기본값: ${localConfig.options.find((o) => o.value === localConfig.defaultValue)?.label}`}
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
};

RadioConfigPanel.displayName = "RadioConfigPanel";
