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 commitSchema = z.object({
  hash: z.string(),
  author: z.string(),
  message: z.string(),
  date: z.string(),
})

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

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

  const { data: commits, isLoading, isError } = useQuery({
    queryKey: ['repos', owner, repo, 'commits'],
    queryFn: () => api.get(`/api/v1/repos/${owner}/${repo}/commits?limit=50`, z.array(commitSchema)),
    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]">Commits</span>
      </div>

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

      {commits && commits.length > 0 && (
        <div className="border border-[#DFE1E6] rounded overflow-hidden bg-white">
          {commits.map((commit, i) => (
            <div key={commit.hash}
              className={`flex items-start gap-4 px-4 py-3 ${i > 0 ? 'border-t border-[#DFE1E6]' : ''} hover:bg-[#FAFBFC]`}>
              <div className="w-7 h-7 rounded-full bg-[#0052CC]/10 text-[#0052CC] flex items-center justify-center text-[10px] font-bold shrink-0 mt-0.5">
                {commit.author?.[0]?.toUpperCase()}
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-[#172B4D] truncate">{commit.message}</p>
                <p className="text-xs text-[#5E6C84] mt-0.5">
                  {commit.author} · {new Date(commit.date).toLocaleDateString()}
                </p>
              </div>
              <code className="text-xs font-mono text-[#5E6C84] bg-[#F4F5F7] px-2 py-0.5 rounded shrink-0">
                {commit.hash.slice(0, 7)}
              </code>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
