/**
 * 플로우 단계 설정 패널
 * 선택된 단계의 속성 편집
 */

import { useState, useEffect, useCallback, useRef } from "react";
import { X, Trash2, Save, Check, ChevronsUpDown } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useToast } from "@/hooks/use-toast";
import { updateFlowStep, deleteFlowStep, getFlowProcedures, getFlowProcedureParameters } from "@/lib/api/flow";
import { FlowStep } from "@/types/flow";
import { FlowConditionBuilder } from "./FlowConditionBuilder";
import { tableManagementApi, getTableColumns } from "@/lib/api/tableManagement";
import { cn } from "@/lib/utils";
import { formatErrorMessage } from "@/lib/utils/errorUtils";
import { flowExternalDbApi } from "@/lib/api/flowExternalDb";
import {
  FlowExternalDbConnection,
  FlowExternalDbIntegrationConfig,
  FlowProcedureConfig,
  FlowProcedureParam,
  ProcedureListItem,
  ProcedureParameterInfo,
  INTEGRATION_TYPE_OPTIONS,
  OPERATION_OPTIONS,
} from "@/types/flowExternalDb";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { ExternalDbConnectionAPI } from "@/lib/api/externalDbConnection";

// 다중 REST API 연결 설정
interface RestApiConnectionConfig {
  connectionId: number;
  connectionName: string;
  endpoint: string;
  jsonPath: string;
  alias: string;
}

interface FlowStepPanelProps {
  step: FlowStep;
  flowId: number;
  flowTableName?: string; // 플로우 정의에서 선택한 테이블명
  flowDbSourceType?: "internal" | "external" | "restapi" | "multi_restapi"; // 플로우의 DB 소스 타입
  flowDbConnectionId?: number; // 플로우의 외부 DB 연결 ID
  flowRestApiConnectionId?: number; // 플로우의 REST API 연결 ID (단일)
  flowRestApiEndpoint?: string; // REST API 엔드포인트 (단일)
  flowRestApiJsonPath?: string; // REST API JSON 경로 (단일)
  flowRestApiConnections?: RestApiConnectionConfig[]; // 다중 REST API 설정
  onClose: () => void;
  onUpdate: () => void;
}

