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-[#0052CC] hover:underline">Repos</Link>
        <span className="text-[#5E6C84]">/</span>
        <Link to={`/repos/${owner}/${repo}`} className="text-[#0052CC] hover:underline">{repo}</Link>
        <span className="text-[#5E6C84]">/</span>
        <span className="font-semibold text-[#172B4D]">Pull requests</span>
      </div>

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

      <div className="flex gap-1 mb-4 border-b border-[#DFE1E6]">
        {(['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-[#0052CC] text-[#0052CC]' : 'border-transparent text-[#5E6C84] hover:text-[#172B4D]',
              )}>
              {s} {count > 0 && <span className="ml-1 text-xs">({count})</span>}
            </button>
          )
        })}
      </div>

      {isLoading ? <PRListSkeleton /> : isError ? (
        <p className="text-sm text-[#DE350B]">Failed to load pull requests.</p>
      ) : !filtered.length ? (
        <p className="text-sm text-[#5E6C84] 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-[#F4F5F7] text-[#5E6C84] border-[#DFE1E6]'

  return (
    <Link
      to={`/repos/${owner}/${repo}/pulls/${pr.id}`}
      className="flex items-start gap-3 p-4 border border-[#DFE1E6] rounded hover:border-[#4C9AFF] hover:bg-[#FAFBFC] 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-[#172B4D] truncate">{pr.title}</p>
        <p className="text-xs text-[#5E6C84] mt-0.5">
          #{pr.id} · {pr.sourceBranch} → {pr.targetBranch}
        </p>
      </div>
    </Link>
  )
}
