"use client";

import React, { useState, useEffect } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { Search, Database, Link, X, Plus } from "lucide-react";
import { EntityTypeConfig } from "@/types/screen";

interface EntityTypeConfigPanelProps {
  config: EntityTypeConfig;
  onConfigChange: (config: EntityTypeConfig) => void;
}

export const EntityTypeConfigPanel: React.FC<EntityTypeConfigPanelProps> = ({ config, onConfigChange }) => {
  // 기본값이 설정된 config 사용
  const safeConfig = {
    referenceTable: "",
    referenceColumn: "id",
    displayColumns: config.displayColumns || (config.displayColumn ? [config.displayColumn] : ["name"]), // 호환성 처리
    searchColumns: [],
    filters: {},
    placeholder: "",
    displayFormat: "simple",
    separator: " - ",
    multiple: false, // 다중 선택
    uiMode: "select", // UI 모드: select, combo, modal, autocomplete
    ...config,
  };

  // 로컬 상태로 실시간 입력 관리
  const [localValues, setLocalValues] = useState({
    referenceTable: safeConfig.referenceTable,
    referenceColumn: safeConfig.referenceColumn,
    displayColumns: [...safeConfig.displayColumns],
    searchColumns: [...(safeConfig.searchColumns || [])],
    placeholder: safeConfig.placeholder,
    displayFormat: safeConfig.displayFormat,
    separator: safeConfig.separator,
    multiple: safeConfig.multiple,
    uiMode: safeConfig.uiMode,
  });

  const [newFilter, setNewFilter] = useState({ field: "", operator: "=", value: "" });
  const [newDisplayColumn, setNewDisplayColumn] = useState("");
  const [availableColumns, setAvailableColumns] = useState<string[]>([]);

  // 표시 형식 옵션
  const displayFormats = [
    { value: "simple", label: "단순 (첫 번째 컬럼만)" },
    { value: "detailed", label: "상세 (모든 컬럼 표시)" },
    { value: "custom", label: "사용자 정의" },
  ];

  // 필터 연산자들
  const operators = [
    { value: "=", label: "같음 (=)" },
    { value: "!=", label: "다름 (!=)" },
    { value: "like", label: "포함 (LIKE)" },
    { value: ">", label: "초과 (>)" },
    { value: "<", label: "미만 (<)" },
    { value: ">=", label: "이상 (>=)" },
    { value: "<=", label: "이하 (<=)" },
    { value: "in", label: "포함됨 (IN)" },
    { value: "not_in", label: "포함안됨 (NOT IN)" },
  ];

  // config가 변경될 때 로컬 상태 동기화
  useEffect(() => {
    setLocalValues({
      referenceTable: safeConfig.referenceTable,
      referenceColumn: safeConfig.referenceColumn,
      displayColumns: [...safeConfig.displayColumns],
      searchColumns: [...(safeConfig.searchColumns || [])],
      placeholder: safeConfig.placeholder,
      displayFormat: safeConfig.displayFormat,
      separator: safeConfig.separator,
      multiple: safeConfig.multiple,
      uiMode: safeConfig.uiMode,
    });
  }, [
    safeConfig.referenceTable,
    safeConfig.referenceColumn,
    safeConfig.displayColumns,
    safeConfig.searchColumns,
    safeConfig.placeholder,
    safeConfig.displayFormat,
    safeConfig.separator,
    safeConfig.multiple,
    safeConfig.uiMode,
  ]);

  // UI 모드 옵션
  const uiModes = [
    { value: "select", label: "드롭다운 선택" },
    { value: "combo", label: "입력 + 모달 버튼" },
    { value: "modal", label: "모달 팝업" },
    { value: "autocomplete", label: "자동완성" },
  ];

  const updateConfig = (key: keyof EntityTypeConfig, value: any) => {
    // 로컬 상태 즉시 업데이트
    setLocalValues((prev) => ({ ...prev, [key]: value }));

    // 실제 config 업데이트
    const newConfig = { ...safeConfig, [key]: value };
    // console.log("🏢 EntityTypeConfig 업데이트:", {
    // key,
    // value,
    // oldConfig: safeConfig,
    // newConfig,
    // });
    onConfigChange(newConfig);
  };

  // 표시 컬럼 추가
  const addDisplayColumn = () => {
    if (newDisplayColumn.trim() && !localValues.displayColumns.includes(newDisplayColumn.trim())) {
      const updatedColumns = [...localValues.displayColumns, newDisplayColumn.trim()];
      updateConfig("displayColumns", updatedColumns);
      setNewDisplayColumn("");
    }
  };

  // 표시 컬럼 제거
  const removeDisplayColumn = (index: number) => {
    const updatedColumns = localValues.displayColumns.filter((_, i) => i !== index);
    updateConfig("displayColumns", updatedColumns);
  };

  const addFilter = () => {
    if (newFilter.field.trim() && newFilter.value.trim()) {
      const updatedFilters = { ...safeConfig.filters, [newFilter.field]: newFilter.value };
      updateConfig("filters", updatedFilters);
      setNewFilter({ field: "", operator: "=", value: "" });
    }
  };

  const removeFilter = (field: string) => {
    const updatedFilters = { ...safeConfig.filters };
    delete updatedFilters[field];
    updateConfig("filters", updatedFilters);
  };

  const updateFilter = (oldField: string, field: string, value: string) => {
    const updatedFilters = { ...safeConfig.filters };
    if (oldField !== field) {
      delete updatedFilters[oldField];
    }
    updatedFilters[field] = value;
    updateConfig("filters", updatedFilters);
  };

  return (
    <div className="space-y-4">
      {/* 참조 테이블 */}
      <div>
        <Label htmlFor="referenceTable" className="text-sm font-medium">
          참조 테이블
        </Label>
        <Input
          id="referenceTable"
          value={localValues.referenceTable}
          onChange={(e) => updateConfig("referenceTable", e.target.value)}
          placeholder="예: user_info, company_info"
          className="mt-1"
        />
      </div>

      {/* 조인 컬럼 (값 필드) */}
      <div>
        <Label htmlFor="referenceColumn" className="text-sm font-medium">
          조인 컬럼 (값 필드)
        </Label>
        <Input
          id="referenceColumn"
          value={localValues.referenceColumn}
          onChange={(e) => updateConfig("referenceColumn", e.target.value)}
          placeholder="id, user_id, company_code"
          className="mt-1"
        />
      </div>

      {/* 표시 컬럼들 (다중 선택) */}
      <div className="space-y-3">
        <Label className="text-sm font-medium">표시 컬럼들</Label>

        {/* 현재 선택된 표시 컬럼들 */}
        <div className="space-y-2">
          {localValues.displayColumns.map((column, index) => (
            <div key={index} className="flex items-center space-x-2 rounded border bg-muted p-2">
              <Database className="h-4 w-4 text-muted-foreground" />
              <span className="flex-1 text-sm font-medium">{column}</span>
              <Button size="sm" variant="outline" onClick={() => removeDisplayColumn(index)}>
                <X className="h-3 w-3" />
              </Button>
            </div>
          ))}

          {localValues.displayColumns.length === 0 && (
            <div className="text-sm text-muted-foreground italic">표시할 컬럼을 추가해주세요</div>
          )}
        </div>

        {/* 새 표시 컬럼 추가 */}
        <div className="flex items-center space-x-2">
          <Input
            value={newDisplayColumn}
            onChange={(e) => setNewDisplayColumn(e.target.value)}
            placeholder="컬럼명 입력 (예: user_name, dept_name)"
            className="flex-1"
          />
          <Button
            size="sm"
            onClick={addDisplayColumn}
            disabled={!newDisplayColumn.trim() || localValues.displayColumns.includes(newDisplayColumn.trim())}
          >
            <Plus className="mr-1 h-3 w-3" />
            추가
          </Button>
        </div>

        <div className="text-xs text-muted-foreground">
          • 여러 컬럼을 선택하면 "{localValues.separator || " - "}"로 구분하여 표시됩니다
          <br />• 예: 이름{localValues.separator || " - "}부서명
        </div>
      </div>

      {/* 구분자 설정 */}
      <div>
        <Label htmlFor="separator" className="text-sm font-medium">
          구분자
        </Label>
        <Input
          id="separator"
          value={localValues.separator}
          onChange={(e) => updateConfig("separator", e.target.value)}
          placeholder=" - "
          className="mt-1"
        />
      </div>

      {/* 표시 형식 */}
      <div>
        <Label htmlFor="displayFormat" className="text-sm font-medium">
          표시 형식
        </Label>
        <Select value={localValues.displayFormat} onValueChange={(value) => updateConfig("displayFormat", value)}>
          <SelectTrigger className="mt-1 h-6 w-full px-2 py-0 text-xs">
            <SelectValue placeholder="형식 선택" />
          </SelectTrigger>
          <SelectContent>
            {displayFormats.map((format) => (
              <SelectItem key={format.value} value={format.value}>
                {format.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* 플레이스홀더 */}
      <div>
        <Label htmlFor="placeholder" className="text-sm font-medium">
          플레이스홀더
        </Label>
        <Input
          id="placeholder"
          value={localValues.placeholder}
          onChange={(e) => updateConfig("placeholder", e.target.value)}
          placeholder="엔터티를 선택하세요"
          className="mt-1"
        />
      </div>

      {/* UI 모드 */}
      <div>
        <Label htmlFor="uiMode" className="text-sm font-medium">
          UI 모드
        </Label>
        <Select value={localValues.uiMode || "select"} onValueChange={(value) => updateConfig("uiMode", value)}>
          <SelectTrigger className="mt-1 h-8 w-full text-xs">
            <SelectValue placeholder="모드 선택" />
          </SelectTrigger>
          <SelectContent>
            {uiModes.map((mode) => (
              <SelectItem key={mode.value} value={mode.value}>
                {mode.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <p className="text-muted-foreground mt-1 text-xs">
          {localValues.uiMode === "select" && "검색 가능한 드롭다운 형태로 표시됩니다."}
          {localValues.uiMode === "combo" && "입력 필드와 검색 버튼이 함께 표시됩니다."}
          {localValues.uiMode === "modal" && "모달 팝업에서 데이터를 검색하고 선택합니다."}
          {localValues.uiMode === "autocomplete" && "입력하면서 자동완성 목록이 표시됩니다."}
        </p>
      </div>

      {/* 다중 선택 */}
      <div className="flex items-center justify-between rounded-md border p-3">
        <div className="space-y-1">
          <Label htmlFor="multiple" className="text-sm font-medium">
            다중 선택
          </Label>
          <p className="text-muted-foreground text-xs">여러 항목을 선택할 수 있습니다.</p>
        </div>
        <Switch
          id="multiple"
          checked={localValues.multiple || false}
          onCheckedChange={(checked) => updateConfig("multiple", checked)}
        />
      </div>

      {/* 필터 관리 */}
      <div className="space-y-3">
        <Label className="text-sm font-medium">데이터 필터</Label>

        {/* 기존 필터 목록 */}
        <div className="max-h-40 space-y-2 overflow-y-auto">
          {Object.entries(safeConfig.filters || {}).map(([field, value]) => (
            <div key={field} className="flex items-center space-x-2 rounded border p-2 text-xs">
              <Input
                value={field}
                onChange={(e) => updateFilter(field, e.target.value, value as string)}
                placeholder="필드명"
                className="flex-1"
              />
              <span className="text-muted-foreground">=</span>
              <Input
                value={value as string}
                onChange={(e) => updateFilter(field, field, e.target.value)}
                placeholder="값"
                className="flex-1"
              />
              <Button size="sm" variant="outline" onClick={() => removeFilter(field)}>
                <X className="h-3 w-3" />
              </Button>
            </div>
          ))}
        </div>

        {/* 새 필터 추가 */}
        <div className="flex items-center space-x-2 rounded border-2 border-dashed border-input p-2">
          <Input
            value={newFilter.field}
            onChange={(e) => setNewFilter((prev) => ({ ...prev, field: e.target.value }))}
            placeholder="필드명"
            className="flex-1"
          />
          <span className="text-muted-foreground">=</span>
          <Input
            value={newFilter.value}
            onChange={(e) => setNewFilter((prev) => ({ ...prev, value: e.target.value }))}
            placeholder="값"
            className="flex-1"
          />
          <Button size="sm" onClick={addFilter} disabled={!newFilter.field.trim() || !newFilter.value.trim()}>
            <Plus className="h-3 w-3" />
          </Button>
        </div>

        <div className="text-xs text-muted-foreground">총 {Object.keys(safeConfig.filters || {}).length}개 필터</div>
      </div>

      {/* 미리보기 */}
      <div className="rounded-md border bg-muted p-3">
        <Label className="text-sm font-medium text-foreground">미리보기</Label>
        <div className="mt-2">
          <div className="flex items-center space-x-2 rounded border bg-white p-2">
            <Search className="h-4 w-4 text-muted-foreground/70" />
            <div className="text-muted-foreground flex-1 text-xs">
              {localValues.placeholder || `${localValues.referenceTable || "엔터티"}를 선택하세요`}
            </div>
            <Database className="h-4 w-4 text-muted-foreground/70" />
          </div>
        </div>
        <div className="mt-2 text-xs text-muted-foreground">
          참조테이블: {localValues.referenceTable || "없음"}, 조인컬럼: {localValues.referenceColumn}
          <br />
          표시컬럼:{" "}
          {localValues.displayColumns.length > 0
            ? localValues.displayColumns.join(localValues.separator || " - ")
            : "없음"}
        </div>
      </div>

      {/* 안내 메시지 */}
      <div className="bg-accent rounded-md p-3">
        <div className="text-sm font-medium text-primary">엔터티 타입 설정 가이드</div>
        <div className="mt-1 text-xs text-primary">
          • <strong>참조 테이블</strong>: 데이터를 가져올 다른 테이블 이름
          <br />• <strong>조인 컬럼</strong>: 테이블 간 연결에 사용할 기준 컬럼 (보통 ID)
          <br />• <strong>표시 컬럼</strong>: 사용자에게 보여질 컬럼들 (여러 개 가능)
          <br />
          • 여러 표시 컬럼 설정 시 화면마다 다르게 표시할 수 있습니다
          <br />• 예: 사용자 선택 시 "이름"만 보이거나 "이름 - 부서명" 형태로 표시
        </div>
      </div>
    </div>
  );
};

export default EntityTypeConfigPanel;
