'use client'

import { useEffect, useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
import { Button, Card } from '@/components/ui'
import { askQuestionAction } from '@/app/actions'

export interface ReviewItem {
  position: number
  prompt: string
  stimulus: string | null
  explanation: string | null
  responseId: string
  typedText: string | null
  choiceKey: string | null
  answerKey: string | null
  imageCount: number
  conceded: boolean
  hintsUsed: number
  feedback: string | null
  questions: { id: string; question: string; answer: string | null; status: string }[]
}

/**
 * What he sees the moment he finishes: his own answer next to how each one
 * worked, while it is all still fresh.
 *
 * Deliberately absent: the per-dimension scores. Those are written for his
 * father in criterion-referenced language ("states the total but never says why
 * four boxes were needed") and are not something to hand a child (Rule 7). The
 * explanation states the answer plainly, so he can see for himself where he
 * landed — which is a better thing to read than a number anyway.
 */
export function SetReview({
  items,
  gradingInProgress,
}: {
  items: ReviewItem[]
  gradingInProgress: boolean
}) {
  const router = useRouter()

  // The encouraging notes arrive a few minutes after he finishes, as grading
  // completes. Poll gently so they appear without him refreshing.
  useEffect(() => {
    if (!gradingInProgress) return
    const t = setInterval(() => router.refresh(), 10000)
    return () => clearInterval(t)
  }, [gradingInProgress, router])

  return (
    <div className="space-y-4">
      {items.map((item) => (
        <ReviewCard key={item.responseId} item={item} />
      ))}
    </div>
  )
}

function ReviewCard({ item }: { item: ReviewItem }) {
  const [open, setOpen] = useState(false)
  const [asking, setAsking] = useState(false)
  const [pending, start] = useTransition()
  const [error, setError] = useState<string | null>(null)
  const router = useRouter()

  const mcRight =
    item.choiceKey !== null && item.answerKey !== null
      ? item.choiceKey === item.answerKey
      : null

  return (
    <Card className="space-y-3">
      <div className="flex flex-wrap items-baseline justify-between gap-2">
        <span className="text-[11px] font-medium uppercase tracking-wide text-[var(--color-muted)]">
          Question {item.position}
        </span>
        <span className="text-[11px] text-[var(--color-muted)]">
          {item.conceded && 'you asked to see this one'}
          {!item.conceded && item.hintsUsed > 0 && `${item.hintsUsed} hint${item.hintsUsed === 1 ? '' : 's'}`}
        </span>
      </div>

      <p className="text-[15px] leading-relaxed whitespace-pre-wrap">{item.prompt}</p>

      <div className="rounded-lg bg-[var(--color-paper)] p-3">
        <p className="text-[11px] font-medium uppercase tracking-wide text-[var(--color-muted)]">
          What you put
        </p>
        {item.typedText && (
          <p className="mt-1 text-[15px] leading-relaxed whitespace-pre-wrap">{item.typedText}</p>
        )}
        {item.choiceKey && (
          <p className="mt-1 text-[15px]">
            {item.choiceKey}
            {mcRight !== null && (
              <span className={mcRight ? 'ml-2 text-[var(--color-accent)]' : 'ml-2 text-[#9b3232]'}>
                {mcRight ? '— that one was right' : `— the answer was ${item.answerKey}`}
              </span>
            )}
          </p>
        )}
        {item.imageCount > 0 && (
          <p className="mt-1 text-sm text-[var(--color-muted)]">
            You sent {item.imageCount} photo{item.imageCount === 1 ? '' : 's'} of your working.
          </p>
        )}
        {!item.typedText && !item.choiceKey && item.imageCount === 0 && (
          <p className="mt-1 text-sm text-[var(--color-muted)]">(nothing written)</p>
        )}
      </div>

      {item.feedback && (
        <div className="rounded-lg border border-[var(--color-accent)] bg-[var(--color-accent-soft)] px-3 py-2">
          <p className="text-[15px] leading-relaxed whitespace-pre-wrap">{item.feedback}</p>
        </div>
      )}

      {!open ? (
        <button
          type="button"
          onClick={() => setOpen(true)}
          className="text-sm text-[var(--color-accent)] underline"
        >
          How this one worked
        </button>
      ) : (
        <div className="space-y-3">
          <div className="text-[15px] leading-relaxed whitespace-pre-wrap">
            {item.explanation ?? 'No explanation was written for this one — tell your dad.'}
          </div>

          {item.questions.map((q) => (
            <div key={q.id} className="space-y-1 border-t border-[var(--color-line)] pt-2">
              <p className="text-sm font-medium">You asked: {q.question}</p>
              {q.status === 'ANSWERED' && q.answer ? (
                <p className="text-[15px] leading-relaxed whitespace-pre-wrap">{q.answer}</p>
              ) : q.status === 'FAILED' ? (
                <p className="text-sm text-[var(--color-muted)]">
                  That one didn&rsquo;t work — try asking it a different way?
                </p>
              ) : (
                <p className="text-sm text-[var(--color-muted)]">
                  Thinking about that one&hellip; a minute or two.
                </p>
              )}
            </div>
          ))}

          {!asking ? (
            <button
              type="button"
              onClick={() => setAsking(true)}
              className="text-sm text-[var(--color-muted)] underline hover:text-[var(--color-ink)]"
            >
              Ask about this one
            </button>
          ) : (
            <form
              action={(fd) =>
                start(async () => {
                  const r = await askQuestionAction(item.responseId, fd)
                  if (r?.error) setError(r.error)
                  else {
                    setError(null)
                    setAsking(false)
                    router.refresh()
                  }
                })
              }
              className="space-y-2"
            >
              <textarea
                name="question"
                rows={2}
                autoFocus
                placeholder="Why does that step work?"
                className="w-full rounded-lg border border-[var(--color-line)] bg-white px-3 py-2 text-[15px] outline-none focus:border-[var(--color-accent)]"
              />
              {error && <p className="text-sm text-[#9b3232]">{error}</p>}
              <div className="flex gap-2">
                <Button type="submit" variant="secondary" disabled={pending}>
                  {pending ? 'Sending…' : 'Ask'}
                </Button>
                <Button type="button" variant="quiet" onClick={() => setAsking(false)}>
                  Cancel
                </Button>
              </div>
            </form>
          )}
        </div>
      )}
    </Card>
  )
}
