import { cn } from '../../lib/utils'
import type { Pipeline } from '../../types/api'

interface Stage {
  name: string
  status: Pipeline['status']
  duration?: string
}

interface PipelineWaterfallProps {
  pipeline: Pipeline
  stages?: Stage[]
}

const STATUS_COLOR: Record<Pipeline['status'], string> = {
  pending:   'bg-[#F4F5F7] border-[#DFE1E6] text-[#5E6C84]',
  running:   'bg-[#DEEBFF] border-[#4C9AFF] text-[#0052CC]',
  success:   'bg-[#E3FCEF] border-[#79F2C0] text-[#006644]',
  failure:   'bg-[#FFEBE6] border-[#FF8F73] text-[#BF2600]',
  cancelled: 'bg-[#F4F5F7] border-[#DFE1E6] text-[#5E6C84]',
}

const STATUS_DOT: Record<Pipeline['status'], string> = {
  pending:   'bg-[#97A0AF]',
  running:   'bg-[#0052CC] animate-pulse',
  success:   'bg-[#00875A]',
  failure:   'bg-[#DE350B]',
  cancelled: 'bg-[#97A0AF]',
}

const STATUS_LABEL: Record<Pipeline['status'], string> = {
  pending:   'Pending',
  running:   'Running',
  success:   'Passed',
  failure:   'Failed',
  cancelled: 'Cancelled',
}

// Default stage breakdown when no stage data is provided
function defaultStages(status: Pipeline['status']): Stage[] {
  const stages: Array<{ name: string; order: number }> = [
    { name: 'Clone',   order: 0 },
    { name: 'Build',   order: 1 },
    { name: 'Test',    order: 2 },
    { name: 'Deploy',  order: 3 },
  ]
  return stages.map((s, i) => ({
    name: s.name,
    status: deriveStageStatus(status, i, stages.length),
  }))
}

function deriveStageStatus(pipelineStatus: Pipeline['status'], idx: number, total: number): Pipeline['status'] {
  if (pipelineStatus === 'success') return 'success'
  if (pipelineStatus === 'pending') return 'pending'
  if (pipelineStatus === 'cancelled') return idx === 0 ? 'cancelled' : 'pending'
  if (pipelineStatus === 'failure') {
    const failAt = Math.floor(total * 0.6)
    if (idx < failAt) return 'success'
    if (idx === failAt) return 'failure'
    return 'pending'
  }
  // running
  const runAt = Math.floor(total * 0.4)
  if (idx < runAt) return 'success'
  if (idx === runAt) return 'running'
  return 'pending'
}

export function PipelineWaterfall({ pipeline, stages }: PipelineWaterfallProps) {
  const resolvedStages = stages ?? defaultStages(pipeline.status)

  return (
    <div className="border border-[#DFE1E6] rounded p-4 bg-white">
      {/* Pipeline header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <span className={cn('w-2.5 h-2.5 rounded-full shrink-0', STATUS_DOT[pipeline.status])} />
          <span className="text-sm font-semibold text-[#172B4D]">
            Pipeline #{pipeline.id}
          </span>
          <span className={cn(
            'text-xs font-medium px-2 py-0.5 rounded-full border',
            STATUS_COLOR[pipeline.status],
          )}>
            {STATUS_LABEL[pipeline.status]}
          </span>
        </div>
        <span className="text-xs text-[#5E6C84]">{pipeline.ref}</span>
      </div>

      {/* Waterfall stages */}
      <div className="flex items-center gap-0 overflow-x-auto pb-2">
        {resolvedStages.map((stage, i) => (
          <div key={stage.name} className="flex items-center shrink-0">
            {/* Stage box */}
            <div className={cn(
              'flex flex-col items-center justify-center px-4 py-3 rounded border text-center min-w-[80px]',
              STATUS_COLOR[stage.status],
            )}>
              <StatusIcon status={stage.status} />
              <span className="text-[11px] font-semibold mt-1">{stage.name}</span>
              {stage.duration && (
                <span className="text-[10px] opacity-70 mt-0.5">{stage.duration}</span>
              )}
            </div>

            {/* Connector arrow (not after last) */}
            {i < resolvedStages.length - 1 && (
              <div className="flex items-center px-1">
                <div className="h-px w-4 bg-[#DFE1E6]" />
                <svg width="6" height="8" viewBox="0 0 6 8" fill="#DFE1E6">
                  <path d="M0 0l6 4-6 4V0z" />
                </svg>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  )
}

function StatusIcon({ status }: { status: Pipeline['status'] }) {
  if (status === 'success') {
    return (
      <svg width="16" height="16" fill="none" stroke="#00875A" strokeWidth="2.5" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" d="m4.5 12.75 6 6 9-13.5" />
      </svg>
    )
  }
  if (status === 'failure') {
    return (
      <svg width="16" height="16" fill="none" stroke="#DE350B" strokeWidth="2.5" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
      </svg>
    )
  }
  if (status === 'running') {
    return (
      <svg width="16" height="16" fill="none" stroke="#0052CC" strokeWidth="2" viewBox="0 0 24 24" className="animate-spin">
        <path strokeLinecap="round" d="M12 3a9 9 0 1 0 9 9" />
      </svg>
    )
  }
  return (
    <svg width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.5" viewBox="0 0 24 24">
      <circle cx="12" cy="12" r="9" />
    </svg>
  )
}
