"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, Link2, ExternalLink } from "lucide-react";
import { WebTypeConfigPanelProps } from "@/lib/registry/types";
import { WidgetComponent, SelectTypeConfig } from "@/types/screen";
import { cascadingRelationApi, CascadingRelation } from "@/lib/api/cascadingRelation";
import Link from "next/link";

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.webTypeConfig 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 || "선택하세요",
    defaultValue: config.defaultValue || "",
    required: config.required || false,
    readonly: config.readonly || false,
    emptyMessage: config.emptyMessage || "선택 가능한 옵션이 없습니다",
    cascadingRelationCode: config.cascadingRelationCode,
    cascadingParentField: config.cascadingParentField,
  });
  
  // 연쇄 드롭다운 설정 상태
  const [cascadingEnabled, setCascadingEnabled] = useState(!!config.cascadingRelationCode);
  const [selectedRelationCode, setSelectedRelationCode] = useState(config.cascadingRelationCode || "");
  const [selectedParentField, setSelectedParentField] = useState(config.cascadingParentField || "");
  
  // 연쇄 관계 목록
  const [relationList, setRelationList] = useState<CascadingRelation[]>([]);
  const [loadingRelations, setLoadingRelations] = useState(false);

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

  // 컴포넌트 변경 시 로컬 상태 동기화
  useEffect(() => {
    const currentConfig = (widget.webTypeConfig 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 || "선택하세요",
      defaultValue: currentConfig.defaultValue || "",
      required: currentConfig.required || false,
      readonly: currentConfig.readonly || false,
      emptyMessage: currentConfig.emptyMessage || "선택 가능한 옵션이 없습니다",
      cascadingRelationCode: currentConfig.cascadingRelationCode,
    });
    
    // 입력 필드 로컬 상태도 동기화
    setLocalInputs({
      placeholder: currentConfig.placeholder || "",
      emptyMessage: currentConfig.emptyMessage || "",
    });
    
    // 연쇄 드롭다운 설정 동기화
    setCascadingEnabled(!!currentConfig.cascadingRelationCode);
    setSelectedRelationCode(currentConfig.cascadingRelationCode || "");
    setSelectedParentField(currentConfig.cascadingParentField || "");
  }, [widget.webTypeConfig]);
  
  // 연쇄 관계 목록 로드
  useEffect(() => {
    if (cascadingEnabled && relationList.length === 0) {
      loadRelationList();
    }
  }, [cascadingEnabled]);
  
  // 연쇄 관계 목록 로드 함수
  const loadRelationList = async () => {
    setLoadingRelations(true);
    try {
      const response = await cascadingRelationApi.getList("Y");
      if (response.success && response.data) {
        setRelationList(response.data);
      }
    } catch (error) {
      console.error("연쇄 관계 목록 로드 실패:", error);
    } finally {
      setLoadingRelations(false);
    }
  };

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

  // 연쇄 드롭다운 활성화/비활성화
  const handleCascadingToggle = (enabled: boolean) => {
    setCascadingEnabled(enabled);
    
    if (!enabled) {
      // 비활성화 시 관계 코드 제거
      setSelectedRelationCode("");
      const newConfig = { ...localConfig, cascadingRelationCode: undefined };
      setLocalConfig(newConfig);
      onUpdateProperty("webTypeConfig", newConfig);
    } else {
      // 활성화 시 관계 목록 로드
      loadRelationList();
    }
  };
  
  // 연쇄 관계 선택
  const handleRelationSelect = (code: string) => {
    setSelectedRelationCode(code);
    const newConfig = { ...localConfig, cascadingRelationCode: code || undefined };
    setLocalConfig(newConfig);
    onUpdateProperty("webTypeConfig", newConfig);
  };
  
  // 부모 필드 선택
  const handleParentFieldChange = (field: string) => {
    setSelectedParentField(field);
    const newConfig = { ...localConfig, cascadingParentField: field || undefined };
    setLocalConfig(newConfig);
    onUpdateProperty("webTypeConfig", 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("webTypeConfig", 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]);
  };

  // 선택된 관계 정보
  const selectedRelation = relationList.find(r => r.relation_code === selectedRelationCode);

  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.emptyMessage}
              onChange={(e) => setLocalInputs({ ...localInputs, emptyMessage: e.target.value })}
              onBlur={() => updateConfig("emptyMessage", localInputs.emptyMessage)}
              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">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Link2 className="h-4 w-4" />
              <h4 className="text-sm font-medium">연쇄 드롭다운</h4>
            </div>
            <Switch
              checked={cascadingEnabled}
              onCheckedChange={handleCascadingToggle}
            />
          </div>
          <p className="text-muted-foreground text-xs">
            다른 필드의 값에 따라 옵션이 동적으로 변경됩니다. (예: 창고 선택 → 해당 창고의 위치만 표시)
          </p>
          
          {cascadingEnabled && (
            <div className="space-y-3 rounded-md border p-3">
              {/* 관계 선택 */}
              <div className="space-y-2">
                <Label className="text-xs">연쇄 관계 선택</Label>
                <Select
                  value={selectedRelationCode}
                  onValueChange={handleRelationSelect}
                >
                  <SelectTrigger className="text-xs">
                    <SelectValue placeholder={loadingRelations ? "로딩 중..." : "관계 선택"} />
                  </SelectTrigger>
                  <SelectContent>
                    {relationList.map((relation) => (
                      <SelectItem key={relation.relation_code} value={relation.relation_code}>
                        <div className="flex flex-col">
                          <span>{relation.relation_name}</span>
                          <span className="text-muted-foreground text-xs">
                            {relation.parent_table} → {relation.child_table}
                          </span>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <p className="text-muted-foreground text-xs">
                  미리 정의된 관계를 선택하세요.
                </p>
              </div>
              
              {/* 부모 필드 설정 */}
              {selectedRelationCode && (
                <div className="space-y-2">
                  <Label className="text-xs">부모 필드 (화면 내 필드명)</Label>
                  <Input
                    value={selectedParentField}
                    onChange={(e) => handleParentFieldChange(e.target.value)}
                    placeholder="예: warehouse_code"
                    className="text-xs"
                  />
                  <p className="text-muted-foreground text-xs">
                    이 드롭다운의 옵션을 결정할 부모 필드의 컬럼명을 입력하세요.
                  </p>
                </div>
              )}
              
              {/* 선택된 관계 정보 표시 */}
              {selectedRelation && (
                <div className="bg-muted/50 space-y-2 rounded-md p-2">
                  <div className="text-xs">
                    <span className="text-muted-foreground">부모 테이블:</span>{" "}
                    <span className="font-medium">{selectedRelation.parent_table}</span>
                    <span className="text-muted-foreground"> ({selectedRelation.parent_value_column})</span>
                  </div>
                  <div className="text-xs">
                    <span className="text-muted-foreground">자식 테이블:</span>{" "}
                    <span className="font-medium">{selectedRelation.child_table}</span>
                    <span className="text-muted-foreground">
                      {" "}({selectedRelation.child_filter_column} → {selectedRelation.child_value_column})
                    </span>
                  </div>
                  {selectedRelation.description && (
                    <div className="text-muted-foreground text-xs">{selectedRelation.description}</div>
                  )}
                </div>
              )}
              
              {/* 관계 관리 페이지 링크 */}
              <div className="flex justify-end">
                <Link href="/admin/cascading-relations" target="_blank">
                  <Button variant="link" size="sm" className="h-auto p-0 text-xs">
                    <ExternalLink className="mr-1 h-3 w-3" />
                    관계 관리
                  </Button>
                </Link>
              </div>
            </div>
          )}
        </div>

        {/* 기본 옵션 세트 (연쇄 드롭다운 비활성화 시에만 표시) */}
        {!cascadingEnabled && (
          <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>
        )}

        {/* 옵션 관리 (연쇄 드롭다운 비활성화 시에만 표시) */}
        {!cascadingEnabled && (
        <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>
        )}

        {/* 기본값 설정 (연쇄 드롭다운 비활성화 시에만 표시) */}
        {!cascadingEnabled && (
        <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>

        {/* 미리보기 (연쇄 드롭다운 비활성화 시에만 표시) */}
        {!cascadingEnabled && (
        <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.defaultValue}
            >
              <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";
