import { memo, useEffect } from 'react';
import { Handle, Position, NodeProps, useUpdateNodeInternals } from '@xyflow/react';
import {
  CheckCircle,
  AlertCircle,
  AlertTriangle,
  Circle,
  Settings,
  UserPlus,
  UserCog,
  Pencil,
  ShoppingCart,
  FileText,
  FileCheck,
  FilePlus,
  FilePenLine,
  Mail,
  Tag,
  UserCheck,
  Database,
  MessageSquare,
  Zap,
  Plus,
  GitBranch,
  type LucideIcon,
} from 'lucide-react';
import { Badge } from './ui/badge';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from './ui/tooltip';
import { WorkflowReactFlowNode as WorkflowNodeType } from '../types/reactflow';
import { cn } from '../lib/utils';
import NodeActionsMenu from './NodeActionsMenu';
import { ServiceIcon } from './ServiceIcon';

const iconMap: Record<string, LucideIcon> = {
  // User-related icons
  UserPlus,
  UserCog,
  Pencil,
  UserCheck,
  // Content-related icons
  FileText,
  FileCheck,
  FilePlus,
  FilePenLine,
  // Communication icons
  Mail,
  MessageSquare,
  // Other icons
  ShoppingCart,
  Tag,
  Database,
  Zap,
  Circle,
  Plus,
  GitBranch,
};

/**
 * Custom ReactFlow node component for workflow builder
 * Zapier-style design: clean cards with app icon, step number, and action name
 */
