"use client";

/**
 * 외부 DB 소스 노드
 */

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

const DB_TYPE_COLORS: Record<string, string> = {
  PostgreSQL: "#336791",
  MySQL: "#4479A1",
  Oracle: "#F80000",
  MSSQL: "#CC2927",
  MariaDB: "#003545",
};

const DB_TYPE_ICONS: Record<string, string> = {
  PostgreSQL: "🐘",
  MySQL: "🐬",
  Oracle: "🔴",
  MSSQL: "🟦",
  MariaDB: "🦭",
};

export const ExternalDBSourceNode = memo(({ data, selected }: NodeProps<ExternalDBSourceNodeData>) => {
  const dbColor = (data.dbType && DB_TYPE_COLORS[data.dbType]) || "#F59E0B";
  const dbIcon = (data.dbType && DB_TYPE_ICONS[data.dbType]) || "🔌";

  return (
    <div
      className={`min-w-[250px] rounded-lg border-2 bg-white shadow-md transition-all ${
        selected ? "border-orange-500 shadow-lg" : "border-gray-200"
      }`}
    >
      {/* 헤더 */}
      <div className="flex items-center gap-2 rounded-t-lg px-3 py-2 text-white" style={{ backgroundColor: dbColor }}>
        <Plug className="h-4 w-4" />
        <div className="flex-1">
          <div className="text-sm font-semibold">{data.displayName || data.connectionName}</div>
          <div className="text-xs opacity-80">{data.tableName}</div>
        </div>
        <span className="text-lg">{dbIcon}</span>
      </div>

      {/* 본문 */}
      <div className="p-3">
        <div className="mb-2 flex items-center gap-1 text-xs">
          <div className="rounded bg-orange-100 px-2 py-0.5 font-medium text-orange-700">{data.dbType || "DB"}</div>
          <div className="flex-1 text-gray-500">외부 DB</div>
        </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" style={{ backgroundColor: dbColor }} />
                  <span className="font-mono">{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 !bg-white"
        style={{ borderColor: dbColor }}
      />
    </div>
  );
});

ExternalDBSourceNode.displayName = "ExternalDBSourceNode";
