"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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Plus, Trash2, List } from "lucide-react";
import { WebTypeConfigPanelProps } from "@/lib/registry/types";
import { WidgetComponent, SelectTypeConfig } from "@/types/screen";

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

export const SelectConfigPanel: React.FC<WebTypeConfigPanelProps> = ({
  component,
  onUpdateComponent,
  onUpdateProperty,
}) => {
  const widget = component as WidgetComponent;
  const config = (widget.web_type_config as unknown as SelectTypeConfig) || {};

  // 로컬 상태
  const [localConfig, setLocalConfig] = useState<SelectTypeConfig>({
    options: config.options || [
      { label: "옵션 1", value: "option1" },
      { label: "옵션 2", value: "option2" },
    ],
    multiple: config.multiple || false,
    searchable: config.searchable || false,
    placeholder: config.placeholder || "선택하세요",
    default_value: config.default_value || "",
    required: config.required || false,
    readonly: config.readonly || false,
    empty_message: config.empty_message || "선택 가능한 옵션이 없습니다",
  });

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

  // 컴포넌트 변경 시 로컬 상태 동기화
  useEffect(() => {
    const currentConfig = (widget.web_type_config as unknown as SelectTypeConfig) || {};
    setLocalConfig({
      options: currentConfig.options || [
        { label: "옵션 1", value: "option1" },
        { label: "옵션 2", value: "option2" },
      ],
      multiple: currentConfig.multiple || false,
      searchable: currentConfig.searchable || false,
      placeholder: currentConfig.placeholder || "선택하세요",
      default_value: currentConfig.default_value || "",
      required: currentConfig.required || false,
      readonly: currentConfig.readonly || false,
      empty_message: currentConfig.empty_message || "선택 가능한 옵션이 없습니다",
    });
    
    // 입력 필드 로컬 상태도 동기화
    setLocalInputs({
      placeholder: currentConfig.placeholder || "",
      empty_message: currentConfig.empty_message || "",
    });
    
  }, [widget.web_type_config]);

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

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

    const newOption: SelectOption = {
      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 updateOptionLocal = (index: number, field: keyof SelectOption, value: any) => {
    const newOptions = [...localConfig.options];
    newOptions[index] = { ...newOptions[index], [field]: value };
    setLocalConfig({ ...localConfig, options: newOptions });
  };

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

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

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

    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" },
    ],
    status: [
      { label: "활성", value: "active" },
      { label: "비활성", value: "inactive" },
      { label: "대기", value: "pending" },
    ],
    priority: [
      { label: "높음", value: "high" },
      { label: "보통", value: "medium" },
      { label: "낮음", value: "low" },
    ],
  };

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

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-xs">
          <List 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="placeholder" className="text-xs">
              플레이스홀더
            </Label>
            <Input
              id="placeholder"
              value={localInputs.placeholder}
              onChange={(e) => setLocalInputs({ ...localInputs, placeholder: e.target.value })}
              onBlur={() => updateConfig("placeholder", localInputs.placeholder)}
              placeholder="선택하세요"
              className="text-xs"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="emptyMessage" className="text-xs">
              빈 목록 메시지
            </Label>
            <Input
              id="emptyMessage"
              value={localInputs.empty_message}
              onChange={(e) => setLocalInputs({ ...localInputs, empty_message: e.target.value })}
              onBlur={() => updateConfig("empty_message", localInputs.empty_message)}
              placeholder="선택 가능한 옵션이 없습니다"
              className="text-xs"
            />
          </div>

          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <Label htmlFor="multiple" className="text-xs">
                다중 선택
              </Label>
              <p className="text-muted-foreground text-xs">여러 옵션을 선택할 수 있습니다.</p>
            </div>
            <Switch
              id="multiple"
              checked={localConfig.multiple || false}
              onCheckedChange={(checked) => updateConfig("multiple", checked)}
            />
          </div>

          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <Label htmlFor="searchable" className="text-xs">
                검색 가능
              </Label>
              <p className="text-muted-foreground text-xs">옵션을 검색할 수 있습니다.</p>
            </div>
            <Switch
              id="searchable"
              checked={localConfig.searchable || false}
              onCheckedChange={(checked) => updateConfig("searchable", checked)}
            />
          </div>
        </div>

        {/* 기본 옵션 세트 */}
        <div className="space-y-3">
          <h4 className="text-sm font-medium">기본 옵션 세트</h4>
          <div className="flex flex-wrap gap-2">
            <Button size="sm" variant="outline" onClick={() => applyDefaultSet("yesno")} className="text-xs">
              예/아니오
            </Button>
            <Button size="sm" variant="outline" onClick={() => applyDefaultSet("status")} className="text-xs">
              상태
            </Button>
            <Button size="sm" variant="outline" onClick={() => applyDefaultSet("priority")} 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("web_type_config", 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.default_value || ""}
              onChange={(e) => updateConfig("default_value", 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">
            <select
              disabled={localConfig.readonly}
              required={localConfig.required}
              multiple={localConfig.multiple}
              className="w-full rounded-md border px-3 py-1 text-xs"
              defaultValue={localConfig.default_value}
            >
              <option value="" disabled>
                {localConfig.placeholder}
              </option>
              {localConfig.options.map((option, index) => (
                <option key={index} value={option.value} disabled={option.disabled}>
                  {option.label}
                </option>
              ))}
            </select>
            <div className="text-muted-foreground mt-2 text-xs">
              {localConfig.multiple && "다중 선택 가능"}
              {localConfig.searchable && " • 검색 가능"}
              {localConfig.required && " • 필수 선택"}
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
};

SelectConfigPanel.displayName = "SelectConfigPanel";