const WorkflowReactFlowNode = memo(({ id, data, selected, type }: NodeProps<WorkflowNodeType>) => {
  const Icon = iconMap[data.icon] || Circle;
  const updateNodeInternals = useUpdateNodeInternals();

  const handleEdit = () => {
    if (data.onEdit) data.onEdit(id);
  };

  const handleDelete = () => {
    if (data.onDelete) data.onDelete(id);
  };

  const handleDuplicate = () => {
    if (data.onDuplicate) data.onDuplicate(id);
  };

  const handleViewDataFields = () => {
    if (data.onViewDataFields) data.onViewDataFields(id);
  };

  // Check if this is a router (flow-control) node with multiple output handles
  const isRouter = data.actionType === 'router';
  const routerRoutes = isRouter
    ? ((data.config?.routes as Array<{ name: string; label?: string }>) || []).filter((r) => r.name)
    : [];

  // Notify React Flow when handles change so edges reconnect correctly
  useEffect(() => {
    if (isRouter) {
      updateNodeInternals(id);
    }
  }, [id, isRouter, routerRoutes.length, updateNodeInternals]);

  // Get status indicator - using Sequensy semantic colors
  const getStatusIndicator = () => {
    switch (data.status) {
      case 'valid':
        return <CheckCircle className="w-4 h-4 text-[var(--seq-success)]" />;
      case 'error':
        return <AlertCircle className="w-4 h-4 text-[var(--seq-error)]" />;
      case 'warning':
        return <AlertTriangle className="w-4 h-4 text-[var(--seq-warning)]" />;
      default:
        return <Settings className="w-4 h-4 text-[var(--seq-slate-400)] status-icon" />;
    }
  };

  // Get border/glow based on type - using Sequensy glow effects
  const getSelectionStyle = () => {
    if (!selected) return '';
    if (type === 'trigger') return 'border-[var(--seq-trigger)]/40 shadow-glow-trigger';
    if (type === 'operator' || isRouter) return 'border-[var(--seq-operator)]/40 shadow-glow-operator';
    return 'border-[var(--seq-action)]/40 shadow-glow-action';
  };

  // Get app display info with fallbacks
  const appName = data.appName || 'WordPress';
  const appService = data.appService || 'wordpress';

  // Check if this is a placeholder node
  const isPlaceholder = data.status === 'placeholder';

  // Handle placeholder click
  const handlePlaceholderClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (isPlaceholder && data.onSelectApp) {
      data.onSelectApp(id);
    }
  };

  // Render placeholder node (dashed border, click to configure)
  if (isPlaceholder) {
    const placeholderType = data.placeholderType || 'action';
    return (
      <>
        {/* Target handle (top - for vertical layout) */}
        {placeholderType !== 'trigger' && (
          <Handle
            type="target"
            position={Position.Top}
            className="!w-2 !h-2 !bg-[var(--wf-neutral-300)] !border-2 !border-white"
          />
        )}

        {/* Placeholder node content - modern minimal */}
        <div
          onClick={handlePlaceholderClick}
          className={cn(
            'w-[300px] bg-white rounded-lg border border-dashed cursor-pointer transition-all duration-200',
            'border-[var(--wf-neutral-300)] hover:border-[var(--wf-neutral-400)]',
            'shadow-[var(--wf-shadow-sm)]',
            'hover:shadow-[var(--wf-shadow-md)]',
            selected && 'border-solid shadow-[0_0_0_3px_var(--wf-action-glow)]',
            selected && placeholderType === 'trigger' && 'border-[var(--wf-trigger)]/40',
            selected && placeholderType !== 'trigger' && 'border-[var(--wf-action)]/40',
          )}
        >
          <div className="p-6 flex flex-col items-center justify-center gap-3">
            {/* Badge showing step type - refined */}
            <Badge
              variant="outline"
              className={cn(
                'text-[11px] font-medium px-2.5 py-0.5 tracking-wide uppercase border',
                placeholderType === 'trigger'
                  ? 'border-[var(--wf-trigger)]/30 text-[var(--wf-trigger)] bg-[var(--wf-trigger-muted)]/50'
                  : 'border-[var(--wf-action)]/30 text-[var(--wf-action)] bg-[var(--wf-action-muted)]/50',
              )}
            >
              {placeholderType === 'trigger' ? 'Trigger' : 'Action'}
            </Badge>

            {/* Instruction text - softer */}
            <p className="text-sm text-[var(--wf-neutral-500)] text-center">
              {placeholderType === 'trigger'
                ? 'Choose an app and event to start your workflow'
                : 'Select the event for your workflow to run'}
            </p>

            {/* Visual cue - plus icon - refined */}
            <div className="w-10 h-10 rounded-lg bg-[var(--wf-neutral-100)] flex items-center justify-center transition-colors hover:bg-[var(--wf-neutral-200)]">
              <Plus className="w-5 h-5 text-[var(--wf-neutral-500)]" />
            </div>
          </div>
        </div>

        {/* Source handle (bottom - for vertical layout) */}
        <Handle
          type="source"
          position={Position.Bottom}
          className="!w-2 !h-2 !bg-[var(--wf-neutral-300)] !border-2 !border-white"
        />
      </>
    );
  }

  // Render configured node - modern minimal design
  return (
    <>
      {/* Target handle (top - for vertical layout) */}
      {type !== 'trigger' && (
        <Handle
          type="target"
          position={Position.Top}
          className="!w-2 !h-2 !bg-[var(--wf-neutral-300)] !border-2 !border-white"
        />
      )}

      {/* Node content - modern minimal card */}
      <div
        className={cn(
          'workflow-node w-[300px] rounded-lg bg-white border overflow-hidden',
          !isRouter && 'h-[120px]',
          'transition-all ease-out cursor-pointer',
          data.isAnimating ? 'duration-500' : 'duration-200',
          // Subtle shadow elevation instead of heavy borders
          'shadow-[var(--wf-shadow-sm)]',
          'hover:shadow-[var(--wf-shadow-md)]',
          'hover:-translate-y-px',
          // Border style
          !selected && !isRouter && 'border-[var(--wf-neutral-200)]',
          !selected && isRouter && 'border-[var(--wf-operator)]/30',
          selected && 'border',
          // Selection glow effect
          getSelectionStyle(),
          // Router flow-control accent
          isRouter && 'border-l-[3px] border-l-[var(--wf-operator)]',
          // Unconfigured state class for pulse animation
          data.status === 'unconfigured' && 'node-unconfigured',
        )}
      >
        <div className="p-4">
          {/* Top row: Status + App branding + Menu */}
          <div className="flex items-center gap-2 mb-2">
            {/* Status indicator */}
            <div className="flex-shrink-0">{getStatusIndicator()}</div>

            {/* App logo using ServiceIcon */}
            <div className="flex-shrink-0">
              <ServiceIcon
                service={appService}
                size={18}
                fallback={<Icon className="w-[18px] h-[18px] text-slate-500" />}
              />
            </div>

            {/* App name - refined typography */}
            <span className="text-sm font-medium text-[var(--wf-neutral-700)]">{appName}</span>

            {/* Spacer */}
            <div className="flex-1" />

            {/* Actions menu */}
            {(data.onEdit || data.onDuplicate || data.onDelete) && (
              <div className="flex-shrink-0">
                <NodeActionsMenu
                  nodeId={id}
                  nodeName={data.name}
                  nodeType={type as 'trigger' | 'action' | 'operator'}
                  onEdit={handleEdit}
                  onDuplicate={handleDuplicate}
                  onDelete={handleDelete}
                  onViewDataFields={
                    type === 'trigger' || type === 'action' ? handleViewDataFields : undefined
                  }
                />
              </div>
            )}
          </div>

          {/* Bottom row: Step number + Action name */}
          <div className="flex items-center gap-3">
            {/* Action icon with muted background - modern minimal */}
            <div
              className={cn(
                'flex-shrink-0 w-9 h-9 rounded-lg flex items-center justify-center',
                type === 'trigger' && 'bg-[var(--wf-trigger-muted)]',
                (type === 'operator' || isRouter) && 'bg-[var(--wf-operator-muted)]',
                type === 'action' && !isRouter && 'bg-[var(--wf-action-muted)]',
              )}
            >
              <Icon
                className={cn(
                  'w-[18px] h-[18px]',
                  type === 'trigger' && 'text-[var(--wf-trigger)]',
                  (type === 'operator' || isRouter) && 'text-[var(--wf-operator)]',
                  type === 'action' && !isRouter && 'text-[var(--wf-action)]',
                )}
              />
            </div>

            {/* Step number and action name - refined typography */}
            <div className="flex-1 min-w-0 flex flex-col gap-0.5">
              <span className="text-[11px] text-[var(--wf-neutral-400)] font-medium tracking-wide uppercase">
                Step {data.stepNumber}
              </span>
              <TooltipProvider>
                <Tooltip>
                  <TooltipTrigger asChild>
                    <span className="text-[15px] font-medium text-[var(--wf-neutral-800)] truncate cursor-default">
                      {data.name}
                    </span>
                  </TooltipTrigger>
                  <TooltipContent side="bottom" className="max-w-[280px]">
                    <p>{data.name}</p>
                  </TooltipContent>
                </Tooltip>
              </TooltipProvider>
            </div>
          </div>

          {/* Config summary and field count section - refined */}
          {(data.configSummary || (type === 'trigger' && data.fieldCount)) && (
            <div className="mt-3 pt-3 border-t border-[var(--wf-neutral-100)] flex items-center justify-between gap-2">
              {data.configSummary && (
                <p className="text-xs text-[var(--wf-neutral-500)] truncate flex-1">
                  {data.configSummary}
                </p>
              )}
              {type === 'trigger' && data.fieldCount && (
                <div className="flex items-center gap-1 text-xs text-[var(--wf-neutral-400)] flex-shrink-0">
                  <Database className="w-3 h-3" />
                  <span>{data.fieldCount} fields</span>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Router multi-handle footer — inside node card for visual continuity */}
        {isRouter && routerRoutes.length > 0 && (
          <div className="flex justify-around w-full px-3 pb-2 pt-1.5 border-t border-[var(--wf-neutral-100)]">
            {routerRoutes.map((route) => (
              <div key={route.name} className="flex flex-col items-center">
                <Handle
                  type="source"
                  position={Position.Bottom}
                  id={route.name}
                  className="!w-0 !h-0 !min-w-0 !min-h-0 !border-0 !opacity-0 !p-0"
                  style={{ position: 'relative', transform: 'none', left: 'auto', bottom: 'auto' }}
                />
                <span className="text-[10px] text-[var(--wf-neutral-500)] font-medium leading-tight">
                  {route.label || route.name}
                </span>
              </div>
            ))}
            <div className="flex flex-col items-center">
              <Handle
                type="source"
                position={Position.Bottom}
                id="default"
                className="!w-0 !h-0 !min-w-0 !min-h-0 !border-0 !opacity-0 !p-0"
                style={{ position: 'relative', transform: 'none', left: 'auto', bottom: 'auto' }}
              />
              <span className="text-[10px] text-[var(--wf-neutral-400)] font-medium leading-tight">
                Default
              </span>
            </div>
          </div>
        )}
      </div>

      {/* Single source handle for non-router nodes */}
      {!(isRouter && routerRoutes.length > 0) && (
        <Handle
          type="source"
          position={Position.Bottom}
          className="!w-2 !h-2 !bg-[var(--wf-neutral-300)] !border-2 !border-white"
        />
      )}
    </>
  );
});

WorkflowReactFlowNode.displayName = 'WorkflowReactFlowNode';

export default WorkflowReactFlowNode;
