import React from 'react';
import { cn } from '../../utils/classNames';
import type { Workflow } from '../../contexts/WorkflowsContext';

interface WorkflowSlashMenuProps {
  items: Workflow[];
  activeIndex: number;
  onSelect: (workflow: Workflow) => void;
  onHover: (index: number) => void;
}

/** Popover of workflows shown above the composer when the draft starts with "/". */
const WorkflowSlashMenu: React.FC<WorkflowSlashMenuProps> = ({ items, activeIndex, onSelect, onHover }) => {
  if (items.length === 0) return null;

  return (
    <div
      role="listbox"
      aria-label="Workflows"
      className="absolute inset-x-0 bottom-full z-30 mb-2 max-h-72 overflow-y-auto rounded-xl border border-app-border bg-app-elevated p-1 shadow-card scrollbar-custom"
    >
      {items.map((workflow, index) => (
        <button
          key={workflow.id}
          type="button"
          role="option"
          aria-selected={index === activeIndex}
          onMouseEnter={() => onHover(index)}
          onMouseDown={(e) => {
            e.preventDefault(); // keep composer focus
            onSelect(workflow);
          }}
          className={cn(
            'flex w-full items-center gap-3 rounded-md px-3 py-2 text-left transition-colors',
            index === activeIndex ? 'bg-app-selected' : 'hover:bg-app-surface-hover',
          )}
        >
          <span className="min-w-0 flex-1">
            <span className="block truncate text-sm font-medium text-app-text">{workflow.title}</span>
            {workflow.description && (
              <span className="block truncate text-xs text-app-muted">{workflow.description}</span>
            )}
          </span>
          {workflow.variables.length > 0 && (
            <span className="shrink-0 text-[0.7rem] text-app-muted-strong">
              {workflow.variables.length} field{workflow.variables.length === 1 ? '' : 's'}
            </span>
          )}
        </button>
      ))}
    </div>
  );
};

export default WorkflowSlashMenu;
