"use client";

/**
 * 조건 분기 노드
 */

import { memo } from "react";
import { Handle, Position, NodeProps } from "reactflow";
import { Zap, Check, X } from "lucide-react";
import type { ConditionNodeData } from "@/types/node-editor";

const OPERATOR_LABELS: Record<string, string> = {
  EQUALS: "=",
  NOT_EQUALS: "≠",
  GREATER_THAN: ">",
  LESS_THAN: "<",
  GREATER_THAN_OR_EQUAL: "≥",
  LESS_THAN_OR_EQUAL: "≤",
  LIKE: "포함",
  NOT_LIKE: "미포함",
  IN: "IN",
  NOT_IN: "NOT IN",
  IS_NULL: "NULL",
  IS_NOT_NULL: "NOT NULL",
  EXISTS_IN: "EXISTS IN",
  NOT_EXISTS_IN: "NOT EXISTS IN",
};

// EXISTS 계열 연산자인지 확인
const isExistsOperator = (operator: string): boolean => {
  return operator === "EXISTS_IN" || operator === "NOT_EXISTS_IN";
};

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

      {/* 헤더 */}
      <div className="flex items-center gap-2 rounded-t-lg bg-amber-500 px-3 py-2 text-white">
        <Zap 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.conditions && data.conditions.length > 0 ? (
          <div className="space-y-2">
            <div className="text-xs font-medium text-foreground">조건식: ({data.conditions.length}개)</div>
            <div className="max-h-[150px] space-y-1.5 overflow-y-auto">
              {data.conditions.slice(0, 4).map((condition, idx) => (
                <div key={idx} className="rounded bg-amber-50 px-2 py-1.5 text-xs">
                  {idx > 0 && (
                    <div className="mb-1 text-center text-xs font-semibold text-amber-600">{data.logic}</div>
                  )}
                  <div className="flex flex-wrap items-center gap-1">
                    <span className="font-mono text-foreground">{condition.field}</span>
                    <span
                      className={`rounded px-1 py-0.5 ${
                        isExistsOperator(condition.operator)
                          ? "bg-purple-200 text-purple-800"
                          : "bg-yellow-200 text-yellow-800"
                      }`}
                    >
                      {OPERATOR_LABELS[condition.operator] || condition.operator}
                    </span>
                    {/* EXISTS 연산자인 경우 테이블.필드 표시 */}
                    {isExistsOperator(condition.operator) ? (
                      <span className="text-purple-600">
                        {(condition as any).lookupTableLabel || (condition as any).lookupTable || "..."}
                        {(condition as any).lookupField && `.${(condition as any).lookupFieldLabel || (condition as any).lookupField}`}
                      </span>
                    ) : (
                      // 일반 연산자인 경우 값 표시
                      condition.value !== null &&
                      condition.value !== undefined && (
                        <span className="text-muted-foreground">
                          {typeof condition.value === "string" ? `"${condition.value}"` : String(condition.value)}
                        </span>
                      )
                    )}
                  </div>
                </div>
              ))}
              {data.conditions.length > 4 && (
                <div className="text-xs text-muted-foreground/70">... 외 {data.conditions.length - 4}개</div>
              )}
            </div>
          </div>
        ) : (
          <div className="text-center text-xs text-muted-foreground/70">조건 없음</div>
        )}
      </div>

      {/* 분기 출력 핸들 */}
      <div className="relative border-t">
        {/* TRUE 출력 - 오른쪽 위 */}
        <div className="relative border-b p-2">
          <div className="flex items-center justify-end gap-1 pr-6 text-xs">
            <Check className="h-3 w-3 text-emerald-600" />
            <span className="font-medium text-emerald-600">TRUE</span>
          </div>
          <Handle
            type="source"
            position={Position.Right}
            id="true"
            className="!top-1/2 !-right-1.5 !h-3 !w-3 !-translate-y-1/2 !border-2 !border-emerald-500 !bg-white"
          />
        </div>

        {/* FALSE 출력 - 오른쪽 아래 */}
        <div className="relative p-2">
          <div className="flex items-center justify-end gap-1 pr-6 text-xs">
            <X className="h-3 w-3 text-destructive" />
            <span className="font-medium text-destructive">FALSE</span>
          </div>
          <Handle
            type="source"
            position={Position.Right}
            id="false"
            className="!top-1/2 !-right-1.5 !h-3 !w-3 !-translate-y-1/2 !border-2 !border-destructive !bg-white"
          />
        </div>
      </div>
    </div>
  );
});

ConditionNode.displayName = "ConditionNode";
