'use client'

import { useState, useTransition } from 'react'
import { Button, Label } from '@/components/ui'
import { adjudicateAction, gradeResponseAction } from '@/app/actions'
import { friendlyActionError } from '@/lib/client-errors'

export function GradeButton({ responseId }: { responseId: string }) {
  const [pending, start] = useTransition()
  const [error, setError] = useState<string | null>(null)
  return (
    <div className="space-y-1">
      <Button
        variant="secondary"
        disabled={pending}
        onClick={() =>
          start(async () => {
            try {
              await gradeResponseAction(responseId)
            } catch (e) {
              setError(friendlyActionError(e))
            }
          })
        }
      >
        {pending ? 'Grading twice…' : 'Grade this'}
      </Button>
      {pending && (
        <p className="text-[11px] text-[var(--color-muted)]">
          Two independent passes, then a separate call for his feedback.
        </p>
      )}
      {error && <p className="text-[11px] text-[#9b3232]">{error}</p>}
    </div>
  )
}

/**
 * Rule 8's mechanism: Eric hand-grades and compares. Available on every
 * response, not just flagged ones — validating the grader means scoring some it
 * was confident about.
 */
export function Adjudicator({
  responseId,
  dimensions,
  flagged,
}: {
  responseId: string
  dimensions: { code: string; label: string; maxValue: number }[]
  flagged: boolean
}) {
  const [open, setOpen] = useState(flagged)
  const [pending, start] = useTransition()
  const [error, setError] = useState<string | null>(null)
  const [done, setDone] = useState(false)

  if (!open) {
    return (
      <button
        onClick={() => setOpen(true)}
        className="text-xs text-[var(--color-muted)] underline hover:text-[var(--color-ink)]"
      >
        Score this yourself
      </button>
    )
  }

  return (
    <form
      action={(formData) =>
        start(async () => {
          const result = await adjudicateAction(responseId, formData)
          if (result?.error) setError(result.error)
          else {
            setError(null)
            setDone(true)
          }
        })
      }
      className="space-y-2 rounded-lg border border-[var(--color-line)] p-3"
    >
      <Label>Your score {flagged ? '(resolves the flag)' : '(for calibration)'}</Label>
      <div className="flex flex-wrap gap-3">
        {dimensions.map((d) => (
          <label key={d.code} className="text-xs">
            <span className="mr-1.5">
              {d.label} /{d.maxValue}
            </span>
            <input
              name={`dim_${d.code}`}
              type="number"
              min={0}
              max={d.maxValue}
              className="w-14 rounded border border-[var(--color-line)] px-2 py-1"
            />
          </label>
        ))}
      </div>
      <textarea
        name="note"
        rows={2}
        placeholder="Where the grader was off, if it was"
        className="w-full rounded border border-[var(--color-line)] px-2 py-1.5 text-xs"
      />
      {error && <p className="text-[11px] text-[#9b3232]">{error}</p>}
      {done && <p className="text-[11px] text-[var(--color-accent)]">Saved.</p>}
      <Button type="submit" variant="secondary" disabled={pending}>
        {pending ? 'Saving…' : 'Save my score'}
      </Button>
    </form>
  )
}
