"use client";

import React, { useState, useCallback, useEffect, useRef } from "react";
import toast from "react-hot-toast";
import {
  ReactFlow,
  Node,
  Edge,
  Controls,
  Background,
  useNodesState,
  useEdgesState,
  BackgroundVariant,
  SelectionMode,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import { TableNode } from "./TableNode";
import { TableSelector } from "./TableSelector";
import { ConnectionSetupModal } from "./ConnectionSetupModal";
import { TableDefinition } from "@/lib/api/dataflow";

// 테이블 노드 데이터 타입 정의
interface TableNodeData extends Record<string, unknown> {
  table: {
    tableName: string;
    displayName: string;
    description: string;
    columns: Array<{
      name: string;
      type: string;
      description: string;
    }>;
  };
  onColumnClick: (tableName: string, columnName: string) => void;
  selectedColumns: string[];
}

// 노드 및 엣지 타입 정의
const nodeTypes = {
  tableNode: TableNode,
};

const edgeTypes = {};

interface DataFlowDesignerProps {
  companyCode: string;
  onSave?: (relationships: TableRelationship[]) => void;
}

interface TableRelationship {
  relationshipId?: number;
  relationshipName: string;
  fromTableName: string;
  fromColumnName: string;
  toTableName: string;
  toColumnName: string;
  relationshipType: "one-to-one" | "one-to-many" | "many-to-one" | "many-to-many";
  connectionType: "simple-key" | "data-save" | "external-call";
  settings?: Record<string, unknown>;
  companyCode: string;
  isActive?: string;
}

export const DataFlowDesigner: React.FC<DataFlowDesignerProps> = ({ companyCode, onSave }) => {
  const [nodes, setNodes, onNodesChange] = useNodesState<Node<TableNodeData>>([]);
  const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>([]);
  const [selectedColumns, setSelectedColumns] = useState<{
    [tableName: string]: string[];
  }>({});
  const [selectionOrder, setSelectionOrder] = useState<string[]>([]);
  const [selectedNodes, setSelectedNodes] = useState<string[]>([]);
  const [pendingConnection, setPendingConnection] = useState<{
    fromNode: { id: string; tableName: string; displayName: string };
    toNode: { id: string; tableName: string; displayName: string };
    fromColumn?: string;
    toColumn?: string;
    selectedColumnsData?: {
      [tableName: string]: {
        displayName: string;
        columns: string[];
      };
    };
  } | null>(null);
  const toastShownRef = useRef(false);

  // 키보드 이벤트 핸들러 (Del 키로 선택된 노드 삭제)
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Delete" && selectedNodes.length > 0) {
        // 선택된 노드들 삭제
        setNodes((prevNodes) => prevNodes.filter((node) => !selectedNodes.includes(node.id)));

        // 삭제된 노드들과 관련된 선택된 컬럼들도 정리
        const deletedTableNames = selectedNodes
          .filter((nodeId) => nodeId.startsWith("table-"))
          .map((nodeId) => nodeId.replace("table-", ""));

        setSelectedColumns((prev) => {
          const newColumns = { ...prev };
          deletedTableNames.forEach((tableName) => {
            delete newColumns[tableName];
          });
          return newColumns;
        });

        // 선택 순서도 정리
        setSelectionOrder((prev) => prev.filter((tableName) => !deletedTableNames.includes(tableName)));

        // 선택된 노드 초기화
        setSelectedNodes([]);

        toast.success(`${selectedNodes.length}개 테이블이 삭제되었습니다.`);
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [selectedNodes, setNodes]);

  // 노드 선택 변경 핸들러
  const onSelectionChange = useCallback(({ nodes }: { nodes: Node<TableNodeData>[] }) => {
    const selectedNodeIds = nodes.map((node) => node.id);
    setSelectedNodes(selectedNodeIds);
  }, []);

  // 빈 onConnect 함수 (드래그 연결 비활성화)
  const onConnect = useCallback(() => {
    // 드래그로 연결하는 것을 방지
    return;
  }, []);

  // 컬럼 클릭 처리 (토글 방식, 최대 2개 테이블만 허용)
  const handleColumnClick = useCallback((tableName: string, columnName: string) => {
    setSelectedColumns((prev) => {
      const currentColumns = prev[tableName] || [];
      const isSelected = currentColumns.includes(columnName);
      const selectedTables = Object.keys(prev).filter((name) => prev[name] && prev[name].length > 0);

      if (isSelected) {
        // 선택 해제
        const newColumns = currentColumns.filter((column) => column !== columnName);
        if (newColumns.length === 0) {
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          const { [tableName]: removed, ...rest } = prev;
          // 선택 순서에서도 제거 (다음 렌더링에서)
          setTimeout(() => {
            setSelectionOrder((order) => order.filter((name) => name !== tableName));
          }, 0);
          return rest;
        }
        return { ...prev, [tableName]: newColumns };
      } else {
        // 선택 추가 - 새로운 테이블이고 이미 2개 테이블이 선택되어 있으면 거부
        if (!prev[tableName] && selectedTables.length >= 2) {
          // 토스트 중복 방지를 위한 ref 사용
          if (!toastShownRef.current) {
            toastShownRef.current = true;
            setTimeout(() => {
              toast.error("최대 2개의 테이블에서만 컬럼을 선택할 수 있습니다.", {
                duration: 3000,
                position: "top-center",
              });
              // 3초 후 플래그 리셋
              setTimeout(() => {
                toastShownRef.current = false;
              }, 3000);
            }, 0);
          }
          return prev;
        }

        // 새로운 테이블이면 선택 순서에 추가, 기존 테이블이면 맨 뒤로 이동 (다음 렌더링에서)
        setTimeout(() => {
          setSelectionOrder((order) => {
            // 기존에 있던 테이블이면 제거 후 맨 뒤에 추가 (순서 갱신)
            const filteredOrder = order.filter((name) => name !== tableName);
            return [...filteredOrder, tableName];
          });
        }, 0);

        return { ...prev, [tableName]: [...currentColumns, columnName] };
      }
    });
  }, []);

  // 선택된 컬럼이 변경될 때마다 기존 노드들 업데이트 및 selectionOrder 정리
  useEffect(() => {
    setNodes((prevNodes) =>
      prevNodes.map((node) => ({
        ...node,
        data: {
          ...node.data,
          selectedColumns: selectedColumns[node.data.table.tableName] || [],
        },
      })),
    );

    // selectionOrder에서 선택되지 않은 테이블들 제거
    const activeTables = Object.keys(selectedColumns).filter(
      (tableName) => selectedColumns[tableName] && selectedColumns[tableName].length > 0,
    );
    setSelectionOrder((prev) => prev.filter((tableName) => activeTables.includes(tableName)));
  }, [selectedColumns, setNodes]);

  // 연결 가능한 상태인지 확인
  const canCreateConnection = () => {
    const selectedTables = Object.keys(selectedColumns).filter(
      (tableName) => selectedColumns[tableName] && selectedColumns[tableName].length > 0,
    );

    // 최소 2개의 서로 다른 테이블에서 컬럼이 선택되어야 함
    return selectedTables.length >= 2;
  };

  // 컬럼 연결 설정 모달 열기
  const openConnectionModal = () => {
    const selectedTables = Object.keys(selectedColumns).filter(
      (tableName) => selectedColumns[tableName] && selectedColumns[tableName].length > 0,
    );

    if (selectedTables.length < 2) return;

    // 선택 순서에 따라 첫 번째와 두 번째 테이블 설정
    const orderedTables = selectionOrder.filter((name) => selectedTables.includes(name));
    const firstTableName = orderedTables[0];
    const secondTableName = orderedTables[1];
    const firstNode = nodes.find((node) => node.data.table.tableName === firstTableName);
    const secondNode = nodes.find((node) => node.data.table.tableName === secondTableName);

    if (!firstNode || !secondNode) return;

    setPendingConnection({
      fromNode: {
        id: firstNode.id,
        tableName: firstNode.data.table.tableName,
        displayName: firstNode.data.table.displayName,
      },
      toNode: {
        id: secondNode.id,
        tableName: secondNode.data.table.tableName,
        displayName: secondNode.data.table.displayName,
      },
      // 선택된 모든 컬럼 정보를 선택 순서대로 전달
      selectedColumnsData: (() => {
        const orderedData: { [key: string]: { displayName: string; columns: string[] } } = {};
        // selectionOrder 순서대로 데이터 구성 (첫 번째 선택이 먼저)
        orderedTables.forEach((tableName) => {
          const node = nodes.find((n) => n.data.table.tableName === tableName);
          if (node && selectedColumns[tableName]) {
            orderedData[tableName] = {
              displayName: node.data.table.displayName,
              columns: selectedColumns[tableName],
            };
          }
        });
        return orderedData;
      })(),
    });
  };

  // 실제 테이블 노드 추가
  const addTableNode = useCallback(
    async (table: TableDefinition) => {
      try {
        const newNode: Node<TableNodeData> = {
          id: `table-${table.tableName}`,
          type: "tableNode",
          position: { x: Math.random() * 300, y: Math.random() * 200 },
          data: {
            table: {
              tableName: table.tableName,
              displayName: table.displayName || table.tableName,
              description: table.description || "",
              columns: table.columns.map((col) => ({
                name: col.columnName || "unknown",
                type: col.dataType || col.dbType || "UNKNOWN",
                description:
                  col.columnLabel || col.displayName || col.description || col.columnName || "No description",
              })),
            },
            onColumnClick: handleColumnClick,
            selectedColumns: selectedColumns[table.tableName] || [],
          },
        };

        setNodes((nds) => nds.concat(newNode));
      } catch (error) {
        console.error("테이블 노드 추가 실패:", error);
        toast.error("테이블 정보를 불러오는데 실패했습니다.");
      }
    },
    [handleColumnClick, selectedColumns, setNodes],
  );

  // 샘플 테이블 노드 추가 (개발용)
  const addSampleNode = useCallback(() => {
    const tableName = `sample_table_${nodes.length + 1}`;
    const newNode: Node<TableNodeData> = {
      id: `sample-${Date.now()}`,
      type: "tableNode",
      position: { x: Math.random() * 300, y: Math.random() * 200 },
      data: {
        table: {
          tableName,
          displayName: `샘플 테이블 ${nodes.length + 1}`,
          description: `샘플 테이블 설명 ${nodes.length + 1}`,
          columns: [
            { name: "id", type: "INTEGER", description: "고유 식별자" },
            { name: "name", type: "VARCHAR(100)", description: "이름" },
            { name: "code", type: "VARCHAR(50)", description: "코드" },
            { name: "created_date", type: "TIMESTAMP", description: "생성일시" },
          ],
        },
        onColumnClick: handleColumnClick,
        selectedColumns: selectedColumns[tableName] || [],
      },
    };

    setNodes((nds) => nds.concat(newNode));
  }, [nodes.length, handleColumnClick, selectedColumns, setNodes]);

  // 노드 전체 삭제
  const clearNodes = useCallback(() => {
    setNodes([]);
    setEdges([]);
    setSelectedColumns({});
    setSelectionOrder([]);
    setSelectedNodes([]);
  }, [setNodes, setEdges]);

  // 현재 추가된 테이블명 목록 가져오기
  const getSelectedTableNames = useCallback(() => {
    return nodes.filter((node) => node.id.startsWith("table-")).map((node) => node.data.table.tableName);
  }, [nodes]);

  // 연결 설정 확인
  const handleConfirmConnection = useCallback(
    (config: { relationshipType: string; connectionType: string; relationshipName: string }) => {
      if (!pendingConnection) return;

      const newEdge = {
        id: `edge-${Date.now()}`,
        source: pendingConnection.fromNode.id,
        target: pendingConnection.toNode.id,
        type: "default",
        data: {
          relationshipType: config.relationshipType,
          connectionType: config.connectionType,
          label: config.relationshipName,
        },
      };

      setEdges((eds) => [...eds, newEdge]);
      setPendingConnection(null);

      // TODO: 백엔드 API 호출하여 관계 저장
      console.log("연결 설정:", config);
    },
    [pendingConnection, setEdges],
  );

  // 연결 설정 취소
  const handleCancelConnection = useCallback(() => {
    setPendingConnection(null);
  }, []);

  return (
    <div className="data-flow-designer h-screen bg-gray-100">
      <div className="flex h-full">
        {/* 사이드바 */}
        <div className="w-80 border-r border-gray-200 bg-white shadow-lg">
          <div className="p-6">
            <h2 className="mb-6 text-xl font-bold text-gray-800">테이블 간 데이터 관계 설정</h2>

            {/* 테이블 선택기 */}
            <TableSelector
              companyCode={companyCode}
              onTableAdd={addTableNode}
              selectedTables={getSelectedTableNames()}
            />

            {/* 컨트롤 버튼들 */}
            <div className="space-y-3">
              <button
                onClick={addSampleNode}
                className="w-full rounded-lg bg-gray-500 p-3 font-medium text-white transition-colors hover:bg-gray-600"
              >
                + 샘플 테이블 추가 (개발용)
              </button>

              <button
                onClick={clearNodes}
                className="w-full rounded-lg bg-red-500 p-3 font-medium text-white transition-colors hover:bg-red-600"
              >
                전체 삭제
              </button>

              <button
                onClick={() => onSave && onSave([])}
                className="w-full rounded-lg bg-green-500 p-3 font-medium text-white transition-colors hover:bg-green-600"
              >
                저장
              </button>
            </div>

            {/* 통계 정보 */}
            <div className="mt-6 rounded-lg bg-gray-50 p-4">
              <div className="mb-2 text-sm font-semibold text-gray-700">통계</div>
              <div className="space-y-1 text-sm text-gray-600">
                <div className="flex justify-between">
                  <span>테이블 노드:</span>
                  <span className="font-medium">{nodes.length}개</span>
                </div>
                <div className="flex justify-between">
                  <span>연결:</span>
                  <span className="font-medium">{edges.length}개</span>
                </div>
              </div>
            </div>

            {/* 선택된 컬럼 정보 */}
            {Object.keys(selectedColumns).length > 0 && (
              <div className="mt-6 space-y-4">
                <div className="rounded-lg border border-blue-200 bg-blue-50 p-4">
                  <div className="mb-3 text-sm font-semibold text-blue-800">선택된 컬럼</div>
                  <div className="space-y-3">
                    {[...new Set(selectionOrder)]
                      .filter((tableName) => selectedColumns[tableName] && selectedColumns[tableName].length > 0)
                      .map((tableName, index, filteredOrder) => {
                        const columns = selectedColumns[tableName];
                        const node = nodes.find((n) => n.data.table.tableName === tableName);
                        const displayName = node?.data.table.displayName || tableName;

                        return (
                          <div key={`selected-${tableName}-${index}`}>
                            <div className="w-full min-w-0 rounded-lg border border-blue-300 bg-white p-3">
                              <div className="mb-2 flex flex-wrap items-center gap-2">
                                <div className="flex-shrink-0 rounded px-2 py-1 text-xs font-medium text-blue-600">
                                  {displayName}
                                </div>
                              </div>
                              <div className="flex w-full min-w-0 flex-wrap gap-1">
                                {columns.map((column, columnIndex) => (
                                  <div
                                    key={`${tableName}-${column}-${columnIndex}`}
                                    className="max-w-full truncate rounded-full border border-blue-200 bg-blue-100 px-2 py-1 text-xs text-blue-800"
                                    title={column}
                                  >
                                    {column}
                                  </div>
                                ))}
                              </div>
                            </div>
                            {/* 첫 번째 테이블 다음에 화살표 표시 */}
                            {index === 0 && filteredOrder.length > 1 && (
                              <div className="flex justify-center py-2">
                                <div className="text-gray-400">↓</div>
                              </div>
                            )}
                          </div>
                        );
                      })}
                  </div>
                  <div className="mt-3 flex gap-2">
                    <button
                      onClick={openConnectionModal}
                      disabled={!canCreateConnection()}
                      className={`w-full rounded px-3 py-1 text-xs font-medium transition-colors ${
                        canCreateConnection()
                          ? "cursor-pointer bg-blue-600 text-white hover:bg-blue-700"
                          : "cursor-not-allowed bg-gray-300 text-gray-500"
                      }`}
                    >
                      컬럼 연결 설정
                    </button>
                    <button
                      onClick={() => {
                        setSelectedColumns({});
                        setSelectionOrder([]);
                      }}
                      className="w-full cursor-pointer rounded bg-gray-200 px-3 py-1 text-xs font-medium text-gray-600 hover:bg-gray-300"
                    >
                      선택 초기화
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* React Flow 캔버스 */}
        <div className="relative flex-1">
          <ReactFlow
            nodes={nodes}
            edges={edges}
            onNodesChange={onNodesChange}
            onEdgesChange={onEdgesChange}
            onConnect={onConnect}
            onSelectionChange={onSelectionChange}
            nodeTypes={nodeTypes}
            edgeTypes={edgeTypes}
            fitView
            attributionPosition="bottom-left"
            panOnScroll={false}
            zoomOnScroll={true}
            zoomOnPinch={true}
            panOnDrag={[1, 2]}
            selectionOnDrag={true}
            multiSelectionKeyCode={null}
            selectNodesOnDrag={false}
            selectionMode={SelectionMode.Partial}
          >
            <Controls />

            <Background variant={BackgroundVariant.Dots} gap={20} size={1} color="#E5E7EB" />
          </ReactFlow>

          {/* 안내 메시지 */}
          {nodes.length === 0 && (
            <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
              <div className="text-center text-gray-500">
                <div className="mb-2 text-2xl">📊</div>
                <div className="mb-1 text-lg font-medium">테이블 간 데이터 관계 설정을 시작하세요</div>
                <div className="text-sm">
                  <div>왼쪽 사이드바에서 테이블을 더블클릭하여 추가하세요</div>
                  <div className="mt-1 text-xs text-gray-400">테이블 선택 후 Del 키로 삭제 가능</div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 연결 설정 모달 */}
      <ConnectionSetupModal
        isOpen={!!pendingConnection}
        connection={pendingConnection}
        onConfirm={handleConfirmConnection}
        onCancel={handleCancelConnection}
      />
    </div>
  );
};
