'use client'

import { useCallback, useEffect, useState } from 'react'
import { apiFetch } from '@/lib/csrf'

async function fetchDiff(repoPath: string): Promise<string> {
  const res = await apiFetch('/api/agent/exec', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ command_key: 'git_diff', args: [repoPath] }),
  })

  if (!res.ok) {
    const text = await res.text()
    throw new Error(`agent ${res.status}: ${text}`)
  }

  const reader = res.body?.getReader()
  if (!reader) throw new Error('no response body')

  const decoder = new TextDecoder()
  let buffer = ''
  let output = ''

  while (true) {
    const { done, value } = await reader.read()
    if (done) break

    buffer += decoder.decode(value, { stream: true })
    const lines = buffer.split('\n')
    buffer = lines.pop() ?? ''

    for (const line of lines) {
      if (line.startsWith('data:')) {
        try {
          const parsed = JSON.parse(line.slice(5).trim()) as { data?: string }
          if (parsed.data !== undefined) output += parsed.data
        } catch {
          // ignore malformed
        }
      }
    }
  }

  return output
}

function DiffLine({ line }: { line: string }) {
  if (line.startsWith('+++') || line.startsWith('---')) {
    return <span className="text-muted-foreground">{line}{'\n'}</span>
  }
  if (line.startsWith('+')) {
    return (
      <span className="bg-green-500/10 text-green-700 dark:text-green-400 block">
        {line}{'\n'}
      </span>
    )
  }
  if (line.startsWith('-')) {
    return (
      <span className="bg-red-500/10 text-red-700 dark:text-red-400 block">
        {line}{'\n'}
      </span>
    )
  }
  if (line.startsWith('@@')) {
    return <span className="text-blue-600 dark:text-blue-400">{line}{'\n'}</span>
  }
  if (line.startsWith('diff ') || line.startsWith('index ')) {
    return <span className="text-muted-foreground font-semibold">{line}{'\n'}</span>
  }
  return <span>{line}{'\n'}</span>
}

type Props = {
  repoPath: string
  initialDiff: string
  initialError: string | null
}

export default function DiffViewer({ repoPath, initialDiff, initialError }: Props) {
  const [diff, setDiff] = useState(initialDiff)
  const [error, setError] = useState(initialError)
  const [refreshing, setRefreshing] = useState(false)

  const refresh = useCallback(async () => {
    setRefreshing(true)
    try {
      const data = await fetchDiff(repoPath)
      setDiff(data)
      setError(null)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'failed')
    } finally {
      setRefreshing(false)
    }
  }, [repoPath])

  useEffect(() => {
    const id = setInterval(refresh, 30000)
    return () => clearInterval(id)
  }, [refresh])

  if (error) {
    return (
      <div className="rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
        {error}
      </div>
    )
  }

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <span className="text-xs text-muted-foreground">git diff HEAD</span>
        <div className="flex items-center gap-2">
          {refreshing && (
            <span className="text-xs text-muted-foreground animate-pulse">refreshing…</span>
          )}
          <button
            onClick={refresh}
            disabled={refreshing}
            className="text-xs text-muted-foreground hover:text-foreground transition-colors"
          >
            Refresh
          </button>
        </div>
      </div>
      {diff.trim() === '' ? (
        <div className="rounded-lg border border-border px-4 py-8 text-center text-sm text-muted-foreground">
          No uncommitted changes
        </div>
      ) : (
        <pre className="overflow-x-auto rounded-lg border border-border bg-muted/30 p-4 text-xs font-mono leading-relaxed">
          {diff.split('\n').map((line, i) => (
            <DiffLine key={i} line={line} />
          ))}
        </pre>
      )}
    </div>
  )
}
