import { useState } from 'react'
import { Link } from 'react-router-dom'
import { useRecentRuns } from '../api/queries/pipelines'
import { Skeleton } from '../ui/Skeleton'
import { cn } from '../lib/utils'
import type { RunStatus } from '../types/api'

// ── Utilities ─────────────────────────────────────────────────────────────────

function timeAgo(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime()
  const min = Math.floor(diff / 60_000)
  if (min < 1) return 'just now'
  if (min < 60) return `${min}m ago`
  const hr = Math.floor(min / 60)
  if (hr < 24) return `${hr}h ago`
  return `${Math.floor(hr / 24)}d ago`
}

function duration(start: string | null, end: string | null): string {
  if (!start) return '—'
  const ms = new Date(end ?? Date.now()).getTime() - new Date(start).getTime()
  const s = Math.floor(ms / 1000)
  if (s < 60) return `${s}s`
  return `${Math.floor(s / 60)}m ${s % 60}s`
}

function shortRef(ref: string): string {
  return ref.replace('refs/heads/', '').replace('refs/tags/', '')
}

function shortSHA(sha: string): string {
  return sha.slice(0, 7)
}

// ── Status helpers ─────────────────────────────────────────────────────────────

const STATUS_DOT: Record<RunStatus, string> = {
  queued:    'bg-[var(--c-subtle)]',
  running:   'bg-[var(--c-brand)] animate-pulse',
  succeeded: 'bg-[var(--c-success)]',
  failed:    'bg-[var(--c-danger)]',
  cancelled: 'bg-[var(--c-subtle)]',
}

const STATUS_LABEL: Record<RunStatus, string> = {
  queued:    'Queued',
  running:   'Running',
  succeeded: 'Passed',
  failed:    'Failed',
  cancelled: 'Cancelled',
}

const STATUS_TEXT: Record<RunStatus, string> = {
  queued:    'text-[var(--c-muted)]',
  running:   'text-[var(--c-brand)]',
  succeeded: 'text-[var(--c-success)]',
  failed:    'text-[var(--c-danger)]',
  cancelled: 'text-[var(--c-muted)]',
}

// ── Row ───────────────────────────────────────────────────────────────────────

function RunRow({ run }: {
  run: {
    id: number
    repoName: string
    ownerName: string
    triggerRef: string
    triggerSha: string
    triggeredBy: string
    status: string
    startedAt: string | null
    finishedAt: string | null
    createdAt: string
  }
}) {
  const status = (run.status as RunStatus) || 'queued'

  return (
    <Link
      to={`/repos/${run.ownerName}/${run.repoName}/runs/${run.id}`}
      className="flex items-center gap-3 px-4 py-3 hover:bg-[var(--c-surface-muted)] transition-colors group"
    >
      {/* Status dot */}
      <span className={cn('w-2 h-2 rounded-full shrink-0', STATUS_DOT[status])} />

      {/* Repo + branch */}
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-sm font-medium text-[var(--c-text)] group-hover:text-[var(--c-brand)] transition-colors">
            {run.ownerName}/{run.repoName}
          </span>
          <span className={cn('text-xs font-medium', STATUS_TEXT[status])}>
            {STATUS_LABEL[status]}
          </span>
        </div>
        <div className="flex items-center gap-2.5 mt-0.5 text-[11px] text-[var(--c-muted)]">
          <span className="font-mono">{shortRef(run.triggerRef)}</span>
          <span className="font-mono">{shortSHA(run.triggerSha)}</span>
          <span>by {run.triggeredBy}</span>
        </div>
      </div>

      {/* Duration + time */}
      <div className="flex flex-col items-end gap-0.5 shrink-0">
        <span className="text-[11px] text-[var(--c-muted)] font-mono">
          {duration(run.startedAt, run.finishedAt)}
        </span>
        <span className="text-[10px] text-[var(--c-subtle)]">
          {timeAgo(run.createdAt)}
        </span>
      </div>

      {/* Arrow */}
      <svg className="shrink-0 text-[var(--c-border)] group-hover:text-[var(--c-brand)] transition-colors" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
      </svg>
    </Link>
  )
}

// ── Row skeleton ──────────────────────────────────────────────────────────────

