"use client";

import React, { useState, useEffect, useMemo } from "react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Database, Table2, ChevronsUpDown, Check, LayoutGrid, LayoutList, Rows3, Plus, X, Type, Settings2, ChevronUp } from "lucide-react";
import { cn } from "@/lib/utils";
import { RepeatContainerConfig, SlotComponentConfig } from "./types";
import { tableTypeApi } from "@/lib/api/screen";
import { tableManagementApi } from "@/lib/api/tableManagement";
import { DynamicComponentConfigPanel, hasComponentConfigPanel } from "@/lib/utils/getComponentConfigPanel";

interface RepeatContainerConfigPanelProps {
  config: RepeatContainerConfig;
  onChange: (config: Partial<RepeatContainerConfig>) => void;
  screenTableName?: string;
}

/**
 * 리피터 컨테이너 설정 패널
 */
export function RepeatContainerConfigPanel({
  config,
  onChange,
  screenTableName,
}: RepeatContainerConfigPanelProps) {
  const [availableTables, setAvailableTables] = useState<Array<{ tableName: string; displayName?: string }>>([]);
  const [loadingTables, setLoadingTables] = useState(false);
  const [tableComboboxOpen, setTableComboboxOpen] = useState(false);
  
  // 컬럼 관련 상태
  const [availableColumns, setAvailableColumns] = useState<Array<{ columnName: string; displayName?: string }>>([]);
  const [loadingColumns, setLoadingColumns] = useState(false);
  
  // 제목/설명 컬럼 콤보박스 상태
  const [titleColumnOpen, setTitleColumnOpen] = useState(false);
  const [descriptionColumnOpen, setDescriptionColumnOpen] = useState(false);

  // 실제 사용할 테이블 이름 계산
  const targetTableName = useMemo(() => {
    if (config.useCustomTable && config.customTableName) {
      return config.customTableName;
    }
    return config.tableName || screenTableName;
  }, [config.useCustomTable, config.customTableName, config.tableName, screenTableName]);

  // 화면 테이블명 자동 설정 (초기 한 번만)
  useEffect(() => {
    if (screenTableName && !config.tableName && !config.customTableName) {
      onChange({ tableName: screenTableName });
    }
  }, [screenTableName, config.tableName, config.customTableName, onChange]);

  // 전체 테이블 목록 로드
  useEffect(() => {
    const fetchTables = async () => {
      setLoadingTables(true);
      try {
        const response = await tableTypeApi.getTables();
        setAvailableTables(
          response.map((table: any) => ({
            tableName: table.tableName,
            displayName: table.displayName || table.tableName,
          }))
        );
      } catch (error) {
        console.error("테이블 목록 가져오기 실패:", error);
      } finally {
        setLoadingTables(false);
      }
    };
    fetchTables();
  }, []);

  // 테이블 컬럼 로드
  useEffect(() => {
    if (!targetTableName) {
      setAvailableColumns([]);
      return;
    }

    const fetchColumns = async () => {
      setLoadingColumns(true);
      try {
        const response = await tableManagementApi.getColumnList(targetTableName);
        // API 응답이 { data: { columns: [...] } } 또는 { data: [...] } 형태일 수 있음
        const columnsData = response.data?.columns || response.data;
        if (response.success && columnsData && Array.isArray(columnsData)) {
          const columns = columnsData.map((col: any) => ({
            columnName: col.columnName,
            displayName: col.displayName || col.columnLabel || col.columnName,
          }));
          setAvailableColumns(columns);
        }
      } catch (error) {
        console.error("컬럼 목록 가져오기 실패:", error);
        setAvailableColumns([]);
      } finally {
        setLoadingColumns(false);
      }
    };
    fetchColumns();
  }, [targetTableName, config.tableName, screenTableName, config.useCustomTable, config.customTableName]);

  return (
    <div className="space-y-4">
      <div className="text-sm font-medium">리피터 컨테이너 설정</div>

      {/* 데이터 소스 테이블 설정 */}
      <div className="space-y-3">
        <div>
          <h3 className="text-sm font-semibold">데이터 소스 테이블</h3>
          <p className="text-muted-foreground text-[10px]">반복 렌더링할 데이터의 테이블을 선택합니다</p>
        </div>
        <hr className="border-border" />

        {/* 현재 선택된 테이블 표시 (카드 형태) */}
        <div className="flex items-center gap-2 rounded-md border bg-slate-50 p-2">
          <Database className="h-4 w-4 text-primary" />
          <div className="flex-1">
            <div className="text-xs font-medium">
              {config.customTableName || config.tableName || screenTableName || "테이블 미선택"}
            </div>
            <div className="text-[10px] text-muted-foreground">
              {config.useCustomTable ? "커스텀 테이블" : "화면 기본 테이블"}
            </div>
          </div>
        </div>

        {/* 테이블 선택 Combobox */}
        <Popover open={tableComboboxOpen} onOpenChange={setTableComboboxOpen}>
          <PopoverTrigger asChild>
            <Button
              variant="outline"
              role="combobox"
              aria-expanded={tableComboboxOpen}
              className="h-8 w-full justify-between text-xs"
              disabled={loadingTables}
            >
              테이블 변경...
              <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-full p-0" align="start">
            <Command>
              <CommandInput placeholder="테이블 검색..." className="h-8 text-xs" />
              <CommandList>
                <CommandEmpty className="py-2 text-xs">테이블을 찾을 수 없습니다</CommandEmpty>

                {/* 그룹 1: 화면 기본 테이블 */}
                {screenTableName && (
                  <CommandGroup heading="기본 (화면 테이블)">
                    <CommandItem
                      key={`default-${screenTableName}`}
                      value={screenTableName}
                      onSelect={() => {
                        onChange({
                          useCustomTable: false,
                          customTableName: undefined,
                          tableName: screenTableName,
                        });
                        setTableComboboxOpen(false);
                      }}
                      className="text-xs cursor-pointer"
                    >
                      <Check
                        className={cn(
                          "mr-2 h-3 w-3",
                          !config.useCustomTable ? "opacity-100" : "opacity-0"
                        )}
                      />
                      <Database className="mr-2 h-3 w-3 text-primary" />
                      {screenTableName}
                    </CommandItem>
                  </CommandGroup>
                )}

                {/* 그룹 2: 전체 테이블 */}
                <CommandGroup heading="전체 테이블">
                  {availableTables
                    .filter((table) => table.tableName !== screenTableName)
                    .map((table) => (
                      <CommandItem
                        key={table.tableName}
                        value={`${table.tableName} ${table.displayName || ""}`}
                        onSelect={() => {
                          onChange({
                            useCustomTable: true,
                            customTableName: table.tableName,
                            tableName: table.tableName,
                          });
                          setTableComboboxOpen(false);
                        }}
                        className="text-xs cursor-pointer"
                      >
                        <Check
                          className={cn(
                            "mr-2 h-3 w-3",
                            config.customTableName === table.tableName ? "opacity-100" : "opacity-0"
                          )}
                        />
                        <Table2 className="mr-2 h-3 w-3 text-slate-400" />
                        {table.displayName || table.tableName}
                      </CommandItem>
                    ))}
                </CommandGroup>
              </CommandList>
            </Command>
          </PopoverContent>
        </Popover>
      </div>

      {/* 데이터 소스 컴포넌트 연결 */}
      <div className="space-y-3">
        <div>
          <h3 className="text-sm font-semibold">데이터 소스 연결</h3>
          <p className="text-muted-foreground text-[10px]">
            테이블 리스트에서 선택한 데이터를 받아올 수 있습니다
          </p>
        </div>
        <hr className="border-border" />
        
        <div className="space-y-2">
          <Label className="text-xs">데이터 수신 방식</Label>
          <Select
            value={config.dataSourceType || "manual"}
            onValueChange={(value) => onChange({ dataSourceType: value as any })}
          >
            <SelectTrigger className="h-8 text-xs">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="manual">수동 (API에서 직접 조회)</SelectItem>
              <SelectItem value="table-list">테이블 리스트 선택 연동</SelectItem>
            </SelectContent>
          </Select>
        </div>

        {config.dataSourceType === "table-list" && (
          <div className="space-y-2">
            <Label className="text-xs">연동할 테이블 리스트 컴포넌트 ID (선택)</Label>
            <Input
              value={config.dataSourceComponentId || ""}
              onChange={(e) => onChange({ dataSourceComponentId: e.target.value })}
              placeholder="비우면 테이블명으로 자동 매칭"
              className="h-8 text-xs"
            />
            <p className="text-[10px] text-muted-foreground">
              비워두면 위에서 설정한 테이블명과 같은 테이블 리스트에서 데이터를 받습니다
            </p>
          </div>
        )}
      </div>

      {/* 슬롯 컴포넌트 설정 */}
      <SlotChildrenSection
        config={config}
        onChange={onChange}
        availableColumns={availableColumns}
        loadingColumns={loadingColumns}
        screenTableName={screenTableName}
      />

      {/* 레이아웃 설정 */}
      <div className="space-y-3">
        <div>
          <h3 className="text-sm font-semibold">레이아웃</h3>
        </div>
        <hr className="border-border" />

        {/* 레이아웃 타입 선택 */}
        <div className="space-y-1">
          <Label className="text-xs">배치 방식</Label>
          <div className="grid grid-cols-3 gap-2">
            <Button
              variant={config.layout === "vertical" ? "default" : "outline"}
              size="sm"
              onClick={() => onChange({ layout: "vertical" })}
              className="h-9 text-xs flex flex-col gap-1"
            >
              <Rows3 className="h-4 w-4" />
              <span>세로</span>
            </Button>
            <Button
              variant={config.layout === "horizontal" ? "default" : "outline"}
              size="sm"
              onClick={() => onChange({ layout: "horizontal" })}
              className="h-9 text-xs flex flex-col gap-1"
            >
              <LayoutList className="h-4 w-4 rotate-90" />
              <span>가로</span>
            </Button>
            <Button
              variant={config.layout === "grid" ? "default" : "outline"}
              size="sm"
              onClick={() => onChange({ layout: "grid" })}
              className="h-9 text-xs flex flex-col gap-1"
            >
              <LayoutGrid className="h-4 w-4" />
              <span>그리드</span>
            </Button>
          </div>
        </div>

        {/* 그리드 컬럼 수 (grid 레이아웃일 때만) */}
        {config.layout === "grid" && (
          <div className="space-y-1">
            <Label className="text-xs">그리드 컬럼 수</Label>
            <Select
              value={String(config.gridColumns || 2)}
              onValueChange={(value) => onChange({ gridColumns: Number(value) })}
            >
              <SelectTrigger className="h-8 text-xs">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="2">2열</SelectItem>
                <SelectItem value="3">3열</SelectItem>
                <SelectItem value="4">4열</SelectItem>
                <SelectItem value="5">5열</SelectItem>
                <SelectItem value="6">6열</SelectItem>
              </SelectContent>
            </Select>
          </div>
        )}

        {/* 간격 */}
        <div className="space-y-1">
          <Label className="text-xs">아이템 간격</Label>
          <Input
            value={config.gap || "16px"}
            onChange={(e) => onChange({ gap: e.target.value })}
            placeholder="16px"
            className="h-8 text-xs"
          />
        </div>
      </div>

      {/* 아이템 카드 설정 */}
      <div className="space-y-3">
        <div>
          <h3 className="text-sm font-semibold">아이템 카드 스타일</h3>
        </div>
        <hr className="border-border" />

        <div className="grid grid-cols-2 gap-2">
          <div className="space-y-1">
            <Label className="text-xs">배경색</Label>
            <Input
              type="color"
              value={config.backgroundColor || "#ffffff"}
              onChange={(e) => onChange({ backgroundColor: e.target.value })}
              className="h-8"
            />
          </div>

          <div className="space-y-1">
            <Label className="text-xs">모서리 둥글기</Label>
            <Input
              value={config.borderRadius || "8px"}
              onChange={(e) => onChange({ borderRadius: e.target.value })}
              placeholder="8px"
              className="h-8 text-xs"
            />
          </div>

          <div className="space-y-1">
            <Label className="text-xs">내부 패딩</Label>
            <Input
              value={config.padding || "16px"}
              onChange={(e) => onChange({ padding: e.target.value })}
              placeholder="16px"
              className="h-8 text-xs"
            />
          </div>

          <div className="space-y-1">
            <Label className="text-xs">아이템 높이</Label>
            <Input
              value={config.itemHeight || "auto"}
              onChange={(e) => onChange({ itemHeight: e.target.value })}
              placeholder="auto"
              className="h-8 text-xs"
            />
          </div>
        </div>

        <div className="flex flex-wrap items-center gap-4">
          <div className="flex items-center gap-2">
            <Checkbox
              id="showBorder"
              checked={config.showBorder ?? true}
              onCheckedChange={(checked) => onChange({ showBorder: checked as boolean })}
            />
            <Label htmlFor="showBorder" className="text-xs">
              테두리 표시
            </Label>
          </div>

          <div className="flex items-center gap-2">
            <Checkbox
              id="showShadow"
              checked={config.showShadow ?? false}
              onCheckedChange={(checked) => onChange({ showShadow: checked as boolean })}
            />
            <Label htmlFor="showShadow" className="text-xs">
              그림자 표시
            </Label>
          </div>
        </div>
      </div>

      {/* 아이템 제목/설명 설정 */}
      <div className="space-y-3">
        <div className="flex items-center gap-2">
          <Checkbox
            id="showItemTitle"
            checked={config.showItemTitle ?? false}
            onCheckedChange={(checked) => onChange({ showItemTitle: checked as boolean })}
          />
          <Label htmlFor="showItemTitle" className="text-sm font-semibold">
            아이템 제목/설명 표시
          </Label>
        </div>
        <hr className="border-border" />

        {config.showItemTitle && (
          <div className="space-y-3">
            {/* 제목 컬럼 선택 (Combobox) */}
            <div className="space-y-1">
              <Label className="text-xs font-medium">제목 컬럼</Label>
              <Popover open={titleColumnOpen} onOpenChange={setTitleColumnOpen}>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    role="combobox"
                    aria-expanded={titleColumnOpen}
                    className="h-8 w-full justify-between text-xs font-normal"
                    disabled={loadingColumns || availableColumns.length === 0}
                  >
                    {loadingColumns
                      ? "로딩 중..."
                      : config.titleColumn
                        ? availableColumns.find(c => c.columnName === config.titleColumn)?.displayName || config.titleColumn
                        : "제목 컬럼 선택..."}
                    <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-[280px] p-0" align="start">
                  <Command>
                    <CommandInput placeholder="컬럼 검색..." className="h-8 text-xs" />
                    <CommandList>
                      <CommandEmpty className="py-2 text-xs text-center">컬럼을 찾을 수 없습니다</CommandEmpty>
                      <CommandGroup>
                        <CommandItem
                          value="__none__"
                          onSelect={() => {
                            onChange({ titleColumn: "" });
                            setTitleColumnOpen(false);
                          }}
                          className="text-xs"
                        >
                          <Check className={cn("mr-2 h-3 w-3", !config.titleColumn ? "opacity-100" : "opacity-0")} />
                          선택 안함
                        </CommandItem>
                        {availableColumns.map((col) => (
                          <CommandItem
                            key={col.columnName}
                            value={col.columnName}
                            onSelect={() => {
                              onChange({ titleColumn: col.columnName });
                              setTitleColumnOpen(false);
                            }}
                            className="text-xs"
                          >
                            <Check className={cn("mr-2 h-3 w-3", config.titleColumn === col.columnName ? "opacity-100" : "opacity-0")} />
                            <div className="flex flex-col">
                              <span>{col.displayName || col.columnName}</span>
                              {col.displayName && col.displayName !== col.columnName && (
                                <span className="text-[10px] text-muted-foreground">{col.columnName}</span>
                              )}
                            </div>
                          </CommandItem>
                        ))}
                      </CommandGroup>
                    </CommandList>
                  </Command>
                </PopoverContent>
              </Popover>
              {config.titleColumn && (
                <p className="text-[10px] text-emerald-600">
                  각 아이템의 "{config.titleColumn}" 값이 제목으로 표시됩니다
                </p>
              )}
            </div>

            {/* 설명 컬럼 선택 (Combobox) */}
            <div className="space-y-1">
              <Label className="text-xs font-medium">설명 컬럼 (선택사항)</Label>
              <Popover open={descriptionColumnOpen} onOpenChange={setDescriptionColumnOpen}>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    role="combobox"
                    aria-expanded={descriptionColumnOpen}
                    className="h-8 w-full justify-between text-xs font-normal"
                    disabled={loadingColumns || availableColumns.length === 0}
                  >
                    {loadingColumns
                      ? "로딩 중..."
                      : config.descriptionColumn
                        ? availableColumns.find(c => c.columnName === config.descriptionColumn)?.displayName || config.descriptionColumn
                        : "설명 컬럼 선택..."}
                    <ChevronsUpDown className="ml-2 h-3 w-3 shrink-0 opacity-50" />
                  </Button>
                </PopoverTrigger>
                <PopoverContent className="w-[280px] p-0" align="start">
                  <Command>
                    <CommandInput placeholder="컬럼 검색..." className="h-8 text-xs" />
                    <CommandList>
                      <CommandEmpty className="py-2 text-xs text-center">컬럼을 찾을 수 없습니다</CommandEmpty>
                      <CommandGroup>
                        <CommandItem
                          value="__none__"
                          onSelect={() => {
                            onChange({ descriptionColumn: "" });
                            setDescriptionColumnOpen(false);
                          }}
                          className="text-xs"
                        >
                          <Check className={cn("mr-2 h-3 w-3", !config.descriptionColumn ? "opacity-100" : "opacity-0")} />
                          선택 안함
                        </CommandItem>
                        {availableColumns.map((col) => (
                          <CommandItem
                            key={col.columnName}
                            value={col.columnName}
                            onSelect={() => {
                              onChange({ descriptionColumn: col.columnName });
                              setDescriptionColumnOpen(false);
                            }}
                            className="text-xs"
                          >
                            <Check className={cn("mr-2 h-3 w-3", config.descriptionColumn === col.columnName ? "opacity-100" : "opacity-0")} />
                            <div className="flex flex-col">
                              <span>{col.displayName || col.columnName}</span>
                              {col.displayName && col.displayName !== col.columnName && (
                                <span className="text-[10px] text-muted-foreground">{col.columnName}</span>
                              )}
                            </div>
                          </CommandItem>
                        ))}
                      </CommandGroup>
                    </CommandList>
                  </Command>
                </PopoverContent>
              </Popover>
              {config.descriptionColumn && (
                <p className="text-[10px] text-emerald-600">
                  각 아이템의 "{config.descriptionColumn}" 값이 설명으로 표시됩니다
                </p>
              )}
            </div>

            {/* 제목 스타일 설정 */}
            <div className="space-y-2 pt-2 border-t">
              <Label className="text-[10px] text-slate-500">제목 스타일</Label>
              <div className="grid grid-cols-3 gap-2">
                <div className="space-y-1">
                  <Label className="text-[10px]">크기</Label>
                  <Select
                    value={config.titleFontSize || "14px"}
                    onValueChange={(value) => onChange({ titleFontSize: value })}
                  >
                    <SelectTrigger className="h-7 text-xs">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="12px">12px</SelectItem>
                      <SelectItem value="14px">14px</SelectItem>
                      <SelectItem value="16px">16px</SelectItem>
                      <SelectItem value="18px">18px</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-1">
                  <Label className="text-[10px]">색상</Label>
                  <Input
                    type="color"
                    value={config.titleColor || "#374151"}
                    onChange={(e) => onChange({ titleColor: e.target.value })}
                    className="h-7"
                  />
                </div>
                <div className="space-y-1">
                  <Label className="text-[10px]">굵기</Label>
                  <Select
                    value={config.titleFontWeight || "600"}
                    onValueChange={(value) => onChange({ titleFontWeight: value })}
                  >
                    <SelectTrigger className="h-7 text-xs">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="400">보통</SelectItem>
                      <SelectItem value="500">중간</SelectItem>
                      <SelectItem value="600">굵게</SelectItem>
                      <SelectItem value="700">아주 굵게</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>

            {/* 설명 스타일 설정 */}
            {config.descriptionColumn && (
              <div className="space-y-2">
                <Label className="text-[10px] text-slate-500">설명 스타일</Label>
                <div className="grid grid-cols-2 gap-2">
                  <div className="space-y-1">
                    <Label className="text-[10px]">크기</Label>
                    <Select
                      value={config.descriptionFontSize || "12px"}
                      onValueChange={(value) => onChange({ descriptionFontSize: value })}
                    >
                      <SelectTrigger className="h-7 text-xs">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="10px">10px</SelectItem>
                        <SelectItem value="12px">12px</SelectItem>
                        <SelectItem value="14px">14px</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-1">
                    <Label className="text-[10px]">색상</Label>
                    <Input
                      type="color"
                      value={config.descriptionColor || "#6b7280"}
                      onChange={(e) => onChange({ descriptionColor: e.target.value })}
                      className="h-7"
                    />
                  </div>
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      {/* 페이징 설정 */}
      <div className="space-y-3">
        <div className="flex items-center gap-2">
          <Checkbox
            id="usePaging"
            checked={config.usePaging ?? false}
            onCheckedChange={(checked) => onChange({ usePaging: checked as boolean })}
          />
          <Label htmlFor="usePaging" className="text-sm font-semibold">
            페이징 사용
          </Label>
        </div>
        <hr className="border-border" />

        {config.usePaging && (
          <div className="space-y-1">
            <Label className="text-xs">페이지당 아이템 수</Label>
            <Select
              value={String(config.pageSize || 10)}
              onValueChange={(value) => onChange({ pageSize: Number(value) })}
            >
              <SelectTrigger className="h-8 text-xs">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="5">5개</SelectItem>
                <SelectItem value="10">10개</SelectItem>
                <SelectItem value="20">20개</SelectItem>
                <SelectItem value="50">50개</SelectItem>
              </SelectContent>
            </Select>
          </div>
        )}
      </div>

      {/* 상호작용 설정 */}
      <div className="space-y-3">
        <div>
          <h3 className="text-sm font-semibold">상호작용</h3>
        </div>
        <hr className="border-border" />

        <div className="flex flex-wrap items-center gap-4">
          <div className="flex items-center gap-2">
            <Checkbox
              id="clickable"
              checked={config.clickable ?? false}
              onCheckedChange={(checked) => onChange({ clickable: checked as boolean })}
            />
            <Label htmlFor="clickable" className="text-xs">
              클릭 가능
            </Label>
          </div>

          {config.clickable && (
            <>
              <div className="flex items-center gap-2">
                <Checkbox
                  id="showSelectedState"
                  checked={config.showSelectedState ?? true}
                  onCheckedChange={(checked) => onChange({ showSelectedState: checked as boolean })}
                />
                <Label htmlFor="showSelectedState" className="text-xs">
                  선택 상태 표시
                </Label>
              </div>

              <div className="space-y-1">
                <Label className="text-[10px]">선택 모드</Label>
                <Select
                  value={config.selectionMode || "single"}
                  onValueChange={(value) =>
                    onChange({ selectionMode: value as "single" | "multiple" })
                  }
                >
                  <SelectTrigger className="h-7 text-xs w-24">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="single">단일</SelectItem>
                    <SelectItem value="multiple">다중</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </>
          )}
        </div>
      </div>

      {/* 빈 상태 설정 */}
      <div className="space-y-3">
        <div>
          <h3 className="text-sm font-semibold">빈 상태 메시지</h3>
        </div>
        <hr className="border-border" />

        <div className="space-y-1">
          <Label className="text-xs">메시지</Label>
          <Input
            value={config.emptyMessage || "데이터가 없습니다"}
            onChange={(e) => onChange({ emptyMessage: e.target.value })}
            placeholder="데이터가 없습니다"
            className="h-8 text-xs"
          />
        </div>
      </div>
    </div>
  );
}

// ============================================================
// 슬롯 자식 컴포넌트 관리 섹션
// ============================================================

interface SlotChildrenSectionProps {
  config: RepeatContainerConfig;
  onChange: (config: Partial<RepeatContainerConfig>) => void;
  availableColumns: Array<{ columnName: string; displayName?: string }>;
  loadingColumns: boolean;
  screenTableName?: string;
}

function SlotChildrenSection({
  config,
  onChange,
  availableColumns,
  loadingColumns,
  screenTableName,
}: SlotChildrenSectionProps) {
  const [columnComboboxOpen, setColumnComboboxOpen] = useState(false);
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());

  const children = config.children || [];

  const toggleExpanded = (id: string) => {
    setExpandedIds((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  };

  const addComponent = (columnName: string, displayName: string) => {
    const newChild: SlotComponentConfig = {
      id: `slot_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      componentType: "text-display",
      label: displayName,
      fieldName: columnName,
      position: { x: 0, y: children.length * 40 },
      size: { width: 200, height: 32 },
      componentConfig: {},
      style: {},
    };

    onChange({
      children: [...children, newChild],
    });
    setColumnComboboxOpen(false);
  };

  const removeComponent = (id: string) => {
    onChange({
      children: children.filter((c) => c.id !== id),
    });
    setExpandedIds((prev) => {
      const newSet = new Set(prev);
      newSet.delete(id);
      return newSet;
    });
  };

  const updateComponentLabel = (id: string, label: string) => {
    onChange({
      children: children.map((c) => (c.id === id ? { ...c, label } : c)),
    });
  };

  const updateComponentConfig = (id: string, key: string, value: any) => {
    onChange({
      children: children.map((c) =>
        c.id === id
          ? { ...c, componentConfig: { ...c.componentConfig, [key]: value } }
          : c
      ),
    });
  };

  const updateComponentStyle = (id: string, key: string, value: any) => {
    onChange({
      children: children.map((c) =>
        c.id === id
          ? { ...c, style: { ...c.style, [key]: value } }
          : c
      ),
    });
  };

  const updateComponentSize = (id: string, width: number | undefined, height: number | undefined) => {
    onChange({
      children: children.map((c) =>
        c.id === id
          ? { ...c, size: { width: width ?? c.size?.width ?? 200, height: height ?? c.size?.height ?? 32 } }
          : c
      ),
    });
  };

  return (
    <div className="space-y-3">
      <div>
        <h3 className="text-sm font-semibold">반복 표시 필드</h3>
        <p className="text-muted-foreground text-[10px]">
          데이터 테이블의 컬럼을 선택하여 각 행에 표시할 필드를 추가합니다
        </p>
      </div>
      <hr className="border-border" />

      {/* 추가된 필드 목록 */}
      {children.length > 0 ? (
        <div className="space-y-2">
          {children.map((child, index) => {
            const isExpanded = expandedIds.has(child.id);
            return (
              <div
                key={child.id}
                className="rounded-md border border-emerald-200 bg-emerald-50 overflow-hidden"
              >
                {/* 기본 정보 헤더 - 타입 선택 드롭다운 제거됨 */}
                <div className="flex items-center gap-2 p-2">
                  <div className="flex h-5 w-5 items-center justify-center rounded bg-emerald-200 text-xs font-medium text-emerald-700">
                    {index + 1}
                  </div>
                  <div className="flex-1">
                    <div className="text-xs font-medium text-emerald-700">
                      {child.label || child.fieldName}
                    </div>
                    <div className="text-[10px] text-emerald-500">
                      필드: {child.fieldName}
                    </div>
                  </div>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-5 w-5 p-0 text-primary hover:text-primary"
                    onClick={() => toggleExpanded(child.id)}
                    title="상세 설정"
                  >
                    {isExpanded ? (
                      <ChevronUp className="h-3 w-3" />
                    ) : (
                      <Settings2 className="h-3 w-3" />
                    )}
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-5 w-5 p-0 text-destructive/80 hover:text-destructive"
                    onClick={() => removeComponent(child.id)}
                  >
                    <X className="h-3 w-3" />
                  </Button>
                </div>

                {/* 상세 설정 패널 */}
                {isExpanded && (
                  <div className="border-t border-emerald-200 bg-white p-3 space-y-3">
                    {hasComponentConfigPanel(child.componentType) ? (
                      <SlotComponentDetailPanel
                        child={child}
                        screenTableName={screenTableName}
                        onConfigChange={(newConfig) => {
                          onChange({
                            children: children.map((c) =>
                              c.id === child.id
                                ? { ...c, componentConfig: { ...c.componentConfig, ...newConfig } }
                                : c
                            ),
                          });
                        }}
                        onLabelChange={(label) => updateComponentLabel(child.id, label)}
                      />
                    ) : (
                      <>
                        {child.fieldName && (
                          <div className="p-2 bg-emerald-50 rounded-md border border-emerald-200">
                            <div className="flex items-center gap-1.5">
                              <Database className="h-3 w-3 text-emerald-600" />
                              <span className="text-[10px] text-emerald-700 font-medium">
                                바인딩: {child.fieldName}
                              </span>
                            </div>
                            <p className="text-[9px] text-emerald-600 mt-0.5">
                              각 아이템의 "{child.fieldName}" 값이 자동으로 표시됩니다
                            </p>
                          </div>
                        )}

                        <div className="space-y-1">
                          <Label className="text-[10px] text-slate-500">표시 라벨</Label>
                          <Input
                            value={child.label || ""}
                            onChange={(e) => updateComponentLabel(child.id, e.target.value)}
                            placeholder="표시할 라벨"
                            className="h-7 text-xs"
                          />
                        </div>

                        <div className="grid grid-cols-2 gap-2">
                          <div className="space-y-1">
                            <Label className="text-[10px] text-slate-500">너비 (px)</Label>
                            <Input
                              type="number"
                              value={child.size?.width || 200}
                              onChange={(e) =>
                                updateComponentSize(child.id, parseInt(e.target.value) || 200, undefined)
                              }
                              className="h-7 text-xs"
                            />
                          </div>
                          <div className="space-y-1">
                            <Label className="text-[10px] text-slate-500">높이 (px)</Label>
                            <Input
                              type="number"
                              value={child.size?.height || 32}
                              onChange={(e) =>
                                updateComponentSize(child.id, undefined, parseInt(e.target.value) || 32)
                              }
                              className="h-7 text-xs"
                            />
                          </div>
                        </div>

                        <div className="space-y-2">
                          <Label className="text-[10px] text-slate-500 font-medium">스타일</Label>
                          <div className="grid grid-cols-2 gap-2">
                            <div className="space-y-1">
                              <Label className="text-[10px] text-slate-400">글자 크기</Label>
                              <Select
                                value={child.style?.fontSize || "14px"}
                                onValueChange={(value) => updateComponentStyle(child.id, "fontSize", value)}
                              >
                                <SelectTrigger className="h-7 text-xs">
                                  <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="10px">10px</SelectItem>
                                  <SelectItem value="12px">12px</SelectItem>
                                  <SelectItem value="14px">14px</SelectItem>
                                  <SelectItem value="16px">16px</SelectItem>
                                  <SelectItem value="18px">18px</SelectItem>
                                </SelectContent>
                              </Select>
                            </div>
                            <div className="space-y-1">
                              <Label className="text-[10px] text-slate-400">글자 색상</Label>
                              <Input
                                type="color"
                                value={child.style?.color || "#000000"}
                                onChange={(e) => updateComponentStyle(child.id, "color", e.target.value)}
                                className="h-7"
                              />
                            </div>
                          </div>
                        </div>
                      </>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      ) : (
        <div className="rounded-md border border-dashed border-slate-300 bg-slate-50 p-4 text-center">
          <Type className="mx-auto h-6 w-6 text-slate-300" />
          <div className="mt-2 text-xs text-slate-500">표시할 필드가 없습니다</div>
          <div className="text-[10px] text-muted-foreground">
            아래 컬럼 목록에서 선택하세요
          </div>
        </div>
      )}

      {/* 컬럼 선택 Combobox */}
      <div className="space-y-2">
        <Label className="text-xs">컬럼 추가</Label>
        <Popover open={columnComboboxOpen} onOpenChange={setColumnComboboxOpen}>
          <PopoverTrigger asChild>
            <Button
              variant="outline"
              role="combobox"
              aria-expanded={columnComboboxOpen}
              className="h-8 w-full justify-between text-xs"
              disabled={loadingColumns || availableColumns.length === 0}
            >
              {loadingColumns
                ? "로딩 중..."
                : availableColumns.length === 0
                  ? "테이블을 먼저 선택하세요"
                  : "컬럼 선택..."}
              <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
            </Button>
          </PopoverTrigger>
          <PopoverContent className="w-full p-0" align="start">
            <Command>
              <CommandInput placeholder="컬럼 검색..." className="h-8 text-xs" />
              <CommandList>
                <CommandEmpty className="py-2 text-xs">컬럼을 찾을 수 없습니다</CommandEmpty>
                <CommandGroup heading="사용 가능한 컬럼">
                  {availableColumns.map((col) => {
                    const isAdded = children.some((c) => c.fieldName === col.columnName);
                    return (
                      <CommandItem
                        key={col.columnName}
                        value={`${col.columnName} ${col.displayName || ""}`}
                        onSelect={() => {
                          if (!isAdded) {
                            addComponent(col.columnName, col.displayName || col.columnName);
                          }
                        }}
                        disabled={isAdded}
                        className={cn(
                          "text-xs cursor-pointer",
                          isAdded && "opacity-50 cursor-not-allowed"
                        )}
                      >
                        <Plus
                          className={cn(
                            "mr-2 h-3 w-3",
                            isAdded ? "text-emerald-500" : "text-primary"
                          )}
                        />
                        <div className="flex-1">
                          <div className="font-medium">{col.displayName || col.columnName}</div>
                          <div className="text-[10px] text-muted-foreground">
                            {col.columnName}
                          </div>
                        </div>
                        {isAdded && (
                          <Check className="h-3 w-3 text-emerald-500" />
                        )}
                      </CommandItem>
                    );
                  })}
                </CommandGroup>
              </CommandList>
            </Command>
          </PopoverContent>
        </Popover>
      </div>
    </div>
  );
}

// 슬롯 컴포넌트 상세 설정 패널
interface SlotComponentDetailPanelProps {
  child: SlotComponentConfig;
  screenTableName?: string;
  onConfigChange: (newConfig: Record<string, any>) => void;
  onLabelChange: (label: string) => void;
}

function SlotComponentDetailPanel({
  child,
  screenTableName,
  onConfigChange,
  onLabelChange,
}: SlotComponentDetailPanelProps) {
  return (
    <div className="space-y-3">
      {child.fieldName && (
        <div className="p-2 bg-emerald-50 rounded-md border border-emerald-200">
          <div className="flex items-center gap-1.5">
            <Database className="h-3 w-3 text-emerald-600" />
            <span className="text-[10px] text-emerald-700 font-medium">
              바인딩: {child.fieldName}
            </span>
          </div>
          <p className="text-[9px] text-emerald-600 mt-0.5">
            각 아이템의 "{child.fieldName}" 값이 자동으로 표시됩니다
          </p>
        </div>
      )}

      <div className="space-y-1">
        <Label className="text-[10px] text-slate-500">표시 라벨</Label>
        <Input
          value={child.label || ""}
          onChange={(e) => onLabelChange(e.target.value)}
          placeholder="표시할 라벨"
          className="h-7 text-xs"
        />
      </div>

      <div className="border-t pt-2">
        <div className="text-[10px] font-medium text-slate-600 mb-2">
          {child.componentType} 상세 설정
        </div>
        <DynamicComponentConfigPanel
          componentId={child.componentType}
          config={child.componentConfig || {}}
          onChange={onConfigChange}
          screenTableName={screenTableName}
        />
      </div>
    </div>
  );
}
