import Link from 'next/link'
import { redirect } from 'next/navigation'
import { getCurrentUser } from '@/lib/session'
import { execAgent } from '@/lib/agent-client'
import { parseGitStatus } from '@/lib/parse-git'
import DiffViewer from './_components/diff-viewer'

export const dynamic = 'force-dynamic'

type Props = {
  params: Promise<{ repo: string }>
}

function findRepoPath(repoName: string): string | null {
  const paths = (process.env.REPO_PATHS ?? '')
    .split(',')
    .map((p) => p.trim())
    .filter(Boolean)
  return paths.find((p) => p.split('/').filter(Boolean).pop() === repoName) ?? null
}

export default async function GitRepoPage({ params }: Props) {
  const user = await getCurrentUser()
  if (!user) redirect('/login')

  const { repo } = await params
  const repoName = decodeURIComponent(repo)
  const repoPath = findRepoPath(repoName)

  if (!repoPath) {
    return (
      <div className="min-h-screen bg-background p-6">
        <div className="mx-auto max-w-6xl space-y-6">
          <div className="flex items-center gap-3">
            <Link href="/git" className="text-sm text-muted-foreground hover:text-foreground">
              ← Repositories
            </Link>
          </div>
          <div className="rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
            Repo &quot;{repoName}&quot; not found in REPO_PATHS.
          </div>
        </div>
      </div>
    )
  }

  let statusSummary = ''
  let initialDiff = ''
  let initialError: string | null = null

  try {
    const [statusOut, diffOut] = await Promise.all([
      execAgent('git_status', [repoPath]),
      execAgent('git_diff', [repoPath]),
    ])
    const status = parseGitStatus(statusOut)
    statusSummary = `${status.branch}${status.dirty ? ' · dirty' : ' · clean'}${status.ahead ? ` · ↑${status.ahead} ahead` : ''}${status.behind ? ` · ↓${status.behind} behind` : ''}`
    initialDiff = diffOut
  } catch (err) {
    initialError = err instanceof Error ? err.message : 'Failed to fetch repo data'
  }

  return (
    <div className="min-h-screen bg-background p-6">
      <div className="mx-auto max-w-6xl space-y-6">
        <div className="flex items-center gap-3">
          <Link href="/git" className="text-sm text-muted-foreground hover:text-foreground">
            ← Repositories
          </Link>
          <span className="text-muted-foreground">/</span>
          <h1 className="text-2xl font-semibold tracking-tight font-mono">{repoName}</h1>
        </div>

        {statusSummary && (
          <div className="flex items-center gap-2 text-sm text-muted-foreground font-mono">
            <span>{repoPath}</span>
            <span className="text-border">·</span>
            <span>{statusSummary}</span>
          </div>
        )}

        <div>
          <h2 className="text-base font-semibold mb-3">Uncommitted changes</h2>
          <DiffViewer repoPath={repoPath} initialDiff={initialDiff} initialError={initialError} />
        </div>
      </div>
    </div>
  )
}
