import { useState } from 'react'
import { Link } from 'react-router-dom'
import { useDashboard } from '../api/queries/dashboard'
import { Skeleton } from '../ui/Skeleton'
import { cn } from '../lib/utils'
import type { DashPR } from '../api/queries/dashboard'

type Tab = 'review' | 'mine'

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`
  const d = Math.floor(hr / 24)
  if (d < 30) return `${d}d ago`
  return `${Math.floor(d / 30)}mo ago`
}

function PRRow({ pr, badge }: { pr: DashPR; badge?: React.ReactNode }) {
  return (
    <Link
      to={`/repos/${pr.ownerName}/${pr.repoName}/pulls/${pr.id}`}
      className="flex items-start gap-3 p-4 border-b border-[var(--c-border)] last:border-b-0 hover:bg-[var(--c-surface-muted)] transition-colors group"
    >
      <svg className="mt-0.5 shrink-0 text-[#00875A]" width="15" height="15" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" d="M7.5 21 3 16.5m0 0L7.5 12M3 16.5h13.5m0-13.5L21 7.5m0 0L16.5 12M21 7.5H7.5" />
      </svg>
      <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 truncate">{pr.title}</span>
          {badge}
        </div>
        <p className="text-xs text-[var(--c-muted)] mt-0.5">
          <Link to={`/repos/${pr.ownerName}/${pr.repoName}/pulls`} onClick={e => e.stopPropagation()}
            className="font-mono hover:underline">{pr.ownerName}/{pr.repoName}</Link>
          {' · '}
          <span className="font-mono">{pr.sourceBranch}</span>
          {' → '}
          <span className="font-mono">{pr.targetBranch}</span>
          {' · '}
          {timeAgo(pr.updatedAt)}
        </p>
      </div>
      <svg className="shrink-0 text-[var(--c-border)] group-hover:text-[var(--c-brand)] transition-colors mt-0.5" 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>
  )
}

function EmptyState({ tab }: { tab: Tab }) {
  return (
    <div className="flex flex-col items-center justify-center py-16 text-center gap-3">
      <svg width="36" height="36" fill="none" stroke="var(--c-border)" strokeWidth="1.2" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" d="M7.5 21 3 16.5m0 0L7.5 12M3 16.5h13.5m0-13.5L21 7.5m0 0L16.5 12M21 7.5H7.5" />
      </svg>
      <div>
        <p className="text-sm font-medium text-[var(--c-text)]">
          {tab === 'review' ? 'No pull requests awaiting your review' : 'No open pull requests'}
        </p>
        <p className="text-xs text-[var(--c-muted)] mt-1">
          {tab === 'review' ? "You're all caught up." : 'Open a PR from any repository to get started.'}
        </p>
      </div>
    </div>
  )
}

export default function PRsPage() {
  const [tab, setTab] = useState<Tab>('mine')
  const { data: dash, isLoading } = useDashboard()

  const tabs: { id: Tab; label: string; count?: number }[] = [
    { id: 'mine', label: 'My pull requests', count: dash?.myOpenPRs.length },
    { id: 'review', label: 'Awaiting my review', count: dash?.reviewQueue.length },
  ]

  const rows = tab === 'mine' ? (dash?.myOpenPRs ?? []) : (dash?.reviewQueue ?? [])

  return (
    <div className="max-w-4xl mx-auto px-4 md:px-6 py-6 space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold text-[var(--c-text)]">Pull Requests</h1>
        <Link to="/repos" className="text-xs text-[var(--c-brand)] hover:underline">
          Browse repos →
        </Link>
      </div>

      {/* Tabs */}
      <div className="flex gap-0 border-b border-[var(--c-border)]">
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            className={cn(
              'flex items-center gap-2 px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors',
              tab === t.id
                ? 'border-[var(--c-brand)] text-[var(--c-brand)]'
                : 'border-transparent text-[var(--c-muted)] hover:text-[var(--c-text)]',
            )}>
            {t.label}
            {t.count !== undefined && t.count > 0 && (
              <span className={cn(
                'text-[10px] font-bold px-1.5 py-0.5 rounded-full',
                tab === t.id ? 'bg-[var(--c-brand)] text-white' : 'bg-[var(--c-surface-muted)] text-[var(--c-muted)]',
              )}>
                {t.count}
              </span>
            )}
          </button>
        ))}
      </div>

      {/* List */}
      {isLoading ? (
        <div className="border border-[var(--c-border)] rounded-lg divide-y divide-[var(--c-border)]">
          {Array.from({ length: 4 }).map((_, i) => (
            <div key={i} className="flex items-start gap-3 p-4">
              <Skeleton className="w-4 h-4 rounded-full mt-0.5 shrink-0" />
              <div className="flex-1 space-y-2">
                <Skeleton className="h-4 w-3/4 rounded" />
                <Skeleton className="h-3 w-1/2 rounded" />
              </div>
            </div>
          ))}
        </div>
      ) : rows.length === 0 ? (
        <EmptyState tab={tab} />
      ) : (
        <div className="border border-[var(--c-border)] rounded-lg overflow-hidden bg-[var(--c-surface)]">
          {rows.map(pr => (
            <PRRow key={`${pr.repoId}-${pr.id}`} pr={pr} badge={
              tab === 'review' ? (
                <span className="text-[9px] font-semibold uppercase tracking-wider px-1.5 py-px rounded-full bg-[var(--c-warning)]/15 text-[var(--c-warning)] border border-[var(--c-warning)]/30 shrink-0">
                  Review requested
                </span>
              ) : undefined
            } />
          ))}
        </div>
      )}

      {/* Per-repo links */}
      {!isLoading && dash && dash.repos.length > 0 && (
        <div className="pt-2">
          <p className="text-xs text-[var(--c-muted)] mb-2">Browse PRs by repository:</p>
          <div className="flex flex-wrap gap-2">
            {dash.repos.slice(0, 8).map(r => (
              <Link key={r.id} to={`/repos/${r.ownerName}/${r.name}/pulls`}
                className="flex items-center gap-1.5 px-2.5 py-1 text-xs border border-[var(--c-border)] rounded-md bg-[var(--c-surface)] text-[var(--c-text)] hover:border-[var(--c-brand-focus)] hover:text-[var(--c-brand)] transition-colors">
                {r.name}
                {r.openPrCount > 0 && (
                  <span className="text-[10px] font-bold text-white bg-[var(--c-brand)] rounded-full px-1.5 py-px">{r.openPrCount}</span>
                )}
              </Link>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