function RunRowSkeleton() {
  return (
    <div className="flex items-center gap-3 px-4 py-3">
      <Skeleton className="w-2 h-2 rounded-full shrink-0" />
      <div className="flex-1 space-y-1.5">
        <Skeleton className="h-3.5 w-48 rounded" />
        <Skeleton className="h-2.5 w-32 rounded" />
      </div>
      <div className="flex flex-col items-end gap-1">
        <Skeleton className="h-3 w-10 rounded" />
        <Skeleton className="h-2.5 w-12 rounded" />
      </div>
    </div>
  )
}

// ── Filter bar ────────────────────────────────────────────────────────────────

type FilterStatus = 'all' | RunStatus

const FILTERS: { label: string; value: FilterStatus }[] = [
  { label: 'All', value: 'all' },
  { label: 'Running', value: 'running' },
  { label: 'Failed', value: 'failed' },
  { label: 'Passed', value: 'succeeded' },
  { label: 'Queued', value: 'queued' },
]

// ── Page ──────────────────────────────────────────────────────────────────────

export default function PipelinesPage() {
  const { data: runs, isLoading } = useRecentRuns(50)

  // Simple client-side filter — real pagination could be added later
  const [filter, setFilter] = useState<FilterStatus>('all')

  const filtered = runs?.filter(r => filter === 'all' || r.status === filter) ?? []

  const runningCount = runs?.filter(r => r.status === 'running').length ?? 0
  const failedCount = runs?.filter(r => r.status === 'failed').length ?? 0

  return (
    <div className="max-w-4xl mx-auto px-4 md:px-6 py-5 space-y-4">

      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-lg font-semibold text-[var(--c-text)]">Pipelines</h1>
          <p className="text-xs text-[var(--c-muted)] mt-0.5">
            Recent runs across all your repositories
          </p>
        </div>

        {/* Live indicators */}
        {!isLoading && (runningCount > 0 || failedCount > 0) && (
          <div className="flex items-center gap-2.5 text-xs">
            {runningCount > 0 && (
              <span className="flex items-center gap-1.5 text-[var(--c-brand)]">
                <span className="w-1.5 h-1.5 rounded-full bg-[var(--c-brand)] animate-pulse" />
                {runningCount} running
              </span>
            )}
            {failedCount > 0 && (
              <span className="flex items-center gap-1.5 text-[var(--c-danger)]">
                <span className="w-1.5 h-1.5 rounded-full bg-[var(--c-danger)]" />
                {failedCount} failed
              </span>
            )}
          </div>
        )}
      </div>

      {/* Filter tabs */}
      <div className="flex items-center gap-1 border-b border-[var(--c-border)]">
        {FILTERS.map(f => (
          <button
            key={f.value}
            onClick={() => setFilter(f.value)}
            className={cn(
              'px-3 py-2 text-xs font-medium border-b-2 -mb-px transition-colors',
              filter === f.value
                ? 'border-[var(--c-brand)] text-[var(--c-brand)]'
                : 'border-transparent text-[var(--c-muted)] hover:text-[var(--c-text)]',
            )}
          >
            {f.label}
            {f.value !== 'all' && !isLoading && runs && (
              <span className="ml-1.5 text-[10px] font-mono text-[var(--c-subtle)]">
                {runs.filter(r => r.status === f.value).length}
              </span>
            )}
          </button>
        ))}
      </div>

      {/* Runs list */}
      <div className="border border-[var(--c-border)] rounded-lg bg-[var(--c-surface)] overflow-hidden divide-y divide-[var(--c-border)]">
        {isLoading ? (
          Array.from({ length: 6 }).map((_, i) => <RunRowSkeleton key={i} />)
        ) : filtered.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 gap-3 text-center">
            <svg width="40" height="40" fill="none" stroke="var(--c-subtle)" strokeWidth="1" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 0 1 0 1.972l-11.54 6.347a1.125 1.125 0 0 1-1.667-.986V5.653Z" />
            </svg>
            <div>
              <p className="text-sm font-medium text-[var(--c-text)]">
                {filter === 'all' ? 'No pipeline runs yet' : `No ${STATUS_LABEL[filter as RunStatus]?.toLowerCase()} runs`}
              </p>
              <p className="text-xs text-[var(--c-muted)] mt-1 max-w-xs">
                {filter === 'all'
                  ? <>Push to a repository with a <code className="font-mono bg-[var(--c-surface-muted)] px-1 rounded">.forgebucket/workflows/*.yml</code> file to trigger a run.</>
                  : 'Try a different filter above.'}
              </p>
            </div>
          </div>
        ) : (
          filtered.map(run => <RunRow key={run.id} run={run} />)
        )}
      </div>
    </div>
  )
}


