"use client";

/**
 * 필드 매핑 노드
 */

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

export const FieldMappingNode = memo(({ data, selected }: NodeProps<FieldMappingNodeData>) => {
  return (
    <div
      className={`min-w-[250px] rounded-lg border-2 bg-white shadow-md transition-all ${
        selected ? "border-purple-500 shadow-lg" : "border-gray-200"
      }`}
    >
      {/* 입력 핸들 */}
      <Handle type="target" position={Position.Left} className="!h-3 !w-3 !border-2 !border-purple-500 !bg-white" />

      {/* 헤더 */}
      <div className="flex items-center gap-2 rounded-t-lg bg-purple-500 px-3 py-2 text-white">
        <ArrowLeftRight className="h-4 w-4" />
        <div className="flex-1">
          <div className="text-sm font-semibold">필드 매핑</div>
          <div className="text-xs opacity-80">{data.displayName || "데이터 매핑"}</div>
        </div>
      </div>

      {/* 본문 */}
      <div className="p-3">
        {data.mappings && data.mappings.length > 0 ? (
          <div className="space-y-1">
            <div className="text-xs font-medium text-gray-700">매핑 규칙: ({data.mappings.length}개)</div>
            <div className="max-h-[150px] space-y-1 overflow-y-auto">
              {data.mappings.slice(0, 5).map((mapping) => (
                <div key={mapping.id} className="rounded bg-gray-50 px-2 py-1 text-xs">
                  <div className="flex items-center justify-between">
                    <span className="font-mono text-gray-600">{mapping.sourceField || "정적값"}</span>
                    <span className="text-purple-500">→</span>
                    <span className="font-mono text-gray-700">{mapping.targetField}</span>
                  </div>
                  {mapping.transform && <div className="mt-0.5 text-xs text-gray-400">변환: {mapping.transform}</div>}
                  {mapping.staticValue !== undefined && (
                    <div className="mt-0.5 text-xs text-gray-400">값: {String(mapping.staticValue)}</div>
                  )}
                </div>
              ))}
              {data.mappings.length > 5 && (
                <div className="text-xs text-gray-400">... 외 {data.mappings.length - 5}개</div>
              )}
            </div>
          </div>
        ) : (
          <div className="text-center text-xs text-gray-400">매핑 규칙 없음</div>
        )}
      </div>

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

FieldMappingNode.displayName = "FieldMappingNode";
