'use client';

import React, { memo } from 'react';
import { ReactFlow, Background, BackgroundVariant, MiniMap, NodeTypes } from '@xyflow/react';
import '@xyflow/react/dist/style.css';

import { AppNode } from '../nodes/AppNode';
import { AppNodeType } from '../types/node';

const nodeTypes: NodeTypes = {
  appNode: AppNode,
};

interface CanvasNodesProps {
  nodes: AppNodeType[];
  edges: any[];
  onNodesChange: (changes: any[]) => void;
  onEdgesChange: (changes: any[]) => void;
  onConnect: (params: any) => void;
  isValidConnection?: (connection: any) => boolean;
  onNodeDrag?: (event: any, node: any, nodes: any[]) => void;
  onNodeDragStart?: (event: any, node: any) => void;
  onNodeContextMenu?: (event: React.MouseEvent, node: AppNodeType) => void;
  onEdgeContextMenu?: (event: React.MouseEvent, edge: any) => void;
  onPaneContextMenu?: (event: React.MouseEvent | MouseEvent) => void;
  onPaneClick?: () => void;
  onDoubleClick?: (event: React.MouseEvent) => void;
  defaultEdgeOptions?: any;
  isMiniMapOpen?: boolean;
}

function CanvasNodesComponent({
  nodes,
  edges,
  onNodesChange,
  onEdgesChange,
  onConnect,
  isValidConnection,
  onNodeDrag,
  onNodeDragStart,
  onNodeContextMenu,
  onEdgeContextMenu,
  onPaneContextMenu,
  onPaneClick,
  onDoubleClick,
  defaultEdgeOptions,
  isMiniMapOpen = false,
}: CanvasNodesProps) {
  return (
    <ReactFlow
      nodes={nodes.filter((n) => n.type === 'appNode')}
      edges={edges}
      onNodesChange={onNodesChange}
      onEdgesChange={onEdgesChange}
      onConnect={onConnect}
      isValidConnection={isValidConnection}
      onNodeDrag={onNodeDrag}
      onNodeDragStart={onNodeDragStart}
      onNodeContextMenu={onNodeContextMenu}
      onEdgeContextMenu={onEdgeContextMenu}
      onPaneContextMenu={onPaneContextMenu}
      onPaneClick={onPaneClick}
      onDoubleClick={onDoubleClick}
      nodeTypes={nodeTypes}
      defaultViewport={{ x: 0, y: 0, zoom: 0.75 }}
      className="bg-black"
      colorMode="dark"
      minZoom={0.1}
      maxZoom={4}
      defaultEdgeOptions={defaultEdgeOptions}
      proOptions={{ hideAttribution: true }}
      connectionLineStyle={{ stroke: 'rgba(255,255,255,0.8)', strokeWidth: 2 }}
    >
      <Background
        variant={BackgroundVariant.Dots}
        gap={32}
        size={1}
        color="#aaa"
        className="opacity-[0.06]"
      />
      {isMiniMapOpen && (
        <MiniMap
          position="bottom-left"
          style={{ width: 240, height: 140 }}
          className="!left-6 !bottom-20 !m-0 bg-black/40 backdrop-blur-md border border-white/10 rounded-xl overflow-hidden shadow-xl z-50 animate-in fade-in slide-in-from-bottom-4 duration-300"
          nodeColor={() => '#3b82f6'}
          maskColor="rgba(0, 0, 0, 0.6)"
          nodeStrokeColor="transparent"
          nodeBorderRadius={4}
          zoomable
          pannable
        />
      )}
    </ReactFlow>
  );
}

export const CanvasNodes = memo(CanvasNodesComponent);
