import { useParams, Link } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { z } from 'zod'
import { api } from '../api/client'
import { useRecentRepos } from '../hooks/useRecentRepos'
import { useEffect } from 'react'

const branchSchema = z.object({ name: z.string() })

export default function BranchesPage() {
  const { owner = '', repo = '' } = useParams<{ owner: string; repo: string }>()
  const { track } = useRecentRepos()

  useEffect(() => { if (owner && repo) track(owner, repo) }, [owner, repo])

  const { data: branches, isLoading, isError } = useQuery({
    queryKey: ['repos', owner, repo, 'branches'],
    queryFn: () => api.get(`/api/v1/repos/${owner}/${repo}/branches`, z.array(branchSchema)),
    enabled: Boolean(owner && repo),
  })

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

      <h1 className="text-xl font-semibold text-[#172B4D] mb-4">Branches</h1>

      {isLoading && <p className="text-sm text-[#5E6C84]">Loading branches…</p>}
      {isError && <p className="text-sm text-[#DE350B]">Failed to load branches.</p>}
      {!isLoading && !branches?.length && (
        <p className="text-sm text-[#5E6C84] py-8 text-center">No branches yet.</p>
      )}

      {branches && branches.length > 0 && (
        <div className="border border-[#DFE1E6] rounded overflow-hidden bg-white">
          {branches.map((branch, i) => (
            <div key={branch.name}
              className={`flex items-center gap-3 px-4 py-3 ${i > 0 ? 'border-t border-[#DFE1E6]' : ''} hover:bg-[#FAFBFC]`}>
              <svg width="14" height="14" fill="none" stroke="#5E6C84" strokeWidth="1.5" viewBox="0 0 24 24" className="shrink-0">
                <path strokeLinecap="round" strokeLinejoin="round" d="M3 13.5V6a2.25 2.25 0 0 1 2.25-2.25h.75a2.25 2.25 0 0 1 2.25 2.25v3.75A2.25 2.25 0 0 1 6 12H5.25A2.25 2.25 0 0 0 3 14.25v2.25A2.25 2.25 0 0 0 5.25 18.75H6a2.25 2.25 0 0 0 2.25-2.25V15m0 0a3 3 0 1 0 6 0 3 3 0 0 0-6 0Zm0 0h3" />
              </svg>
              <Link to={`/repos/${owner}/${repo}?ref=${branch.name}`}
                className="text-sm text-[#0052CC] hover:underline font-mono">
                {branch.name}
              </Link>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
