"use client";

/**
 * 테이블 소스 노드
 */

import { memo } from "react";
import { Handle, Position, NodeProps } from "reactflow";
import { Database } from "lucide-react";
import type { TableSourceNodeData } from "@/types/node-editor";

export const TableSourceNode = memo(({ data, selected }: NodeProps<TableSourceNodeData>) => {
  // 디버깅: 필드 데이터 확인
  if (data.fields && data.fields.length > 0) {
    console.log("🔍 TableSource 필드 데이터:", data.fields);
  }

  return (
    <div
      className={`min-w-[250px] rounded-lg border-2 bg-white shadow-md transition-all ${
        selected ? "border-blue-500 shadow-lg" : "border-gray-200"
      }`}
    >
      {/* 헤더 */}
      <div className="flex items-center gap-2 rounded-t-lg bg-blue-500 px-3 py-2 text-white">
        <Database className="h-4 w-4" />
        <div className="flex-1">
          <div className="text-sm font-semibold">{data.displayName || data.tableName || "테이블 소스"}</div>
          {data.tableName && data.displayName !== data.tableName && (
            <div className="text-xs opacity-80">{data.tableName}</div>
          )}
        </div>
      </div>

      {/* 본문 */}
      <div className="p-3">
        <div className="mb-2 text-xs font-medium text-gray-500">📍 내부 데이터베이스</div>

        {/* 필드 목록 */}
        <div className="space-y-1">
          <div className="text-xs font-medium text-gray-700">출력 필드:</div>
          <div className="max-h-[150px] overflow-y-auto">
            {data.fields && data.fields.length > 0 ? (
              data.fields.slice(0, 5).map((field) => (
                <div key={field.name} className="flex items-center gap-2 text-xs text-gray-600">
                  <div className="h-1.5 w-1.5 rounded-full bg-blue-400" />
                  <span className="font-medium">{field.label || field.displayName || field.name}</span>
                  {(field.label || field.displayName) && field.label !== field.name && (
                    <span className="font-mono text-gray-400">({field.name})</span>
                  )}
                  <span className="text-gray-400">{field.type}</span>
                </div>
              ))
            ) : (
              <div className="text-xs text-gray-400">필드 없음</div>
            )}
            {data.fields && data.fields.length > 5 && (
              <div className="text-xs text-gray-400">... 외 {data.fields.length - 5}개</div>
            )}
          </div>
        </div>
      </div>

      {/* 출력 핸들 */}
      <Handle type="source" position={Position.Right} className="!h-3 !w-3 !border-2 !border-blue-500 !bg-white" />
    </div>
  );
});

TableSourceNode.displayName = "TableSourceNode";
