"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 { Checkbox } from "@/components/ui/checkbox";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { Settings, Layout, ArrowRight, Database, Loader2, Check, ChevronsUpDown, Plus, Trash2, Link2 } from "lucide-react";
import { screenApi } from "@/lib/api/screen";
import { getTableColumns } from "@/lib/api/tableManagement";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import type { ParentDataMapping, LinkedFilter } from "@/contexts/SplitPanelContext";

interface ScreenSplitPanelConfigPanelProps {
  config: any;
  onChange: (newConfig: any) => void;
}

export function ScreenSplitPanelConfigPanel({ config = {}, onChange }: ScreenSplitPanelConfigPanelProps) {
  // 화면 목록 상태
  const [screens, setScreens] = useState<any[]>([]);
  const [isLoadingScreens, setIsLoadingScreens] = useState(true);

  // Combobox 상태
  const [leftOpen, setLeftOpen] = useState(false);
  const [rightOpen, setRightOpen] = useState(false);

  // 좌측 화면의 테이블 컬럼 목록
  const [leftScreenColumns, setLeftScreenColumns] = useState<Array<{ columnName: string; columnLabel: string }>>([]);
  const [isLoadingLeftColumns, setIsLoadingLeftColumns] = useState(false);

  // 우측 화면의 테이블 컬럼 목록 (테이블별로 그룹화)
  const [rightScreenTables, setRightScreenTables] = useState<Array<{ 
    tableName: string; 
    screenName: string;
    columns: Array<{ columnName: string; columnLabel: string }> 
  }>>([]);
  const [isLoadingRightColumns, setIsLoadingRightColumns] = useState(false);

  const [localConfig, setLocalConfig] = useState({
    screenId: config.screenId || 0,
    leftScreenId: config.leftScreenId || 0,
    rightScreenId: config.rightScreenId || 0,
    splitRatio: config.splitRatio || 50,
    resizable: config.resizable ?? true,
    buttonLabel: config.buttonLabel || "데이터 전달",
    buttonPosition: config.buttonPosition || "center",
    parentDataMapping: config.parentDataMapping || [] as ParentDataMapping[],
    linkedFilters: config.linkedFilters || [] as LinkedFilter[],
    disableAutoDataTransfer: config.disableAutoDataTransfer ?? false,  // 자동 데이터 전달 비활성화
    ...config,
  });

  // config prop이 변경되면 localConfig 동기화
  useEffect(() => {
    console.log("🔄 [ScreenSplitPanelConfigPanel] config prop 변경 감지:", config);
    setLocalConfig({
      screenId: config.screenId || 0,
      leftScreenId: config.leftScreenId || 0,
      rightScreenId: config.rightScreenId || 0,
      splitRatio: config.splitRatio || 50,
      resizable: config.resizable ?? true,
      buttonLabel: config.buttonLabel || "데이터 전달",
      buttonPosition: config.buttonPosition || "center",
      parentDataMapping: config.parentDataMapping || [],
      linkedFilters: config.linkedFilters || [],
      disableAutoDataTransfer: config.disableAutoDataTransfer ?? false,
      ...config,
    });
  }, [config]);

  // 좌측 화면이 변경되면 해당 화면의 테이블 컬럼 로드
  useEffect(() => {
    const loadLeftScreenColumns = async () => {
      if (!localConfig.leftScreenId) {
        setLeftScreenColumns([]);
        return;
      }

      try {
        setIsLoadingLeftColumns(true);
        
        // 좌측 화면 정보 조회
        const screenData = await screenApi.getScreen(localConfig.leftScreenId);
        if (!screenData?.tableName) {
          console.warn("좌측 화면에 테이블이 설정되지 않았습니다.");
          setLeftScreenColumns([]);
          return;
        }

        // 테이블 컬럼 조회
        const columnsResponse = await getTableColumns(screenData.tableName);
        if (columnsResponse.success && columnsResponse.data?.columns) {
          const columns = columnsResponse.data.columns.map((col: any) => ({
            columnName: col.column_name || col.columnName,
            columnLabel: col.column_label || col.columnLabel || col.column_name || col.columnName,
          }));
          setLeftScreenColumns(columns);
          console.log("📋 좌측 화면 컬럼 로드 완료:", columns.length);
        }
      } catch (error) {
        console.error("좌측 화면 컬럼 로드 실패:", error);
        setLeftScreenColumns([]);
      } finally {
        setIsLoadingLeftColumns(false);
      }
    };

    loadLeftScreenColumns();
  }, [localConfig.leftScreenId]);

  // 우측 화면이 변경되면 해당 화면 및 임베드된 화면들의 테이블 컬럼 로드
  useEffect(() => {
    const loadRightScreenColumns = async () => {
      if (!localConfig.rightScreenId) {
        setRightScreenTables([]);
        return;
      }

      try {
        setIsLoadingRightColumns(true);
        const tables: Array<{ tableName: string; screenName: string; columns: Array<{ columnName: string; columnLabel: string }> }> = [];
        
        // 우측 화면 정보 조회
        const screenData = await screenApi.getScreen(localConfig.rightScreenId);
        
        // 1. 메인 화면의 테이블 (있는 경우)
        if (screenData?.tableName) {
          const columnsResponse = await getTableColumns(screenData.tableName);
          if (columnsResponse.success && columnsResponse.data?.columns) {
            tables.push({
              tableName: screenData.tableName,
              screenName: screenData.screenName || "메인 화면",
              columns: columnsResponse.data.columns.map((col: any) => ({
                columnName: col.column_name || col.columnName,
                columnLabel: col.column_label || col.columnLabel || col.column_name || col.columnName,
              })),
            });
          }
        }

        // 2. 레이아웃에서 임베드된 화면들의 테이블 찾기 (탭, 분할 패널 등)
        const layoutData = await screenApi.getLayout(localConfig.rightScreenId);
        const components = layoutData?.components || [];
        
        if (components.length > 0) {
          const embeddedScreenIds = new Set<number>();
          
          // 컴포넌트에서 임베드된 화면 ID 수집
          const findEmbeddedScreens = (comps: any[]) => {
            for (const comp of comps) {
              const config = comp.componentConfig || {};
              
              // TabsWidget의 탭들
              if (comp.componentType === "tabs-widget" && config.tabs) {
                for (const tab of config.tabs) {
                  if (tab.screenId) {
                    embeddedScreenIds.add(tab.screenId);
                    console.log("🔍 탭에서 화면 발견:", tab.screenId, tab.screenName);
                  }
                }
              }
              
              // ScreenSplitPanel
              if (comp.componentType === "screen-split-panel") {
                if (config.leftScreenId) embeddedScreenIds.add(config.leftScreenId);
                if (config.rightScreenId) embeddedScreenIds.add(config.rightScreenId);
              }
              
              // EmbeddedScreen
              if (comp.componentType === "embedded-screen" && config.screenId) {
                embeddedScreenIds.add(config.screenId);
              }
              
              // 중첩된 컴포넌트 검색
              if (comp.children) {
                findEmbeddedScreens(comp.children);
              }
            }
          };
          
          findEmbeddedScreens(components);
          console.log("📋 발견된 임베드 화면 ID:", Array.from(embeddedScreenIds));
          
          // 임베드된 화면들의 테이블 컬럼 로드
          for (const embeddedScreenId of embeddedScreenIds) {
            try {
              const embeddedScreen = await screenApi.getScreen(embeddedScreenId);
              if (embeddedScreen?.tableName) {
                // 이미 추가된 테이블인지 확인
                if (!tables.find(t => t.tableName === embeddedScreen.tableName)) {
                  const columnsResponse = await getTableColumns(embeddedScreen.tableName);
                  if (columnsResponse.success && columnsResponse.data?.columns) {
                    tables.push({
                      tableName: embeddedScreen.tableName,
                      screenName: embeddedScreen.screenName || `화면 ${embeddedScreenId}`,
                      columns: columnsResponse.data.columns.map((col: any) => ({
                        columnName: col.column_name || col.columnName,
                        columnLabel: col.column_label || col.columnLabel || col.column_name || col.columnName,
                      })),
                    });
                    console.log("✅ 테이블 추가:", embeddedScreen.tableName);
                  }
                }
              }
            } catch (err) {
              console.warn(`임베드된 화면 ${embeddedScreenId} 로드 실패:`, err);
            }
          }
        }

        setRightScreenTables(tables);
        console.log("📋 우측 화면 테이블 로드 완료:", tables.map(t => t.tableName));
      } catch (error) {
        console.error("우측 화면 컬럼 로드 실패:", error);
        setRightScreenTables([]);
      } finally {
        setIsLoadingRightColumns(false);
      }
    };

    loadRightScreenColumns();
  }, [localConfig.rightScreenId]);

  // 화면 목록 로드
  useEffect(() => {
    const loadScreens = async () => {
      try {
        setIsLoadingScreens(true);
        const response = await screenApi.getScreens({ page: 1, size: 1000 });
        if (response.data) {
          setScreens(response.data);
        }
      } catch (error) {
        console.error("화면 목록 로드 실패:", error);
      } finally {
        setIsLoadingScreens(false);
      }
    };

    loadScreens();
  }, []);

  const updateConfig = (key: string, value: any) => {
    const newConfig = {
      ...localConfig,
      [key]: value,
    };
    setLocalConfig(newConfig);

    console.log("📝 [ScreenSplitPanelConfigPanel] 설정 변경:", {
      key,
      value,
      newConfig,
      hasOnChange: !!onChange,
    });

    // 변경 즉시 부모에게 전달
    if (onChange) {
      onChange(newConfig);
    }
  };

  // 부모 데이터 매핑 추가
  const addParentDataMapping = () => {
    const newMapping: ParentDataMapping = {
      sourceColumn: "",
      targetColumn: "",
    };
    const newMappings = [...(localConfig.parentDataMapping || []), newMapping];
    updateConfig("parentDataMapping", newMappings);
  };

  // 부모 데이터 매핑 수정
  const updateParentDataMapping = (index: number, field: keyof ParentDataMapping, value: string) => {
    const newMappings = [...(localConfig.parentDataMapping || [])];
    newMappings[index] = {
      ...newMappings[index],
      [field]: value,
    };
    updateConfig("parentDataMapping", newMappings);
  };

  // 부모 데이터 매핑 삭제
  const removeParentDataMapping = (index: number) => {
    const newMappings = (localConfig.parentDataMapping || []).filter((_: any, i: number) => i !== index);
    updateConfig("parentDataMapping", newMappings);
  };

  // 연결 필터 추가
  const addLinkedFilter = () => {
    const newFilter: LinkedFilter = {
      sourceColumn: "",
      targetColumn: "",
    };
    const newFilters = [...(localConfig.linkedFilters || []), newFilter];
    updateConfig("linkedFilters", newFilters);
  };

  // 연결 필터 수정
  const updateLinkedFilter = (index: number, field: keyof LinkedFilter, value: string) => {
    const newFilters = [...(localConfig.linkedFilters || [])];
    newFilters[index] = {
      ...newFilters[index],
      [field]: value,
    };
    updateConfig("linkedFilters", newFilters);
  };

  // 연결 필터 삭제
  const removeLinkedFilter = (index: number) => {
    const newFilters = (localConfig.linkedFilters || []).filter((_: any, i: number) => i !== index);
    updateConfig("linkedFilters", newFilters);
  };

  return (
    <div className="space-y-4">
      <Tabs defaultValue="layout" className="w-full">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="layout" className="gap-1 text-xs">
            <Layout className="h-3 w-3" />
            레이아웃
          </TabsTrigger>
          <TabsTrigger value="screens" className="gap-1 text-xs">
            <Database className="h-3 w-3" />
            화면
          </TabsTrigger>
          <TabsTrigger value="linkedFilter" className="gap-1 text-xs">
            <Link2 className="h-3 w-3" />
            연결필터
          </TabsTrigger>
          <TabsTrigger value="dataMapping" className="gap-1 text-xs">
            <ArrowRight className="h-3 w-3" />
            데이터전달
          </TabsTrigger>
        </TabsList>

        {/* 레이아웃 탭 */}
        <TabsContent value="layout" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">분할 비율</CardTitle>
              <CardDescription className="text-xs">좌측과 우측 패널의 너비 비율을 설정합니다</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <Label htmlFor="splitRatio" className="text-xs">
                    좌측 패널 너비 (%)
                  </Label>
                  <span className="text-xs font-medium">{localConfig.splitRatio}%</span>
                </div>
                <Input
                  id="splitRatio"
                  type="range"
                  min="20"
                  max="80"
                  step="5"
                  value={localConfig.splitRatio}
                  onChange={(e) => updateConfig("splitRatio", parseInt(e.target.value))}
                  className="h-2"
                />
                <div className="text-muted-foreground flex justify-between text-xs">
                  <span>20%</span>
                  <span>50%</span>
                  <span>80%</span>
                </div>
              </div>

              <Separator />

              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <Label htmlFor="resizable" className="text-xs font-medium">
                    크기 조절 가능
                  </Label>
                  <p className="text-muted-foreground text-xs">사용자가 패널 크기를 조절할 수 있습니다</p>
                </div>
                <Checkbox
                  id="resizable"
                  checked={localConfig.resizable}
                  onCheckedChange={(checked) => updateConfig("resizable", checked)}
                />
              </div>

              <Separator />

              <div className="flex items-center justify-between">
                <div className="space-y-0.5">
                  <Label htmlFor="disableAutoDataTransfer" className="text-xs font-medium">
                    자동 데이터 전달 비활성화
                  </Label>
                  <p className="text-muted-foreground text-xs">
                    좌측 행 선택 시 우측으로 데이터가 자동 전달되지 않습니다.
                    <br />
                    버튼 클릭으로만 데이터를 전달하려면 활성화하세요.
                  </p>
                </div>
                <Checkbox
                  id="disableAutoDataTransfer"
                  checked={localConfig.disableAutoDataTransfer}
                  onCheckedChange={(checked) => updateConfig("disableAutoDataTransfer", checked)}
                />
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 화면 설정 탭 */}
        <TabsContent value="screens" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">임베드할 화면 선택</CardTitle>
              <CardDescription className="text-xs">좌측과 우측에 표시할 화면을 선택합니다</CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {isLoadingScreens ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 className="text-muted-foreground h-6 w-6 animate-spin" />
                  <span className="text-muted-foreground ml-2 text-xs">화면 목록 로딩 중...</span>
                </div>
              ) : (
                <>
                  <div className="space-y-2">
                    <Label htmlFor="leftScreenId" className="text-xs">
                      좌측 화면 (소스)
                    </Label>
                    <Popover open={leftOpen} onOpenChange={setLeftOpen}>
                      <PopoverTrigger asChild>
                        <Button
                          variant="outline"
                          role="combobox"
                          aria-expanded={leftOpen}
                          className="h-9 w-full justify-between text-xs"
                        >
                          {localConfig.leftScreenId
                            ? screens.find((s) => s.screenId === localConfig.leftScreenId)?.screenName || "화면 선택..."
                            : "화면 선택..."}
                          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                        </Button>
                      </PopoverTrigger>
                      <PopoverContent
                        className="p-0"
                        style={{ width: "var(--radix-popover-trigger-width)" }}
                        align="start"
                      >
                        <Command>
                          <CommandInput placeholder="화면 검색..." className="text-xs" />
                          <CommandList>
                            <CommandEmpty className="text-xs">화면을 찾을 수 없습니다.</CommandEmpty>
                            <CommandGroup>
                              {screens.map((screen) => (
                                <CommandItem
                                  key={screen.screenId}
                                  value={`${screen.screenName} ${screen.screenCode}`}
                                  onSelect={() => {
                                    updateConfig("leftScreenId", screen.screenId);
                                    setLeftOpen(false);
                                  }}
                                  className="text-xs"
                                >
                                  <Check
                                    className={cn(
                                      "mr-2 h-4 w-4",
                                      localConfig.leftScreenId === screen.screenId ? "opacity-100" : "opacity-0",
                                    )}
                                  />
                                  <div className="flex flex-col">
                                    <span className="font-medium">{screen.screenName}</span>
                                    <span className="text-[10px] text-muted-foreground">{screen.screenCode}</span>
                                  </div>
                                </CommandItem>
                              ))}
                            </CommandGroup>
                          </CommandList>
                        </Command>
                      </PopoverContent>
                    </Popover>
                    <p className="text-muted-foreground text-xs">데이터를 선택할 소스 화면</p>
                  </div>

                  <Separator />

                  <div className="space-y-2">
                    <Label htmlFor="rightScreenId" className="text-xs">
                      우측 화면 (타겟)
                    </Label>
                    <Popover open={rightOpen} onOpenChange={setRightOpen}>
                      <PopoverTrigger asChild>
                        <Button
                          variant="outline"
                          role="combobox"
                          aria-expanded={rightOpen}
                          className="h-9 w-full justify-between text-xs"
                        >
                          {localConfig.rightScreenId
                            ? screens.find((s) => s.screenId === localConfig.rightScreenId)?.screenName ||
                              "화면 선택..."
                            : "화면 선택..."}
                          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                        </Button>
                      </PopoverTrigger>
                      <PopoverContent
                        className="p-0"
                        style={{ width: "var(--radix-popover-trigger-width)" }}
                        align="start"
                      >
                        <Command>
                          <CommandInput placeholder="화면 검색..." className="text-xs" />
                          <CommandList>
                            <CommandEmpty className="text-xs">화면을 찾을 수 없습니다.</CommandEmpty>
                            <CommandGroup>
                              {screens.map((screen) => (
                                <CommandItem
                                  key={screen.screenId}
                                  value={`${screen.screenName} ${screen.screenCode}`}
                                  onSelect={() => {
                                    updateConfig("rightScreenId", screen.screenId);
                                    setRightOpen(false);
                                  }}
                                  className="text-xs"
                                >
                                  <Check
                                    className={cn(
                                      "mr-2 h-4 w-4",
                                      localConfig.rightScreenId === screen.screenId ? "opacity-100" : "opacity-0",
                                    )}
                                  />
                                  <div className="flex flex-col">
                                    <span className="font-medium">{screen.screenName}</span>
                                    <span className="text-[10px] text-muted-foreground">{screen.screenCode}</span>
                                  </div>
                                </CommandItem>
                              ))}
                            </CommandGroup>
                          </CommandList>
                        </Command>
                      </PopoverContent>
                    </Popover>
                    <p className="text-muted-foreground text-xs">데이터를 받을 타겟 화면</p>
                  </div>

                  <div className="rounded-lg border border-amber-200 bg-amber-50 p-3 dark:border-amber-900 dark:bg-amber-950">
                    <p className="text-xs text-amber-800 dark:text-amber-200">
                      데이터 전달 방법: 좌측 화면에 테이블과 버튼을 배치하고, 버튼의 액션을
                      "transferData"로 설정하세요.
                      <br />
                      버튼 설정에서 소스 컴포넌트(테이블), 타겟 화면, 필드 매핑을 지정할 수 있습니다.
                    </p>
                  </div>
                </>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* 연결 필터 탭 */}
        <TabsContent value="linkedFilter" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">연결 필터</CardTitle>
              <CardDescription className="text-xs">
                좌측 화면에서 행을 선택하면, 우측 화면의 테이블이 자동으로 필터링됩니다.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {!localConfig.leftScreenId || !localConfig.rightScreenId ? (
                <div className="rounded-lg border border-amber-200 bg-amber-50 p-3 dark:border-amber-900 dark:bg-amber-950">
                  <p className="text-xs text-amber-800 dark:text-amber-200">
                    먼저 "화면" 탭에서 좌측/우측 화면을 모두 선택하세요.
                  </p>
                </div>
              ) : isLoadingLeftColumns || isLoadingRightColumns ? (
                <div className="flex items-center justify-center py-4">
                  <Loader2 className="text-muted-foreground h-5 w-5 animate-spin" />
                  <span className="text-muted-foreground ml-2 text-xs">컬럼 정보 로딩 중...</span>
                </div>
              ) : leftScreenColumns.length === 0 || rightScreenTables.length === 0 ? (
                <div className="rounded-lg border border-amber-200 bg-amber-50 p-3 dark:border-amber-900 dark:bg-amber-950">
                  <p className="text-xs text-amber-800 dark:text-amber-200">
                    {leftScreenColumns.length === 0 && "좌측 화면에 테이블이 설정되지 않았습니다. "}
                    {rightScreenTables.length === 0 && "우측 화면에 테이블이 설정되지 않았습니다."}
                  </p>
                </div>
              ) : (
                <>
                  {/* 연결 필터 설명 */}
                  <div className="rounded-lg border border-primary/20 bg-primary/10 p-3 dark:border-primary/20 dark:bg-primary/15">
                    <p className="text-xs text-primary dark:text-primary/70">
                      예: 좌측에서 설비를 선택하면 → 우측 점검항목이 해당 설비의 항목만 표시됩니다.
                      <br />
                      좌측 <code className="bg-primary/10 dark:bg-primary/20 px-1 rounded">equipment_code</code> → 
                      우측 <code className="bg-primary/10 dark:bg-primary/20 px-1 rounded">equipment_code</code>
                    </p>
                  </div>

                  {/* 필터 목록 */}
                  <div className="space-y-3">
                    {(localConfig.linkedFilters || []).map((filter: LinkedFilter, index: number) => (
                      <div key={index} className="rounded-lg border bg-muted p-3 dark:bg-foreground">
                        <div className="mb-2 flex items-center justify-between">
                          <span className="text-xs font-medium text-foreground">필터 #{index + 1}</span>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => removeLinkedFilter(index)}
                            className="h-6 w-6 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive"
                          >
                            <Trash2 className="h-3 w-3" />
                          </Button>
                        </div>
                        <div className="space-y-2">
                          <div>
                            <Label className="text-xs text-muted-foreground">소스 컬럼 (좌측 화면)</Label>
                            <Select
                              value={filter.sourceColumn}
                              onValueChange={(value) => updateLinkedFilter(index, "sourceColumn", value)}
                            >
                              <SelectTrigger className="h-8 text-xs">
                                <SelectValue placeholder="컬럼 선택" />
                              </SelectTrigger>
                              <SelectContent>
                                {leftScreenColumns.map((col) => (
                                  <SelectItem key={col.columnName} value={col.columnName} className="text-xs">
                                    {col.columnLabel} ({col.columnName})
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>
                          <div className="flex justify-center">
                            <ArrowRight className="h-4 w-4 rotate-90 text-muted-foreground/70" />
                          </div>
                          <div>
                            <Label className="text-xs text-muted-foreground">타겟 컬럼 (우측 화면 필터)</Label>
                            <Select
                              value={filter.targetColumn}
                              onValueChange={(value) => updateLinkedFilter(index, "targetColumn", value)}
                            >
                              <SelectTrigger className="h-8 text-xs">
                                <SelectValue placeholder="테이블.컬럼 선택" />
                              </SelectTrigger>
                              <SelectContent>
                                {rightScreenTables.map((table) => (
                                  <React.Fragment key={table.tableName}>
                                    <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground bg-muted dark:bg-foreground/90">
                                      {table.screenName} ({table.tableName})
                                    </div>
                                    {table.columns.map((col) => (
                                      <SelectItem 
                                        key={`${table.tableName}.${col.columnName}`} 
                                        value={`${table.tableName}.${col.columnName}`}
                                        className="text-xs"
                                      >
                                        {col.columnLabel} ({col.columnName})
                                      </SelectItem>
                                    ))}
                                  </React.Fragment>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>

                  {/* 추가 버튼 */}
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={addLinkedFilter}
                    className="w-full text-xs"
                  >
                    <Plus className="mr-2 h-3 w-3" />
                    연결 필터 추가
                  </Button>

                  {/* 현재 설정 표시 */}
                  <Separator />
                  <div className="text-xs text-muted-foreground">
                    {(localConfig.linkedFilters || []).length > 0
                      ? `${localConfig.linkedFilters.length}개 필터 설정됨`
                      : "필터 없음 - 우측 화면에 모든 데이터가 표시됩니다"}
                  </div>
                </>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* 데이터 전달 탭 */}
        <TabsContent value="dataMapping" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">부모 데이터 자동 전달</CardTitle>
              <CardDescription className="text-xs">
                좌측 화면에서 행을 선택하면, 우측 화면의 추가/저장 시 지정된 컬럼 값이 자동으로 포함됩니다.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {!localConfig.leftScreenId || !localConfig.rightScreenId ? (
                <div className="rounded-lg border border-amber-200 bg-amber-50 p-3 dark:border-amber-900 dark:bg-amber-950">
                  <p className="text-xs text-amber-800 dark:text-amber-200">
                    먼저 "화면 설정" 탭에서 좌측/우측 화면을 모두 선택하세요.
                  </p>
                </div>
              ) : isLoadingLeftColumns || isLoadingRightColumns ? (
                <div className="flex items-center justify-center py-4">
                  <Loader2 className="text-muted-foreground h-5 w-5 animate-spin" />
                  <span className="text-muted-foreground ml-2 text-xs">컬럼 정보 로딩 중...</span>
                </div>
              ) : leftScreenColumns.length === 0 || rightScreenTables.length === 0 ? (
                <div className="rounded-lg border border-amber-200 bg-amber-50 p-3 dark:border-amber-900 dark:bg-amber-950">
                  <p className="text-xs text-amber-800 dark:text-amber-200">
                    {leftScreenColumns.length === 0 && "좌측 화면에 테이블이 설정되지 않았습니다. "}
                    {rightScreenTables.length === 0 && "우측 화면에 테이블이 설정되지 않았습니다."}
                  </p>
                </div>
              ) : (
                <>
                  {/* 우측 화면 테이블 목록 표시 */}
                  <div className="rounded-lg border border-emerald-200 bg-emerald-50 p-3 dark:border-emerald-900 dark:bg-emerald-950">
                    <p className="text-xs font-medium text-emerald-800 dark:text-emerald-200 mb-1">
                      우측 화면에서 감지된 테이블 ({rightScreenTables.length}개):
                    </p>
                    <ul className="text-xs text-emerald-700 dark:text-emerald-300 space-y-0.5">
                      {rightScreenTables.map((table) => (
                        <li key={table.tableName}>• {table.screenName}: <code className="bg-emerald-100 dark:bg-emerald-900 px-1 rounded">{table.tableName}</code></li>
                      ))}
                    </ul>
                  </div>

                  {/* 매핑 목록 */}
                  <div className="space-y-3">
                    {(localConfig.parentDataMapping || []).map((mapping: ParentDataMapping, index: number) => (
                      <div key={index} className="rounded-lg border bg-muted p-3 dark:bg-foreground">
                        <div className="mb-2 flex items-center justify-between">
                          <span className="text-xs font-medium text-foreground">매핑 #{index + 1}</span>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => removeParentDataMapping(index)}
                            className="h-6 w-6 p-0 text-destructive hover:bg-destructive/10 hover:text-destructive"
                          >
                            <Trash2 className="h-3 w-3" />
                          </Button>
                        </div>
                        <div className="space-y-2">
                          <div>
                            <Label className="text-xs text-muted-foreground">소스 컬럼 (좌측 화면)</Label>
                            <Select
                              value={mapping.sourceColumn}
                              onValueChange={(value) => updateParentDataMapping(index, "sourceColumn", value)}
                            >
                              <SelectTrigger className="h-8 text-xs">
                                <SelectValue placeholder="컬럼 선택" />
                              </SelectTrigger>
                              <SelectContent>
                                {leftScreenColumns.map((col) => (
                                  <SelectItem key={col.columnName} value={col.columnName} className="text-xs">
                                    {col.columnLabel} ({col.columnName})
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>
                          <div className="flex justify-center">
                            <ArrowRight className="h-4 w-4 rotate-90 text-muted-foreground/70" />
                          </div>
                          <div>
                            <Label className="text-xs text-muted-foreground">타겟 컬럼 (우측 화면)</Label>
                            <Select
                              value={mapping.targetColumn}
                              onValueChange={(value) => updateParentDataMapping(index, "targetColumn", value)}
                            >
                              <SelectTrigger className="h-8 text-xs">
                                <SelectValue placeholder="테이블.컬럼 선택" />
                              </SelectTrigger>
                              <SelectContent>
                                {rightScreenTables.map((table) => (
                                  <React.Fragment key={table.tableName}>
                                    <div className="px-2 py-1.5 text-xs font-semibold text-muted-foreground bg-muted dark:bg-foreground/90">
                                      {table.screenName} ({table.tableName})
                                    </div>
                                    {table.columns.map((col) => (
                                      <SelectItem 
                                        key={`${table.tableName}.${col.columnName}`} 
                                        value={col.columnName} 
                                        className="text-xs pl-4"
                                      >
                                        {col.columnLabel} ({col.columnName})
                                      </SelectItem>
                                    ))}
                                  </React.Fragment>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>

                  {/* 매핑 추가 버튼 */}
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={addParentDataMapping}
                    className="w-full"
                  >
                    <Plus className="mr-2 h-4 w-4" />
                    매핑 추가
                  </Button>

                  {/* 자동 매핑 안내 */}
                  <div className="rounded-lg border border-emerald-200 bg-emerald-50 p-3 dark:border-emerald-900 dark:bg-emerald-950">
                    <p className="text-xs text-emerald-800 dark:text-emerald-200">
                      <strong>자동 매핑:</strong> 좌측에서 선택한 데이터의 모든 컬럼이 우측 화면에 자동 전달됩니다.
                      <br />
                      동일한 컬럼명(예: equipment_code)이 있으면 별도 설정 없이 자동으로 매핑됩니다.
                    </p>
                  </div>

                  {/* 수동 매핑 안내 */}
                  <div className="rounded-lg border border-primary/20 bg-primary/10 p-3 dark:border-primary/20 dark:bg-primary/15">
                    <p className="text-xs text-primary dark:text-primary/70">
                      <strong>수동 매핑 (선택사항):</strong>
                      <br />
                      컬럼명이 다른 경우에만 위에서 매핑을 추가하세요.
                      <br />
                      예: 좌측 <code className="bg-primary/10 px-1 rounded">user_id</code> → 우측 <code className="bg-primary/10 px-1 rounded">created_by</code>
                    </p>
                  </div>
                </>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 설정 요약 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-sm">현재 설정</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-1 text-xs">
            <div className="flex justify-between">
              <span className="text-muted-foreground">좌측 화면:</span>
              <span className="font-medium">
                {localConfig.leftScreenId
                  ? screens.find((s) => s.screenId === localConfig.leftScreenId)?.screenName ||
                    `ID: ${localConfig.leftScreenId}`
                  : "미설정"}
              </span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">우측 화면:</span>
              <span className="font-medium">
                {localConfig.rightScreenId
                  ? screens.find((s) => s.screenId === localConfig.rightScreenId)?.screenName ||
                    `ID: ${localConfig.rightScreenId}`
                  : "미설정"}
              </span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">분할 비율:</span>
              <span className="font-medium">
                {localConfig.splitRatio}% / {100 - localConfig.splitRatio}%
              </span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">크기 조절:</span>
              <span className="font-medium">{localConfig.resizable ? "가능" : "불가능"}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-muted-foreground">데이터 매핑:</span>
              <span className="font-medium">
                {(localConfig.parentDataMapping || []).length > 0
                  ? `${localConfig.parentDataMapping.length}개 설정`
                  : "미설정"}
              </span>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
