import type { ReactNode } from 'react'
import { EllipsisVertical } from 'lucide-react'
import styles from './ProcessorTimeline.module.css'
import { Dropdown } from '../Dropdown/Dropdown'
import type { NodeBadge } from '../RouteFlow/RouteFlow'

export interface ProcessorStep {
  name: string
  type: string
  durationMs: number
  status: 'ok' | 'slow' | 'fail'
  startMs: number
  badges?: NodeBadge[]
}

export interface ProcessorAction {
  label: string
  icon?: ReactNode
  onClick: () => void
  disabled?: boolean
  divider?: boolean
}

interface ProcessorTimelineProps {
  processors: ProcessorStep[]
  totalMs: number
  onProcessorClick?: (processor: ProcessorStep, index: number) => void
  selectedIndex?: number
  actions?: ProcessorAction[]
  getActions?: (processor: ProcessorStep, index: number) => ProcessorAction[]
  className?: string
}

function formatDuration(ms: number): string {
  if (ms >= 1000) return `${(ms / 1000).toFixed(2)}s`
  return `${ms}ms`
}

export function ProcessorTimeline({
  processors,
  totalMs,
  onProcessorClick,
  selectedIndex,
  actions,
  getActions,
  className,
}: ProcessorTimelineProps) {
  const safeTotal = totalMs || 1

  if (processors.length === 0) {
    return (
      <div className={`${styles.empty} ${className ?? ''}`}>No processor data</div>
    )
  }

  return (
    <div className={`${styles.timeline} ${className ?? ''}`}>
      {processors.map((proc, i) => {
        const leftPct = (proc.startMs / safeTotal) * 100
        const widthPct = Math.max((proc.durationMs / safeTotal) * 100, 1)

        const barClass = [
          styles.barFill,
          proc.status === 'ok' ? styles.ok : '',
          proc.status === 'slow' ? styles.slow : '',
          proc.status === 'fail' ? styles.fail : '',
        ]
          .filter(Boolean)
          .join(' ')

        const isSelected = selectedIndex === i

        return (
          <div
            key={i}
            className={`${styles.row} ${onProcessorClick ? styles.clickable : ''} ${isSelected ? styles.selectedRow : ''}`}
            onClick={() => onProcessorClick?.(proc, i)}
            role={onProcessorClick ? 'button' : undefined}
            tabIndex={onProcessorClick ? 0 : undefined}
            onKeyDown={(e) => {
              if (onProcessorClick && (e.key === 'Enter' || e.key === ' ')) {
                e.preventDefault()
                onProcessorClick(proc, i)
              }
            }}
            aria-label={`${proc.name}: ${formatDuration(proc.durationMs)} (${proc.status})`}
          >
            <div className={styles.name} title={proc.name}>
              {proc.name}
              {proc.badges?.map((badge, bi) => (
                <span
                  key={bi}
                  className={`${styles.badge} ${styles[`badge${(badge.variant ?? 'info').charAt(0).toUpperCase()}${(badge.variant ?? 'info').slice(1)}`] ?? styles.badgeInfo}`}
                  onClick={badge.onClick ? (e) => { e.stopPropagation(); badge.onClick!() } : undefined}
                  style={badge.onClick ? { cursor: 'pointer' } : undefined}
                >
                  {badge.label}
                </span>
              ))}
            </div>
            <div className={styles.barBg}>
              <div
                className={barClass}
                style={{ left: `${leftPct}%`, width: `${widthPct}%` }}
              >
                {widthPct > 8 && (
                  <span className={styles.barLabel}>{formatDuration(proc.durationMs)}</span>
                )}
              </div>
            </div>
            <div className={styles.dur}>{formatDuration(proc.durationMs)}</div>
            {(() => {
              const resolvedActions = getActions ? getActions(proc, i) : (actions ?? [])
              if (resolvedActions.length === 0) return null
              return (
                <div
                  className={`${styles.actionsTrigger} ${isSelected ? styles.actionsVisible : ''}`}
                  onClick={(e) => e.stopPropagation()}
                  onKeyDown={(e) => e.stopPropagation()}
                >
                  <Dropdown
                    trigger={
                      <button
                        className={styles.actionsBtn}
                        aria-label={`Actions for ${proc.name}`}
                        type="button"
                      >
                        <EllipsisVertical size={14} />
                      </button>
                    }
                    items={resolvedActions}
                  />
                </div>
              )
            })()}
          </div>
        )
      })}
    </div>
  )
}
