import { useState } from 'react'
import { useParams, Link } from 'react-router-dom'
import { usePRs } from '../api/queries/prs'
import { PRListSkeleton } from '../ui/Skeleton'
import { cn } from '../lib/utils'
import type { PRStatus, PullRequest } from '../types/api'

export default function RepoPRsPage() {
  const { owner = '', repo = '' } = useParams<{ owner: string; repo: string }>()
  const [status, setStatus] = useState<PRStatus>('open')
  const { data: prs, isLoading, isError } = usePRs(owner, repo)

  const filtered = prs?.filter(p => p.status === status) ?? []

  return (
    <div className="max-w-4xl mx-auto px-4 md:px-6 py-6">
      <div className="flex items-center gap-1 text-sm mb-4">
        <Link to="/repos" className="text-[var(--c-brand)] hover:underline">Repos</Link>
        <span className="text-[var(--c-muted)]">/</span>
        <Link to={`/repos/${owner}/${repo}`} className="text-[var(--c-brand)] hover:underline">{repo}</Link>
        <span className="text-[var(--c-muted)]">/</span>
        <span className="font-semibold text-[var(--c-text)]">Pull requests</span>
      </div>

      <div className="flex items-center justify-between mb-4">
        <h1 className="text-xl font-semibold text-[var(--c-text)]">Pull Requests</h1>
        <Link
          to={`/repos/${owner}/${repo}/pulls/new`}
          className="px-3 py-2 rounded bg-[var(--c-brand)] text-white text-sm font-medium hover:bg-[var(--c-brand-hover)] min-h-[44px] flex items-center"
        >
          New PR
        </Link>
      </div>

      <div className="flex gap-1 mb-4 border-b border-[var(--c-border)]">
        {(['open', 'merged', 'closed'] as PRStatus[]).map(s => {
          const count = prs?.filter(p => p.status === s).length ?? 0
          return (
            <button key={s} onClick={() => setStatus(s)}
              className={cn(
                'px-4 py-2 text-sm font-medium capitalize border-b-2 -mb-px min-h-[44px]',
                status === s ? 'border-[var(--c-brand)] text-[var(--c-brand)]' : 'border-transparent text-[var(--c-muted)] hover:text-[var(--c-text)]',
              )}>
              {s} {count > 0 && <span className="ml-1 text-xs">({count})</span>}
            </button>
          )
        })}
      </div>

      {isLoading ? <PRListSkeleton /> : isError ? (
        <p className="text-sm text-[var(--c-danger)]">Failed to load pull requests.</p>
      ) : !filtered.length ? (
        <p className="text-sm text-[var(--c-muted)] py-8 text-center">No {status} pull requests.</p>
      ) : (
        <div className="flex flex-col gap-2">
          {filtered.map(pr => <PRRow key={pr.id} pr={pr} owner={owner} repo={repo} />)}
        </div>
      )}
    </div>
  )
}

function PRRow({ pr, owner, repo }: { pr: PullRequest; owner: string; repo: string }) {
  const statusColor = pr.status === 'open'
    ? 'bg-[#E3FCEF] text-[#006644] border-[#79F2C0]'
    : pr.status === 'merged'
    ? 'bg-[#EAE6FF] text-[#403294] border-[#C0B6F2]'
    : 'bg-[var(--c-surface-muted)] text-[var(--c-muted)] border-[var(--c-border)]'

  return (
    <Link
      to={`/repos/${owner}/${repo}/pulls/${pr.id}`}
      className="flex items-start gap-3 p-4 border border-[var(--c-border)] rounded hover:border-[var(--c-brand-focus)] hover:bg-[var(--c-surface-raised)] transition-colors"
    >
      <span className={cn('text-[10px] font-semibold px-2 py-0.5 rounded-full border shrink-0 mt-0.5', statusColor)}>
        {pr.status}
      </span>
      <div className="flex-1 min-w-0">
        <p className="text-sm font-medium text-[var(--c-text)] truncate">{pr.title}</p>
        <p className="text-xs text-[var(--c-muted)] mt-0.5">
          #{pr.id} · {pr.sourceBranch} → {pr.targetBranch}
        </p>
      </div>
    </Link>
  )
}