export function FlowStepPanel({
  step,
  flowId,
  flowTableName,
  flowDbSourceType = "internal",
  flowDbConnectionId,
  flowRestApiConnectionId,
  flowRestApiEndpoint,
  flowRestApiJsonPath,
  flowRestApiConnections,
  onClose,
  onUpdate,
}: FlowStepPanelProps) {
  const { toast } = useToast();

  console.log("🎯 FlowStepPanel Props:", {
    stepTableName: step.tableName,
    flowTableName,
    flowDbSourceType,
    flowDbConnectionId,
    flowRestApiConnectionId,
    flowRestApiEndpoint,
    flowRestApiJsonPath,
    final: step.tableName || flowTableName || "",
  });

  const [formData, setFormData] = useState({
    stepName: step.stepName,
    tableName: step.tableName || flowTableName || "", // 플로우 테이블명 우선 사용 (신규 방식)
    conditionJson: step.conditionJson,
    // 하이브리드 모드 필드
    moveType: step.moveType || "status",
    statusColumn: step.statusColumn || "",
    statusValue: step.statusValue || "",
    targetTable: step.targetTable || "",
    fieldMappings: step.fieldMappings || {},
    // 외부 연동 필드
    integrationType: step.integrationType || "internal",
    integrationConfig: step.integrationConfig,
    // 🆕 표시 설정
    displayConfig: step.displayConfig || { visibleColumns: [] },
  });

  const [tableList, setTableList] = useState<any[]>([]);
  const [loadingTables, setLoadingTables] = useState(true);
  const [openTableCombobox, setOpenTableCombobox] = useState(false);

  // 외부 DB 테이블 목록
  const [externalTableList, setExternalTableList] = useState<string[]>([]);
  const [loadingExternalTables, setLoadingExternalTables] = useState(false);
  const [selectedDbSource, setSelectedDbSource] = useState<"internal" | number>("internal"); // "internal" 또는 외부 DB connection ID

  // 컬럼 목록 (상태 컬럼 선택용)
  const [columns, setColumns] = useState<any[]>([]);
  const [loadingColumns, setLoadingColumns] = useState(false);
  const [openStatusColumnCombobox, setOpenStatusColumnCombobox] = useState(false);

  // 외부 DB 연결 목록
  const [externalConnections, setExternalConnections] = useState<FlowExternalDbConnection[]>([]);
  const [loadingConnections, setLoadingConnections] = useState(false);

  // 🆕 표시 설정용 컬럼 목록
  const [availableColumns, setAvailableColumns] = useState<string[]>([]);
  const [loadingAvailableColumns, setLoadingAvailableColumns] = useState(false);

  // 프로시저 관련 상태
  const [procedureList, setProcedureList] = useState<ProcedureListItem[]>([]);
  const [loadingProcedures, setLoadingProcedures] = useState(false);
  const [procedureParams, setProcedureParams] = useState<ProcedureParameterInfo[]>([]);
  const [loadingProcedureParams, setLoadingProcedureParams] = useState(false);
  const [openProcedureCombobox, setOpenProcedureCombobox] = useState(false);

  // 테이블 목록 조회
  useEffect(() => {
    const loadTables = async () => {
      try {
        setLoadingTables(true);
        const response = await tableManagementApi.getTableList();
        if (response.success && response.data) {
          setTableList(response.data);
        }
      } catch (error) {
        console.error("Failed to load tables:", error);
      } finally {
        setLoadingTables(false);
      }
    };
    loadTables();
  }, []);

  // 외부 DB 연결 목록 조회 (JWT 토큰 사용)
  useEffect(() => {
    const loadConnections = async () => {
      try {
        setLoadingConnections(true);

        // localStorage에서 JWT 토큰 가져오기
        const token = localStorage.getItem("authToken");
        if (!token) {
          console.warn("토큰이 없습니다. 외부 DB 연결 목록을 조회할 수 없습니다.");
          setExternalConnections([]);
          return;
        }

        const response = await ExternalDbConnectionAPI.getActiveControlConnections();

        if (response.success && response.data) {
          const filtered = response.data.filter(
            (conn) => !conn.connection_name.includes("메인") && !conn.connection_name.includes("현재 시스템"),
          );
          setExternalConnections(filtered);
        }
      } catch (error) {
        console.error("Failed to load external connections:", error);
        setExternalConnections([]);
      }
    };

    loadConnections();
  }, []);

  // 🆕 테이블이 선택되면 해당 테이블의 컬럼 목록 조회 (표시 설정용)
  useEffect(() => {
    const loadAvailableColumns = async () => {
      const tableName = formData.tableName || flowTableName;
      if (!tableName) {
        setAvailableColumns([]);
        return;
      }

      try {
        setLoadingAvailableColumns(true);
        const response = await getTableColumns(tableName);

        console.log("🎨 [FlowStepPanel] 컬럼 목록 API 응답:", {
          tableName,
          success: response.success,
          dataType: typeof response.data,
          dataKeys: response.data ? Object.keys(response.data) : [],
          isArray: Array.isArray(response.data),
          message: response.message,
          fullResponse: response,
        });

        if (response.success && response.data) {
          // response.data가 객체일 경우 columns 배열 찾기
          let columnsArray: any[] = [];

          if (Array.isArray(response.data)) {
            columnsArray = response.data;
          } else if (response.data.columns && Array.isArray(response.data.columns)) {
            columnsArray = response.data.columns;
          } else if (response.data.data && Array.isArray(response.data.data)) {
            columnsArray = response.data.data;
          } else {
            console.warn("⚠️ 예상치 못한 data 구조:", response.data);
          }

          const columnNames = columnsArray.map((col: any) => col.columnName || col.column_name);
          setAvailableColumns(columnNames);

          console.log("✅ [FlowStepPanel] 컬럼 목록 로드 성공:", {
            tableName,
            columns: columnNames,
          });
        } else {
          console.warn("⚠️ [FlowStepPanel] 컬럼 목록 조회 실패:", {
            tableName,
            message: response.message,
            success: response.success,
            hasData: !!response.data,
          });
          setAvailableColumns([]);
        }
      } catch (error) {
        console.error("❌ [FlowStepPanel] 컬럼 목록 로드 에러:", {
          tableName,
          error,
        });
        setAvailableColumns([]);
      } finally {
        setLoadingAvailableColumns(false);
      }
    };

    loadAvailableColumns();
  }, [formData.tableName, flowTableName]);

  // 외부 DB 선택 시 해당 DB의 테이블 목록 조회 (JWT 토큰 사용)
  useEffect(() => {
    const loadExternalTables = async () => {
      console.log("🔍 loadExternalTables triggered, selectedDbSource:", selectedDbSource);

      if (selectedDbSource === "internal" || typeof selectedDbSource !== "number") {
        console.log("⚠️ Skipping external table load (internal or not a number)");
        setExternalTableList([]);
        return;
      }

      console.log("📡 Loading external tables for connection ID:", selectedDbSource);

      try {
        setLoadingExternalTables(true);

        // localStorage에서 JWT 토큰 가져오기
        const token = localStorage.getItem("authToken");
        if (!token) {
          console.warn("토큰이 없습니다. 외부 DB 테이블 목록을 조회할 수 없습니다.");
          setExternalTableList([]);
          return;
        }

        // 기존 multi-connection API 사용 (JWT 토큰 포함)
        const response = await fetch(`/api/multi-connection/connections/${selectedDbSource}/tables`, {
          credentials: "include",
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
          },
        }).catch((err) => {
          console.warn("외부 DB 테이블 목록 fetch 실패:", err);
          return null;
        });

        if (response && response.ok) {
          const result = await response.json();
          console.log("✅ External tables API response:", result);
          console.log("📊 result.data type:", typeof result.data, "isArray:", Array.isArray(result.data));
          console.log("📊 result.data:", JSON.stringify(result.data, null, 2));

          if (result.success && result.data) {
            // 데이터 형식이 다를 수 있으므로 변환
            const tableNames = result.data.map((t: any) => {
              console.log("🔍 Processing item:", t, "type:", typeof t);
              // tableName (camelCase), table_name, tablename, name 모두 지원
              return typeof t === "string" ? t : t.tableName || t.table_name || t.tablename || t.name;
            });
            console.log("📋 Processed table names:", tableNames);
            setExternalTableList(tableNames);
          } else {
            console.warn("❌ No data in response or success=false");
            setExternalTableList([]);
          }
        } else {
          // 인증 오류 시에도 빈 배열로 처리 (리다이렉트 방지)
          console.warn(`외부 DB 테이블 목록 조회 실패: ${response?.status || "네트워크 오류"}`);
          setExternalTableList([]);
        }
      } catch (error) {
        console.error("외부 DB 테이블 목록 조회 오류:", error);
        setExternalTableList([]);
      } finally {
        setLoadingExternalTables(false);
      }
    };

    loadExternalTables();
  }, [selectedDbSource]);

  useEffect(() => {
    console.log("🔄 Initializing formData from step:", {
      id: step.id,
      stepName: step.stepName,
      statusColumn: step.statusColumn,
      statusValue: step.statusValue,
      flowTableName, // 플로우 정의의 테이블명
    });

    const newFormData = {
      stepName: step.stepName,
      tableName: step.tableName || flowTableName || "", // 플로우 테이블명 우선 사용
      conditionJson: step.conditionJson,
      // 하이브리드 모드 필드
      moveType: step.moveType || "status",
      statusColumn: step.statusColumn || "",
      statusValue: step.statusValue || "",
      targetTable: step.targetTable || "",
      fieldMappings: step.fieldMappings || {},
      // 외부 연동 필드
      integrationType: step.integrationType || "internal",
      integrationConfig: step.integrationConfig,
      // 표시 설정 (displayConfig 반드시 초기화)
      displayConfig: step.displayConfig || { visibleColumns: [] },
    };

    console.log("✅ Setting formData:", newFormData);
    setFormData(newFormData);
  }, [step.id, flowTableName]); // flowTableName도 의존성 추가

  // 테이블 선택 시 컬럼 로드 - 내부/외부 DB 및 REST API 모두 지원
  useEffect(() => {
    const loadColumns = async () => {
      // 다중 REST API인 경우 tableName 없이도 컬럼 로드 가능
      if (!formData.tableName && flowDbSourceType !== "multi_restapi") {
        setColumns([]);
        return;
      }

      try {
        setLoadingColumns(true);
        console.log("🔍 Loading columns for status column selector:", {
          tableName: formData.tableName,
          flowDbSourceType,
          flowDbConnectionId,
          flowRestApiConnectionId,
          flowRestApiConnections,
        });

        // 다중 REST API인 경우
        if (flowDbSourceType === "multi_restapi" && flowRestApiConnections && flowRestApiConnections.length > 0) {
          console.log("🌐 다중 REST API 컬럼 로드 시작");
          const { ExternalRestApiConnectionAPI } = await import("@/lib/api/externalRestApiConnection");
          
          const allColumns: any[] = [];
          
          for (const config of flowRestApiConnections) {
            try {
              const effectiveJsonPath = (!config.jsonPath || config.jsonPath === "data") ? "response" : config.jsonPath;
              
              const restApiData = await ExternalRestApiConnectionAPI.fetchData(
                config.connectionId,
                config.endpoint,
                effectiveJsonPath,
              );
              
              if (restApiData.columns && restApiData.columns.length > 0) {
                const prefixedColumns = restApiData.columns.map((col) => ({
                  column_name: config.alias ? `${config.alias}${col.columnName}` : col.columnName,
                  data_type: col.dataType || "varchar",
                  displayName: `${col.columnLabel || col.columnName} (${config.connectionName})`,
                }));
                allColumns.push(...prefixedColumns);
              }
            } catch (apiError) {
              console.warn(`API ${config.connectionId} 컬럼 로드 실패:`, apiError);
            }
          }
          
          console.log("✅ 다중 REST API 컬럼 로드 완료:", allColumns.length, "items");
          setColumns(allColumns);
          return;
        }

        // 단일 REST API인 경우
        const isRestApi = flowDbSourceType === "restapi" || formData.tableName?.startsWith("_restapi_");
        
        if (isRestApi && flowRestApiConnectionId) {
          console.log("🌐 단일 REST API 컬럼 로드 시작");
          const { ExternalRestApiConnectionAPI } = await import("@/lib/api/externalRestApiConnection");
          
          const effectiveJsonPath = (!flowRestApiJsonPath || flowRestApiJsonPath === "data") ? "response" : flowRestApiJsonPath;
          
          const restApiData = await ExternalRestApiConnectionAPI.fetchData(
            flowRestApiConnectionId,
            flowRestApiEndpoint,
            effectiveJsonPath,
          );
          
          if (restApiData.columns && restApiData.columns.length > 0) {
            const columnList = restApiData.columns.map((col) => ({
              column_name: col.columnName,
              data_type: col.dataType || "varchar",
              displayName: col.columnLabel || col.columnName,
            }));
            console.log("✅ REST API 컬럼 로드 완료:", columnList.length, "items");
            setColumns(columnList);
          } else {
            setColumns([]);
          }
          return;
        }

        // 외부 DB인 경우
        if (flowDbSourceType === "external" && flowDbConnectionId) {
          const token = localStorage.getItem("authToken");
          if (!token) {
            console.warn("토큰이 없습니다. 외부 DB 컬럼 목록을 조회할 수 없습니다.");
            setColumns([]);
            return;
          }

          // 외부 DB 컬럼 조회 API
          const response = await fetch(
            `/api/multi-connection/connections/${flowDbConnectionId}/tables/${formData.tableName}/columns`,
            {
              credentials: "include",
              headers: {
                Authorization: `Bearer ${token}`,
                "Content-Type": "application/json",
              },
            },
          ).catch((err) => {
            console.warn("외부 DB 컬럼 목록 fetch 실패:", err);
            return null;
          });

          if (response && response.ok) {
            const result = await response.json();
            console.log("✅ External columns API response:", result);

            if (result.success && result.data) {
              // 컬럼 데이터 형식 통일
              const columnList = Array.isArray(result.data)
                ? result.data.map((col: any) => ({
                    column_name: col.column_name || col.columnName || col.name,
                    data_type: col.data_type || col.dataType || col.type,
                  }))
                : [];
              console.log("✅ Setting external columns:", columnList);
              setColumns(columnList);
            } else {
              console.warn("❌ No data in external columns response");
              setColumns([]);
            }
          } else {
            console.warn(`외부 DB 컬럼 목록 조회 실패: ${response?.status || "네트워크 오류"}`);
            setColumns([]);
          }
        } else {
          // 내부 DB인 경우 (기존 로직)
          const response = await getTableColumns(formData.tableName);
          console.log("📦 Internal columns response:", response);

          if (response.success && response.data && response.data.columns) {
            console.log("✅ Setting internal columns:", response.data.columns);
            setColumns(response.data.columns);
          } else {
            console.log("❌ No columns in response");
            setColumns([]);
          }
        }
      } catch (error) {
        console.error("Failed to load columns:", error);
        setColumns([]);
      } finally {
        setLoadingColumns(false);
      }
    };

    loadColumns();
  }, [formData.tableName, flowDbSourceType, flowDbConnectionId, flowRestApiConnectionId, flowRestApiEndpoint, flowRestApiJsonPath, flowRestApiConnections]);

  // formData의 최신 값을 항상 참조하기 위한 ref
  const formDataRef = useRef(formData);

  // formData가 변경될 때마다 ref 업데이트
  useEffect(() => {
    formDataRef.current = formData;
  }, [formData]);

  // 저장
  const handleSave = useCallback(async () => {
    const currentFormData = formDataRef.current;
    console.log("🚀 handleSave called, formData:", JSON.stringify(currentFormData, null, 2));

    // 상태 변경 방식일 때 필수 필드 검증
    if (currentFormData.moveType === "status") {
      if (!currentFormData.statusColumn) {
        toast({
          title: "입력 오류",
          description: "상태 변경 방식을 사용하려면 '상태 컬럼명'을 반드시 지정해야 합니다.",
          variant: "destructive",
        });
        return;
      }
      if (!currentFormData.statusValue) {
        toast({
          title: "입력 오류",
          description: "상태 변경 방식을 사용하려면 '이 단계의 상태값'을 반드시 지정해야 합니다.",
          variant: "destructive",
        });
        return;
      }
    }

    try {
      const response = await updateFlowStep(step.id, currentFormData);
      console.log("📡 API response:", response);
      if (response.success) {
        toast({
          title: "저장 완료",
          description: "단계가 수정되었습니다.",
        });
        onUpdate();
        onClose();
      } else {
        toast({
          title: "저장 실패",
          description: formatErrorMessage(response.error, "단계 저장 중 오류가 발생했습니다."),
          variant: "destructive",
        });
      }
    } catch (error: any) {
      toast({
        title: "오류 발생",
        description: error.message || "단계 저장 중 오류가 발생했습니다.",
        variant: "destructive",
      });
    }
  }, [step.id, onUpdate, onClose, toast]);

  // 삭제
  const handleDelete = async () => {
    if (!confirm(`"${step.stepName}" 단계를 삭제하시겠습니까?\n이 작업은 되돌릴 수 없습니다.`)) {
      return;
    }

    try {
      const response = await deleteFlowStep(step.id);
      if (response.success) {
        toast({
          title: "삭제 완료",
          description: "단계가 삭제되었습니다.",
        });
        onUpdate();
        onClose();
      } else {
        toast({
          title: "삭제 실패",
          description: formatErrorMessage(response.error, "단계 삭제 중 오류가 발생했습니다."),
          variant: "destructive",
        });
      }
    } catch (error: any) {
      toast({
        title: "오류 발생",
        description: error.message || "단계 삭제 중 오류가 발생했습니다.",
        variant: "destructive",
      });
    }
  };

  return (
    <div className="fixed top-0 right-0 z-50 h-full w-96 overflow-y-auto border-l bg-white shadow-xl">
      <div className="space-y-6 p-6">
        {/* 헤더 */}
        <div className="flex items-center justify-between">
          <h2 className="text-xl font-bold">단계 설정</h2>
          <Button variant="ghost" size="sm" onClick={onClose}>
            <X className="h-4 w-4" />
          </Button>
        </div>

        {/* 기본 정보 */}
        <Card>
          <CardHeader>
            <CardTitle>기본 정보</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label>단계 이름</Label>
              <Input
                value={formData.stepName}
                onChange={(e) => setFormData({ ...formData, stepName: e.target.value })}
                placeholder="단계 이름 입력"
              />
            </div>

            <div>
              <Label>단계 순서</Label>
              <Input value={step.stepOrder} disabled />
            </div>

            {/* ===== 구버전: 단계별 테이블 선택 방식 (주석처리) ===== */}
            {/* DB 소스 선택 */}
            {/* <div>
              <Label>데이터베이스 소스</Label>
              <Select
                value={selectedDbSource.toString()}
                onValueChange={(value) => {
                  const dbSource = value === "internal" ? "internal" : parseInt(value);
                  setSelectedDbSource(dbSource);
                  // DB 소스 변경 시 테이블 선택 초기화
                  setFormData({ ...formData, tableName: "" });
                }}
              >
                <SelectTrigger>
                  <SelectValue placeholder="데이터베이스 선택" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="internal">내부 데이터베이스</SelectItem>
                  {externalConnections.map((conn: any) => (
                    <SelectItem key={conn.id} value={conn.id.toString()}>
                      {conn.connection_name} ({conn.db_type?.toUpperCase()})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <p className="mt-1 text-xs text-muted-foreground">조회할 데이터베이스를 선택합니다</p>
            </div> */}

            {/* 테이블 선택 */}
            {/* <div>
              <Label>조회할 테이블</Label>
              <Popover open={openTableCombobox} onOpenChange={setOpenTableCombobox}>
                <PopoverTrigger asChild>
                  <Button
                    variant="outline"
                    role="combobox"
                    aria-expanded={openTableCombobox}
                    className="w-full justify-between"
                    disabled={loadingTables || (selectedDbSource !== "internal" && loadingExternalTables)}
                  >
                    {formData.tableName
                      ? selectedDbSource === "internal"
                        ? tableList.find((table) => table.tableName === formData.tableName)?.displayName ||
                          formData.tableName
                        : formData.tableName
                      : loadingTables || loadingExternalTables
                        ? "로딩 중..."
                        : "테이블 선택"}
                    <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="테이블 검색..." />
                    <CommandList>
                      <CommandEmpty>테이블을 찾을 수 없습니다.</CommandEmpty>
                      <CommandGroup>
                        {selectedDbSource === "internal"
                          ? // 내부 DB 테이블 목록
                            tableList.map((table) => (
                              <CommandItem
                                key={table.tableName}
                                value={table.tableName}
                                onSelect={(currentValue) => {
                                  setFormData({ ...formData, tableName: currentValue });
                                  setOpenTableCombobox(false);
                                }}
                              >
                                <Check
                                  className={cn(
                                    "mr-2 h-4 w-4",
                                    formData.tableName === table.tableName ? "opacity-100" : "opacity-0",
                                  )}
                                />
                                <div className="flex flex-col">
                                  <span className="font-medium">{table.displayName || table.tableName}</span>
                                  {table.description && (
                                    <span className="text-xs text-muted-foreground">{table.description}</span>
                                  )}
                                </div>
                              </CommandItem>
                            ))
                          : // 외부 DB 테이블 목록 (문자열 배열)
                            externalTableList.map((tableName, index) => (
                              <CommandItem
                                key={`external-${selectedDbSource}-${tableName}-${index}`}
                                value={tableName}
                                onSelect={(currentValue) => {
                                  setFormData({ ...formData, tableName: currentValue });
                                  setOpenTableCombobox(false);
                                }}
                              >
                                <Check
                                  className={cn(
                                    "mr-2 h-4 w-4",
                                    formData.tableName === tableName ? "opacity-100" : "opacity-0",
                                  )}
                                />
                                <div>{tableName}</div>
                              </CommandItem>
                            ))}
                      </CommandGroup>
                    </CommandList>
                  </Command>
                </PopoverContent>
              </Popover>
              <p className="mt-1 text-xs text-muted-foreground">
                {selectedDbSource === "internal"
                  ? "이 단계에서 조건을 적용할 테이블을 선택합니다"
                  : "외부 데이터베이스의 테이블을 선택합니다"}
              </p>
            </div> */}
            {/* ===== 구버전 끝 ===== */}

            {/* ===== 신버전: 플로우에서 선택한 테이블 표시만 ===== */}
            <div>
              <Label>연결된 테이블</Label>
              <Input value={formData.tableName || "테이블이 지정되지 않았습니다"} disabled className="bg-muted" />
              <p className="mt-1 text-xs text-muted-foreground">플로우 생성 시 선택한 테이블입니다 (수정 불가)</p>
            </div>
            {/* ===== 신버전 끝 ===== */}
          </CardContent>
        </Card>

        {/* 조건 설정 */}
        <Card>
          <CardHeader>
            <CardTitle>조건 설정</CardTitle>
            <CardDescription>이 단계에 포함될 데이터의 조건을 설정합니다</CardDescription>
          </CardHeader>
          <CardContent>
            {!formData.tableName ? (
              <div className="py-8 text-center text-muted-foreground">먼저 테이블을 선택해주세요</div>
            ) : (
              <FlowConditionBuilder
                flowId={flowId}
                tableName={formData.tableName}
                dbSourceType={flowDbSourceType}
                dbConnectionId={flowDbConnectionId}
                restApiConnectionId={flowRestApiConnectionId}
                restApiEndpoint={flowRestApiEndpoint}
                restApiJsonPath={flowRestApiJsonPath}
                restApiConnections={flowRestApiConnections}
                condition={formData.conditionJson}
                onChange={(condition) => setFormData({ ...formData, conditionJson: condition })}
              />
            )}
          </CardContent>
        </Card>

        {/* 데이터 이동 설정 */}
        <Card>
          <CardHeader>
            <CardTitle>데이터 이동 설정</CardTitle>
            <CardDescription>다음 단계로 데이터를 이동할 때의 동작을 설정합니다</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* 이동 방식 선택 */}
            <div>
              <Label>이동 방식</Label>
              <Select
                value={formData.moveType}
                onValueChange={(value: "status" | "table" | "both") => setFormData({ ...formData, moveType: value })}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="status">
                    <div>
                      <div className="font-medium">상태 변경</div>
                      <div className="text-xs text-muted-foreground">같은 테이블 내에서 상태 컬럼만 업데이트</div>
                    </div>
                  </SelectItem>
                  <SelectItem value="table">
                    <div>
                      <div className="font-medium">테이블 이동</div>
                      <div className="text-xs text-muted-foreground">다른 테이블로 데이터 복사</div>
                    </div>
                  </SelectItem>
                  <SelectItem value="both">
                    <div>
                      <div className="font-medium">하이브리드</div>
                      <div className="text-xs text-muted-foreground">상태 변경 + 테이블 이동</div>
                    </div>
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 상태 변경 설정 (status 또는 both일 때) */}
            {(formData.moveType === "status" || formData.moveType === "both") && (
              <>
                <div>
                  <Label>상태 컬럼명</Label>
                  <Popover open={openStatusColumnCombobox} onOpenChange={setOpenStatusColumnCombobox}>
                    <PopoverTrigger asChild>
                      <Button
                        variant="outline"
                        role="combobox"
                        aria-expanded={openStatusColumnCombobox}
                        className="w-full justify-between"
                        disabled={!formData.tableName || loadingColumns}
                      >
                        {loadingColumns
                          ? "컬럼 로딩 중..."
                          : formData.statusColumn
                            ? (() => {
                                const col = columns.find(
                                  (c) => (c.column_name || c.columnName) === formData.statusColumn,
                                );
                                return col ? col.column_name || col.columnName : formData.statusColumn;
                              })()
                            : "상태 컬럼 선택"}
                        <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-full p-0">
                      <Command>
                        <CommandInput placeholder="컬럼 검색..." />
                        <CommandList>
                          <CommandEmpty>컬럼을 찾을 수 없습니다.</CommandEmpty>
                          <CommandGroup>
                            {columns.map((column, idx) => {
                              const columnName = column.column_name || column.columnName || "";
                              const dataType = column.data_type || column.dataType || "";

                              return (
                                <CommandItem
                                  key={`${columnName}-${idx}`}
                                  value={columnName}
                                  onSelect={() => {
                                    setFormData({ ...formData, statusColumn: columnName });
                                    setOpenStatusColumnCombobox(false);
                                  }}
                                >
                                  <Check
                                    className={cn(
                                      "mr-2 h-4 w-4",
                                      formData.statusColumn === columnName ? "opacity-100" : "opacity-0",
                                    )}
                                  />
                                  <div>
                                    <div>{columnName}</div>
                                    <div className="text-xs text-muted-foreground">({dataType})</div>
                                  </div>
                                </CommandItem>
                              );
                            })}
                          </CommandGroup>
                        </CommandList>
                      </Command>
                    </PopoverContent>
                  </Popover>
                  <p className="mt-1 text-xs text-muted-foreground">업데이트할 컬럼의 이름</p>
                </div>

                <div>
                  <Label>이 단계의 상태값</Label>
                  <Input
                    value={formData.statusValue}
                    onChange={(e) => {
                      const newValue = e.target.value;
                      console.log("💡 statusValue onChange:", newValue);
                      setFormData({ ...formData, statusValue: newValue });
                      console.log("✅ Updated formData:", { ...formData, statusValue: newValue });
                    }}
                    placeholder="예: approved"
                  />
                  <p className="mt-1 text-xs text-muted-foreground">이 단계에 있을 때의 상태값</p>
                </div>
              </>
            )}

            {/* 테이블 이동 설정 (table 또는 both일 때) */}
            {(formData.moveType === "table" || formData.moveType === "both") && (
              <>
                <div>
                  <Label>타겟 테이블</Label>
                  <Select
                    value={formData.targetTable}
                    onValueChange={(value) => setFormData({ ...formData, targetTable: value })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="테이블 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {tableList.map((table) => (
                        <SelectItem key={table.tableName} value={table.tableName}>
                          {table.displayName || table.tableName}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <p className="mt-1 text-xs text-muted-foreground">다음 단계로 이동 시 데이터가 저장될 테이블</p>
                </div>

                <div className="rounded-md bg-primary/10 p-3">
                  <p className="text-sm text-primary">
                    💡 필드 매핑은 향후 구현 예정입니다. 현재는 같은 이름의 컬럼만 자동 매핑됩니다.
                  </p>
                </div>
              </>
            )}
          </CardContent>
        </Card>

        {/* 외부 DB 연동 설정 */}
        <Card>
          <CardHeader>
            <CardTitle>외부 DB 연동 설정</CardTitle>
            <CardDescription>데이터 이동 시 외부 시스템과의 연동을 설정합니다</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <Label>연동 타입</Label>
              <Select
                value={formData.integrationType}
                onValueChange={(value: any) => {
                  setFormData({ ...formData, integrationType: value });
                  // 타입 변경 시 config 초기화
                  if (value === "internal") {
                    setFormData((prev) => ({ ...prev, integrationConfig: undefined }));
                  }
                }}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {INTEGRATION_TYPE_OPTIONS.map((opt) => (
                    <SelectItem
                      key={opt.value}
                      value={opt.value}
                      disabled={opt.value !== "internal" && opt.value !== "external_db" && opt.value !== "procedure" && opt.value !== "rest_api"}
                    >
                      {opt.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 외부 DB 연동 설정 */}
            {formData.integrationType === "external_db" && (
              <div className="space-y-4 rounded-lg border p-4">
                {externalConnections.length === 0 ? (
                  <div className="rounded-md bg-amber-50 p-3">
                    <p className="text-sm text-yellow-900">
                      ⚠️ 등록된 외부 DB 연결이 없습니다. 먼저 외부 DB 연결을 추가해주세요.
                    </p>
                  </div>
                ) : (
                  <>
                    <div>
                      <Label>외부 DB 연결</Label>
                      <Select
                        value={formData.integrationConfig?.connectionId?.toString() || ""}
                        onValueChange={(value) => {
                          const connectionId = parseInt(value);
                          setFormData({
                            ...formData,
                            integrationConfig: {
                              type: "external_db",
                              connectionId,
                              operation: "update",
                              tableName: "",
                              updateFields: {},
                              whereCondition: {},
                            },
                          });
                        }}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="연결 선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {externalConnections.map((conn) => (
                            <SelectItem key={conn.id} value={conn.id.toString()}>
                              {conn.name} ({conn.dbType})
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>

                    {formData.integrationConfig?.connectionId && (
                      <>
                        <div>
                          <Label>작업 타입</Label>
                          <Select
                            value={formData.integrationConfig.operation}
                            onValueChange={(value: any) =>
                              setFormData({
                                ...formData,
                                integrationConfig: {
                                  ...formData.integrationConfig!,
                                  operation: value,
                                },
                              })
                            }
                          >
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              {OPERATION_OPTIONS.map((opt) => (
                                <SelectItem key={opt.value} value={opt.value}>
                                  {opt.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>

                        <div>
                          <Label>테이블명</Label>
                          <Input
                            value={formData.integrationConfig.tableName}
                            onChange={(e) =>
                              setFormData({
                                ...formData,
                                integrationConfig: {
                                  ...formData.integrationConfig!,
                                  tableName: e.target.value,
                                },
                              })
                            }
                            placeholder="예: orders"
                          />
                        </div>

                        {formData.integrationConfig.operation === "custom" ? (
                          <div>
                            <Label>커스텀 쿼리</Label>
                            <Textarea
                              value={formData.integrationConfig.customQuery || ""}
                              onChange={(e) =>
                                setFormData({
                                  ...formData,
                                  integrationConfig: {
                                    ...formData.integrationConfig!,
                                    customQuery: e.target.value,
                                  },
                                })
                              }
                              placeholder="UPDATE orders SET status = 'approved' WHERE id = {{dataId}}"
                              rows={4}
                              className="font-mono text-sm"
                            />
                            <p className="mt-1 text-xs text-muted-foreground">
                              템플릿 변수: {`{{dataId}}, {{currentUser}}, {{currentTimestamp}}`}
                            </p>
                          </div>
                        ) : (
                          <>
                            {(formData.integrationConfig.operation === "update" ||
                              formData.integrationConfig.operation === "insert") && (
                              <div>
                                <Label>업데이트할 필드 (JSON)</Label>
                                <Textarea
                                  value={JSON.stringify(formData.integrationConfig.updateFields || {}, null, 2)}
                                  onChange={(e) => {
                                    try {
                                      const parsed = JSON.parse(e.target.value);
                                      setFormData({
                                        ...formData,
                                        integrationConfig: {
                                          ...formData.integrationConfig!,
                                          updateFields: parsed,
                                        },
                                      });
                                    } catch (err) {
                                      // JSON 파싱 실패 시 무시
                                    }
                                  }}
                                  placeholder='{"status": "approved", "updated_by": "{{currentUser}}"}'
                                  rows={4}
                                  className="font-mono text-sm"
                                />
                              </div>
                            )}

                            {(formData.integrationConfig.operation === "update" ||
                              formData.integrationConfig.operation === "delete") && (
                              <div>
                                <Label>WHERE 조건 (JSON)</Label>
                                <Textarea
                                  value={JSON.stringify(formData.integrationConfig.whereCondition || {}, null, 2)}
                                  onChange={(e) => {
                                    try {
                                      const parsed = JSON.parse(e.target.value);
                                      setFormData({
                                        ...formData,
                                        integrationConfig: {
                                          ...formData.integrationConfig!,
                                          whereCondition: parsed,
                                        },
                                      });
                                    } catch (err) {
                                      // JSON 파싱 실패 시 무시
                                    }
                                  }}
                                  placeholder='{"id": "{{dataId}}"}'
                                  rows={3}
                                  className="font-mono text-sm"
                                />
                              </div>
                            )}
                          </>
                        )}

                        <div className="rounded-md bg-primary/10 p-3">
                          <p className="text-sm text-primary">
                            💡 템플릿 변수를 사용하여 동적 값을 삽입할 수 있습니다:
                            <br />• {`{{dataId}}`} - 이동하는 데이터의 ID
                            <br />• {`{{currentUser}}`} - 현재 사용자
                            <br />• {`{{currentTimestamp}}`} - 현재 시간
                          </p>
                        </div>
                      </>
                    )}
                  </>
                )}
              </div>
            )}

            {/* REST API 연동 설정 */}
            {formData.integrationType === "rest_api" && (
              <div className="space-y-4 rounded-lg border p-4">
                <div>
                  <Label>REST API 연결</Label>
                  <Select
                    value={formData.integrationConfig?.connectionId?.toString() || ""}
                    onValueChange={(value) => {
                      const connectionId = parseInt(value);
                      setFormData({
                        ...formData,
                        integrationConfig: {
                          type: "rest_api",
                          connectionId,
                          operation: "update",
                          endpoint: "",
                          method: "POST",
                          bodyTemplate: "{}",
                        } as any,
                      });
                    }}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="REST API 연결 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {flowRestApiConnections && flowRestApiConnections.length > 0 ? (
                        flowRestApiConnections.map((api) => (
                          <SelectItem key={api.connectionId} value={api.connectionId.toString()}>
                            {api.connectionName}
                          </SelectItem>
                        ))
                      ) : flowRestApiConnectionId ? (
                        <SelectItem value={flowRestApiConnectionId.toString()}>
                          기본 REST API 연결
                        </SelectItem>
                      ) : (
                        // Radix UI Select v2.x: 빈 문자열 value="" 금지 → "__placeholder__" 사용
                        <SelectItem value="__placeholder__" disabled>
                          연결된 REST API가 없습니다
                        </SelectItem>
                      )}
                    </SelectContent>
                  </Select>
                </div>

                {formData.integrationConfig?.connectionId && (
                  <>
                    <div>
                      <Label>HTTP 메서드</Label>
                      <Select
                        value={(formData.integrationConfig as any).method || "POST"}
                        onValueChange={(value) =>
                          setFormData({
                            ...formData,
                            integrationConfig: {
                              ...formData.integrationConfig!,
                              method: value,
                            } as any,
                          })
                        }
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="GET">GET</SelectItem>
                          <SelectItem value="POST">POST</SelectItem>
                          <SelectItem value="PUT">PUT</SelectItem>
                          <SelectItem value="PATCH">PATCH</SelectItem>
                          <SelectItem value="DELETE">DELETE</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <div>
                      <Label>엔드포인트</Label>
                      <Input
                        value={(formData.integrationConfig as any).endpoint || ""}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            integrationConfig: {
                              ...formData.integrationConfig!,
                              endpoint: e.target.value,
                            } as any,
                          })
                        }
                        placeholder="/api/update"
                      />
                      <p className="text-muted-foreground mt-1 text-xs">
                        데이터 이동 시 호출할 API 엔드포인트
                      </p>
                    </div>

                    <div>
                      <Label>요청 바디 (JSON)</Label>
                      <Textarea
                        value={(formData.integrationConfig as any).bodyTemplate || "{}"}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            integrationConfig: {
                              ...formData.integrationConfig!,
                              bodyTemplate: e.target.value,
                            } as any,
                          })
                        }
                        placeholder='{"id": "{{dataId}}", "status": "approved"}'
                        rows={4}
                        className="font-mono text-sm"
                      />
                    </div>

                    <div className="rounded-md bg-primary/10 p-3">
                      <p className="text-sm text-primary">
                        💡 템플릿 변수를 사용하여 동적 값을 삽입할 수 있습니다:
                        <br />• {`{{dataId}}`} - 이동하는 데이터의 ID
                        <br />• {`{{currentUser}}`} - 현재 사용자
                        <br />• {`{{currentTimestamp}}`} - 현재 시간
                      </p>
                    </div>
                  </>
                )}
              </div>
            )}

            {/* 프로시저/함수 호출 설정 */}
            {formData.integrationType === "procedure" && (
              <div className="space-y-4 rounded-lg border p-4">
                {/* DB 소스 선택 */}
                <div>
                  <Label>DB 소스</Label>
                  <Select
                    value={
                      (formData.integrationConfig as FlowProcedureConfig)?.dbSource || "internal"
                    }
                    onValueChange={async (value: "internal" | "external") => {
                      const newConfig: FlowProcedureConfig = {
                        type: "procedure",
                        dbSource: value,
                        connectionId: undefined,
                        procedureName: "",
                        procedureSchema: "public",
                        callType: "function",
                        parameters: [],
                      };
                      setFormData({ ...formData, integrationConfig: newConfig });
                      setProcedureList([]);
                      setProcedureParams([]);

                      if (value === "internal") {
                        setLoadingProcedures(true);
                        try {
                          const res = await getFlowProcedures("internal");
                          if (res.success && res.data) setProcedureList(res.data);
                        } catch (e) {
                          console.error("프로시저 목록 조회 실패:", e);
                        } finally {
                          setLoadingProcedures(false);
                        }
                      }
                    }}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="internal">내부 DB</SelectItem>
                      <SelectItem value="external">외부 DB</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {/* 외부 DB 연결 선택 */}
                {(formData.integrationConfig as FlowProcedureConfig)?.dbSource === "external" && (
                  <div>
                    <Label>외부 DB 연결</Label>
                    {externalConnections.length === 0 ? (
                      <div className="rounded-md bg-amber-50 p-3">
                        <p className="text-sm text-yellow-900">
                          등록된 외부 DB 연결이 없습니다. 먼저 외부 DB 연결을 추가해주세요.
                        </p>
                      </div>
                    ) : (
                      <Select
                        value={
                          (formData.integrationConfig as FlowProcedureConfig)?.connectionId?.toString() || ""
                        }
                        onValueChange={async (value) => {
                          const connId = parseInt(value);
                          const newConfig: FlowProcedureConfig = {
                            ...(formData.integrationConfig as FlowProcedureConfig),
                            connectionId: connId,
                            procedureName: "",
                            parameters: [],
                          };
                          setFormData({ ...formData, integrationConfig: newConfig });
                          setProcedureParams([]);

                          setLoadingProcedures(true);
                          try {
                            const res = await getFlowProcedures("external", connId);
                            if (res.success && res.data) setProcedureList(res.data);
                          } catch (e) {
                            console.error("외부 프로시저 목록 조회 실패:", e);
                          } finally {
                            setLoadingProcedures(false);
                          }
                        }}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="연결 선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {externalConnections.map((conn) => (
                            <SelectItem key={conn.id} value={conn.id.toString()}>
                              {conn.name} ({conn.dbType})
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    )}
                  </div>
                )}

                {/* 프로시저 선택 */}
                {((formData.integrationConfig as FlowProcedureConfig)?.dbSource === "internal" ||
                  (formData.integrationConfig as FlowProcedureConfig)?.connectionId) && (
                  <>
                    <div>
                      <Label>프로시저/함수 선택</Label>
                      {loadingProcedures ? (
                        <div className="py-2 text-sm text-muted-foreground">로딩 중...</div>
                      ) : (
                        <Popover open={openProcedureCombobox} onOpenChange={setOpenProcedureCombobox}>
                          <PopoverTrigger asChild>
                            <Button
                              variant="outline"
                              role="combobox"
                              aria-expanded={openProcedureCombobox}
                              className="h-8 w-full justify-between text-xs sm:h-10 sm:text-sm"
                            >
                              {(formData.integrationConfig as FlowProcedureConfig)?.procedureName || "프로시저 선택"}
                              <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 sm:text-sm" />
                              <CommandList>
                                <CommandEmpty className="text-xs sm:text-sm">
                                  프로시저를 찾을 수 없습니다.
                                </CommandEmpty>
                                <CommandGroup>
                                  {procedureList.map((proc) => (
                                    <CommandItem
                                      key={`${proc.schema}.${proc.name}`}
                                      value={proc.name}
                                      onSelect={async () => {
                                        const procConfig = formData.integrationConfig as FlowProcedureConfig;
                                        const newConfig: FlowProcedureConfig = {
                                          ...procConfig,
                                          procedureName: proc.name,
                                          procedureSchema: proc.schema,
                                          callType: proc.type === "PROCEDURE" ? "procedure" : "function",
                                          parameters: [],
                                        };
                                        setFormData({ ...formData, integrationConfig: newConfig });
                                        setOpenProcedureCombobox(false);

                                        setLoadingProcedureParams(true);
                                        try {
                                          const res = await getFlowProcedureParameters(
                                            proc.name,
                                            procConfig.dbSource,
                                            procConfig.connectionId,
                                            proc.schema,
                                          );
                                          if (res.success && res.data) {
                                            setProcedureParams(res.data);
                                            const mappedParams: FlowProcedureParam[] = res.data.map((p) => ({
                                              name: p.name,
                                              dataType: p.dataType,
                                              mode: p.mode,
                                              source: "record_field" as const,
                                              field: "",
                                              value: "",
                                            }));
                                            setFormData((prev) => ({
                                              ...prev,
                                              integrationConfig: {
                                                ...(prev.integrationConfig as FlowProcedureConfig),
                                                procedureName: proc.name,
                                                procedureSchema: proc.schema,
                                                callType: proc.type === "PROCEDURE" ? "procedure" : "function",
                                                parameters: mappedParams,
                                              },
                                            }));
                                          }
                                        } catch (e) {
                                          console.error("파라미터 조회 실패:", e);
                                        } finally {
                                          setLoadingProcedureParams(false);
                                        }
                                      }}
                                      className="text-xs sm:text-sm"
                                    >
                                      <Check
                                        className={cn(
                                          "mr-2 h-4 w-4",
                                          (formData.integrationConfig as FlowProcedureConfig)?.procedureName === proc.name
                                            ? "opacity-100"
                                            : "opacity-0",
                                        )}
                                      />
                                      <div className="flex flex-col">
                                        <span className="font-medium">{proc.name}</span>
                                        <span className="text-[10px] text-muted-foreground">
                                          {proc.type} | {proc.schema}
                                          {proc.returnType ? ` | 반환: ${proc.returnType}` : ""}
                                        </span>
                                      </div>
                                    </CommandItem>
                                  ))}
                                </CommandGroup>
                              </CommandList>
                            </Command>
                          </PopoverContent>
                        </Popover>
                      )}
                      {procedureList.length === 0 && !loadingProcedures && (
                        <Button
                          variant="outline"
                          size="sm"
                          className="mt-2"
                          onClick={async () => {
                            const procConfig = formData.integrationConfig as FlowProcedureConfig;
                            setLoadingProcedures(true);
                            try {
                              const res = await getFlowProcedures(
                                procConfig.dbSource,
                                procConfig.connectionId,
                              );
                              if (res.success && res.data) setProcedureList(res.data);
                            } catch (e) {
                              console.error("프로시저 목록 조회 실패:", e);
                            } finally {
                              setLoadingProcedures(false);
                            }
                          }}
                        >
                          프로시저 목록 새로고침
                        </Button>
                      )}
                    </div>

                    {/* 호출 타입 */}
                    {(formData.integrationConfig as FlowProcedureConfig)?.procedureName && (
                      <div>
                        <Label>호출 타입</Label>
                        <Select
                          value={(formData.integrationConfig as FlowProcedureConfig)?.callType || "function"}
                          onValueChange={(value: "procedure" | "function") => {
                            setFormData({
                              ...formData,
                              integrationConfig: {
                                ...(formData.integrationConfig as FlowProcedureConfig),
                                callType: value,
                              },
                            });
                          }}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="procedure">
                              <div>
                                <div className="font-medium">CALL (프로시저)</div>
                                <div className="text-xs text-muted-foreground">CALL procedure_name()</div>
                              </div>
                            </SelectItem>
                            <SelectItem value="function">
                              <div>
                                <div className="font-medium">SELECT (함수)</div>
                                <div className="text-xs text-muted-foreground">SELECT function_name()</div>
                              </div>
                            </SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    )}

                    {/* 파라미터 매핑 테이블 */}
                    {(formData.integrationConfig as FlowProcedureConfig)?.procedureName && (
                      <div>
                        <Label>파라미터 매핑</Label>
                        {loadingProcedureParams ? (
                          <div className="py-2 text-sm text-muted-foreground">파라미터 로딩 중...</div>
                        ) : (formData.integrationConfig as FlowProcedureConfig)?.parameters?.length === 0 ? (
                          <div className="rounded-md bg-muted p-3">
                            <p className="text-sm text-muted-foreground">파라미터가 없는 프로시저입니다.</p>
                          </div>
                        ) : (
                          <div className="space-y-3">
                            {(formData.integrationConfig as FlowProcedureConfig)?.parameters?.map((param, idx) => (
                              <div key={idx} className="rounded-md border p-3 space-y-2">
                                <div className="flex items-center justify-between">
                                  <span className="text-sm font-medium">{param.name}</span>
                                  <span className="text-xs text-muted-foreground">
                                    {param.dataType} | {param.mode}
                                  </span>
                                </div>
                                {param.mode !== "OUT" && (
                                  <div className="grid grid-cols-2 gap-2">
                                    <div>
                                      <Label className="text-xs">소스</Label>
                                      <Select
                                        value={param.source}
                                        onValueChange={(value: "record_field" | "static" | "step_variable") => {
                                          const params = [...(formData.integrationConfig as FlowProcedureConfig).parameters];
                                          params[idx] = { ...params[idx], source: value };
                                          setFormData({
                                            ...formData,
                                            integrationConfig: {
                                              ...(formData.integrationConfig as FlowProcedureConfig),
                                              parameters: params,
                                            },
                                          });
                                        }}
                                      >
                                        <SelectTrigger className="h-8 text-xs">
                                          <SelectValue />
                                        </SelectTrigger>
                                        <SelectContent>
                                          <SelectItem value="record_field">레코드 필드</SelectItem>
                                          <SelectItem value="static">고정값</SelectItem>
                                          <SelectItem value="step_variable">스텝 변수</SelectItem>
                                        </SelectContent>
                                      </Select>
                                    </div>
                                    <div>
                                      <Label className="text-xs">
                                        {param.source === "static" ? "값" : "필드명"}
                                      </Label>
                                      <Input
                                        className="h-8 text-xs"
                                        placeholder={param.source === "static" ? "고정값 입력" : "컬럼명 입력"}
                                        value={param.source === "static" ? param.value || "" : param.field || ""}
                                        onChange={(e) => {
                                          const params = [...(formData.integrationConfig as FlowProcedureConfig).parameters];
                                          if (param.source === "static") {
                                            params[idx] = { ...params[idx], value: e.target.value };
                                          } else {
                                            params[idx] = { ...params[idx], field: e.target.value };
                                          }
                                          setFormData({
                                            ...formData,
                                            integrationConfig: {
                                              ...(formData.integrationConfig as FlowProcedureConfig),
                                              parameters: params,
                                            },
                                          });
                                        }}
                                      />
                                    </div>
                                  </div>
                                )}
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    )}

                    <div className="rounded-md bg-primary/10 p-3">
                      <p className="text-sm text-primary">
                        프로시저는 데이터 이동 전에 실행됩니다.
                        <br />실패 시 데이터 이동도 함께 롤백됩니다.
                      </p>
                    </div>
                  </>
                )}
              </div>
            )}
          </CardContent>
        </Card>

        {/* 🆕 표시 설정 */}
        <Card>
          <CardHeader>
            <CardTitle>표시 설정</CardTitle>
            <CardDescription>플로우 위젯에서 이 단계의 데이터를 표시할 때 보여줄 컬럼을 선택합니다</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {loadingAvailableColumns ? (
              <div className="text-muted-foreground flex items-center justify-center py-8 text-sm">
                컬럼 목록을 불러오는 중...
              </div>
            ) : availableColumns.length === 0 ? (
              <div className="rounded-md bg-amber-50 p-4 text-center">
                <p className="text-sm text-yellow-900">
                  ⚠️ 테이블의 컬럼 목록을 불러올 수 없습니다.
                  <br />
                  플로우 테이블:{" "}
                  <span className="font-mono font-semibold">{formData.tableName || flowTableName || "없음"}</span>
                  <br />
                  <span className="text-xs">
                    테이블이 존재하지 않거나, 컬럼이 없거나, 접근 권한이 없을 수 있습니다.
                  </span>
                </p>
              </div>
            ) : (
              <>
                <div>
                  <Label>표시할 컬럼 선택</Label>
                  <p className="text-muted-foreground mb-2 text-xs">선택하지 않으면 모든 컬럼이 표시됩니다</p>
                  <div className="max-h-64 space-y-2 overflow-y-auto rounded-md border p-3">
                    <div className="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        id="select-all-columns"
                        checked={formData.displayConfig.visibleColumns?.length === availableColumns.length}
                        onChange={(e) => {
                          setFormData({
                            ...formData,
                            displayConfig: {
                              ...formData.displayConfig,
                              visibleColumns: e.target.checked ? [...availableColumns] : [],
                            },
                          });
                        }}
                        className="h-4 w-4"
                      />
                      <label htmlFor="select-all-columns" className="text-sm font-medium">
                        전체 선택/해제
                      </label>
                    </div>
                    <div className="border-t pt-2" />
                    {availableColumns.map((colName) => (
                      <div key={colName} className="flex items-center space-x-2">
                        <input
                          type="checkbox"
                          id={`col-${colName}`}
                          checked={formData.displayConfig.visibleColumns?.includes(colName) || false}
                          onChange={(e) => {
                            const currentColumns = formData.displayConfig.visibleColumns || [];
                            const newColumns = e.target.checked
                              ? [...currentColumns, colName]
                              : currentColumns.filter((c) => c !== colName);

                            setFormData({
                              ...formData,
                              displayConfig: {
                                ...formData.displayConfig,
                                visibleColumns: newColumns,
                              },
                            });
                          }}
                          className="h-4 w-4"
                        />
                        <label htmlFor={`col-${colName}`} className="cursor-pointer font-mono text-sm">
                          {colName}
                        </label>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="rounded-md bg-primary/10 p-3">
                  <p className="text-sm text-primary">
                    💡 선택된 컬럼: {formData.displayConfig.visibleColumns?.length || 0}개
                    {formData.displayConfig.visibleColumns?.length === 0 && " (모든 컬럼이 표시됩니다)"}
                  </p>
                </div>
              </>
            )}
          </CardContent>
        </Card>

        {/* 액션 버튼 */}
        <div className="flex gap-2">
          <Button className="flex-1" onClick={handleSave}>
            <Save className="mr-2 h-4 w-4" />
            저장
          </Button>
          <Button variant="destructive" onClick={handleDelete}>
            <Trash2 className="h-4 w-4" />
          </Button>
        </div>
      </div>
    </div>
  );
}
