'use client'

import { useActionState, useEffect, useRef } from 'react'
import { Button, Card } from '@/components/ui'
import { submitResponseFormAction } from '@/app/actions'

/**
 * Bound server action rather than an inline closure, so the form still submits
 * with JavaScript disabled or still loading. These are children on a tablet;
 * losing a written answer to a stalled bundle is not an acceptable failure.
 */
export function ItemForm({
  setItemId,
  item,
}: {
  setItemId: string
  item: {
    stimulus: string | null
    prompt: string
    choices: { key: string; text: string }[] | null
    format: string
    responseMode: string
  }
}) {
  const action = submitResponseFormAction.bind(null, setItemId)
  const [state, formAction, pending] = useActionState(action, null)
  const startedAt = useRef(Date.now())
  const timeField = useRef<HTMLInputElement>(null)

  // Administration conditions are worth capturing: their own testing history
  // contains a result invalidated by a rushed session. Absent without JS, which
  // is why the column is nullable.
  useEffect(() => {
    const tick = setInterval(() => {
      if (timeField.current) {
        timeField.current.value = String(Date.now() - startedAt.current)
      }
    }, 1000)
    return () => clearInterval(tick)
  }, [])

  const isPhoto = item.responseMode === 'PHOTO'
  const isChoice = item.format === 'MULTIPLE_CHOICE' && item.choices

  return (
    <Card className="space-y-4">
      {item.stimulus && (
        <div className="rounded-lg bg-[var(--color-paper)] p-4 text-[15px] leading-relaxed whitespace-pre-wrap">
          {item.stimulus}
        </div>
      )}

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

      <form action={formAction} className="space-y-3">
        <input ref={timeField} type="hidden" name="timeSpentMs" defaultValue="" />

        {isChoice ? (
          <div className="grid gap-2">
            {item.choices!.map((c) => (
              <label
                key={c.key}
                className="flex cursor-pointer items-start gap-3 rounded-lg border border-[var(--color-line)] px-3 py-2.5 text-sm has-checked:border-[var(--color-accent)] has-checked:bg-[var(--color-accent-soft)]"
              >
                <input
                  type="radio"
                  name="choiceKey"
                  value={c.key}
                  required
                  className="mt-0.5 accent-[var(--color-accent)]"
                />
                <span>
                  <strong className="mr-1">{c.key}.</strong>
                  {c.text}
                </span>
              </label>
            ))}
          </div>
        ) : isPhoto ? (
          <div className="space-y-2">
            <label htmlFor="images" className="block text-sm font-medium">
              Show your work on paper, then take a photo of it
            </label>
            <input
              id="images"
              type="file"
              name="images"
              accept="image/jpeg,image/png,image/webp"
              multiple
              className="block w-full text-sm"
            />
            <details className="text-xs text-[var(--color-muted)]">
              <summary className="cursor-pointer">Want to type instead?</summary>
              <textarea
                name="typedText"
                rows={4}
                className="mt-2 w-full rounded-lg border border-[var(--color-line)] px-3 py-2 text-sm"
              />
            </details>
          </div>
        ) : (
          <div className="space-y-2">
            <label htmlFor="typedText" className="block text-sm font-medium">
              Your answer
            </label>
            <textarea
              id="typedText"
              name="typedText"
              rows={8}
              required
              className="w-full rounded-lg border border-[var(--color-line)] bg-white px-3 py-2 text-[15px] leading-relaxed outline-none focus:border-[var(--color-accent)]"
            />
          </div>
        )}

        {state?.error && <p className="text-sm text-[#9b3232]">{state.error}</p>}

        <Button type="submit" disabled={pending} className="w-full">
          {pending ? 'Saving…' : 'Next'}
        </Button>
      </form>
    </Card>
  )
}
