'use client'

import { useEffect, useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
import { Button, Card, Caveat } from '@/components/ui'
import { generateSetAction, recomputeAllStatesAction } from '../actions'
import { friendlyActionError } from '@/lib/client-errors'

export function GenerateButton({
  studentId,
  disabled,
  track = 'ACADEMIC',
  label = 'Generate next set',
}: {
  studentId: string
  disabled?: boolean
  track?: 'ACADEMIC' | 'SPIRITUAL'
  label?: string
}) {
  const [pending, start] = useTransition()
  const [error, setError] = useState<string | null>(null)
  const [queued, setQueued] = useState(false)
  const router = useRouter()

  return (
    <div className="flex flex-col items-end gap-1">
      <Button
        disabled={pending || disabled}
        onClick={() =>
          start(async () => {
            setError(null)
            setQueued(false)
            let result
            try {
              result = await generateSetAction(studentId, track)
            } catch (e) {
              return setError(friendlyActionError(e))
            }
            if (result?.error) setError(result.error)
            else {
              setQueued(Boolean(result?.queued))
              router.refresh()
            }
          })
        }
      >
        {pending ? 'Starting…' : label}
      </Button>
      {queued && (
        <span className="max-w-xs text-right text-[11px] text-[var(--color-muted)]">
          Queued — the mini is busy; this goes the moment it&rsquo;s free.
        </span>
      )}
      {error && <span className="max-w-xs text-right text-[11px] text-[#9b3232]">{error}</span>}
    </div>
  )
}

export function RecomputeButton() {
  const [pending, start] = useTransition()
  const router = useRouter()
  return (
    <Button
      variant="secondary"
      disabled={pending}
      onClick={() =>
        start(async () => {
          await recomputeAllStatesAction()
          router.refresh()
        })
      }
    >
      {pending ? 'Recomputing…' : 'Rebuild estimates'}
    </Button>
  )
}

interface SessionView {
  id: string
  kind: string
  status: string
  queueDepth: number
  completed: number
  errorMessage: string | null
  logTail: string | null
  startedAt: string
}

/**
 * The agent runs on the Mac mini, so the only honest thing this page can do is
 * report what the Mac last said. Poll while a session is live; the Mac posts
 * RUNNING on pickup and SUCCEEDED/FAILED at the end.
 */
export function SessionBanner({
  session,
  isRunning,
}: {
  session: SessionView | null
  isRunning: boolean
}) {
  const router = useRouter()

  useEffect(() => {
    if (!isRunning) return
    const t = setInterval(() => router.refresh(), 5000)
    return () => clearInterval(t)
  }, [isRunning, router])

  if (!session) return null

  const verb = session.kind === 'GENERATE' ? 'Writing a set' : 'Grading'
  const started = new Date(session.startedAt).toLocaleTimeString()

  if (session.status === 'PENDING') {
    return (
      <Card className="text-sm">
        <strong>{verb}</strong> — sent to the Mac mini at {started}. Waiting for it
        to pick the job up. If nothing happens, the mini may be asleep or the
        agent watcher may not be installed.
      </Card>
    )
  }

  if (session.status === 'RUNNING') {
    return (
      <Card className="text-sm">
        <strong>{verb}</strong> on the Mac mini, started {started}.
        {session.queueDepth > 1 && ` ${session.completed} of ${session.queueDepth} done.`}{' '}
        This takes a minute or two per response — each one is graded twice,
        independently.
      </Card>
    )
  }

  if (session.status === 'FAILED') {
    return (
      <Caveat>
        <strong>The last agent run failed</strong> ({verb.toLowerCase()}, {started}).{' '}
        {session.errorMessage}
        {session.logTail && (
          <details className="mt-2">
            <summary className="cursor-pointer">Log tail from the mini</summary>
            <pre className="mt-1 max-h-48 overflow-auto whitespace-pre-wrap text-[10px]">
              {session.logTail}
            </pre>
          </details>
        )}
      </Caveat>
    )
  }

  return null
}
