'use client'

import { useState, useTransition } from 'react'
import { Button, Card, Label } from '@/components/ui'
import {
  approveSetAction,
  discardSetAction,
  dropItemAction,
  restoreItemAction,
  updateItemAction,
} from '@/app/actions'

interface ItemView {
  id: string
  constructLabel: string
  format: string
  responseMode: string
  stimulus: string | null
  prompt: string
  choices: { key: string; text: string }[] | null
  answerKey: string | null
  rubricCriteria: string
  rationale: string | null
  pairKind: string | null
  editedByParent: boolean
}

const FORMAT_LABELS: Record<string, string> = {
  MULTIPLE_CHOICE: 'multiple choice',
  CONSTRUCTED_RESPONSE: 'constructed response',
  ESTIMATE_THEN_JUSTIFY: 'estimate, then justify',
  ERROR_ANALYSIS: 'error analysis',
  CRITIQUE: 'critique',
  MODELING: 'modelling',
  COMPUTATION_CONTROL: 'computation control',
  REVISE_PARAGRAPH: 'revise the paragraph',
  SOURCE_RESPONSE: 'response from a source',
}

export function ItemEditor({
  setItemId,
  index,
  item,
  reviewVerdict,
  reviewNote,
  droppedByReviewer,
  followUp,
}: {
  setItemId: string
  index: number
  item: ItemView
  reviewVerdict?: 'KEEP' | 'FLAG' | 'DROP' | null
  reviewNote?: string | null
  droppedByReviewer?: boolean
  followUp?: { question: string; askedAt: string } | null
}) {
  const [editing, setEditing] = useState(false)
  const [dropped, setDropped] = useState(false)
  const [withheld, setWithheld] = useState(Boolean(droppedByReviewer))
  const [pending, start] = useTransition()
  const [error, setError] = useState<string | null>(null)

  if (dropped) return null

  return (
    <Card className={withheld ? 'space-y-3 opacity-60' : 'space-y-3'}>
      {followUp && (
        <div className="rounded-lg border border-[var(--color-accent)] bg-[var(--color-accent-soft)] px-3 py-2">
          <p className="text-xs font-medium text-[var(--color-accent)]">
            Re-tests something he asked about on {followUp.askedAt}
          </p>
          <p className="mt-1 text-xs leading-relaxed text-[var(--color-muted)]">
            He asked: &ldquo;{followUp.question}&rdquo;
          </p>
          <p className="mt-1 text-xs text-[var(--color-muted)]">
            Deliberately in a different context and unsignposted &mdash; if he can tell
            it&rsquo;s the follow-up, it stops measuring whether he understood.
          </p>
        </div>
      )}

      {reviewVerdict && reviewVerdict !== 'KEEP' && (
        <div
          className={
            withheld
              ? 'rounded-lg border border-[#e8cfcf] bg-[#fdf5f5] px-3 py-2'
              : 'rounded-lg border border-[#f0e2cd] bg-[var(--color-warn-soft)] px-3 py-2'
          }
        >
          <p className="text-xs font-medium">
            {withheld
              ? 'Withheld by the reviewer'
              : reviewVerdict === 'DROP'
                ? 'The reviewer wanted this dropped — you put it back'
                : 'The reviewer left a note'}
          </p>
          {reviewNote && (
            <p className="mt-1 text-xs leading-relaxed text-[var(--color-muted)]">{reviewNote}</p>
          )}
          {withheld && (
            <button
              onClick={() =>
                start(async () => {
                  await restoreItemAction(setItemId)
                  setWithheld(false)
                })
              }
              disabled={pending}
              className="mt-2 text-xs text-[var(--color-accent)] underline"
            >
              Put it back
            </button>
          )}
        </div>
      )}
      <div className="flex flex-wrap items-baseline justify-between gap-2">
        <Label>
          {index}. {item.constructLabel} &middot; {FORMAT_LABELS[item.format] ?? item.format}
          {item.responseMode === 'PHOTO' ? ' · photo of work' : ' · typed'}
          {item.pairKind ? ' · paired' : ''}
          {item.editedByParent ? ' · edited by you' : ''}
        </Label>
        <div className="flex gap-3 text-xs">
          <button
            onClick={() => setEditing(!editing)}
            className="text-[var(--color-muted)] hover:text-[var(--color-ink)]"
          >
            {editing ? 'Cancel' : 'Edit'}
          </button>
          <button
            onClick={() =>
              start(async () => {
                await dropItemAction(setItemId)
                setDropped(true)
              })
            }
            disabled={pending}
            className="text-[#9b3232] hover:underline"
          >
            Drop
          </button>
        </div>
      </div>

      {editing ? (
        <form
          action={(formData) =>
            start(async () => {
              const result = await updateItemAction(item.id, formData)
              if (result?.error) setError(result.error)
              else {
                setError(null)
                setEditing(false)
              }
            })
          }
          className="space-y-3"
        >
          <div className="space-y-1">
            <label className="text-xs font-medium">Source material (optional)</label>
            <textarea
              name="stimulus"
              defaultValue={item.stimulus ?? ''}
              rows={item.stimulus ? 8 : 3}
              className="w-full rounded-lg border border-[var(--color-line)] px-3 py-2 text-sm"
            />
          </div>
          <div className="space-y-1">
            <label className="text-xs font-medium">Question</label>
            <textarea
              name="prompt"
              defaultValue={item.prompt}
              rows={4}
              className="w-full rounded-lg border border-[var(--color-line)] px-3 py-2 text-sm"
            />
          </div>
          <div className="space-y-1">
            <label className="text-xs font-medium">
              Scoring criteria &mdash; criteria, not a model answer
            </label>
            <textarea
              name="rubricCriteria"
              defaultValue={item.rubricCriteria}
              rows={4}
              className="w-full rounded-lg border border-[var(--color-line)] px-3 py-2 text-sm"
            />
          </div>
          {error && <p className="text-xs text-[#9b3232]">{error}</p>}
          <Button type="submit" disabled={pending}>
            {pending ? 'Saving…' : 'Save item'}
          </Button>
        </form>
      ) : (
        <div className="space-y-3">
          {item.stimulus && (
            <div className="rounded-lg bg-[var(--color-paper)] p-3 text-sm leading-relaxed whitespace-pre-wrap">
              {item.stimulus}
            </div>
          )}
          <p className="text-sm leading-relaxed whitespace-pre-wrap">{item.prompt}</p>
          {item.choices && (
            <ul className="space-y-1 text-sm">
              {item.choices.map((c) => (
                <li key={c.key} className={c.key === item.answerKey ? 'font-medium' : ''}>
                  {c.key}. {c.text}
                  {c.key === item.answerKey && (
                    <span className="ml-2 text-xs text-[var(--color-accent)]">key</span>
                  )}
                </li>
              ))}
            </ul>
          )}
          <details className="text-xs text-[var(--color-muted)]">
            <summary className="cursor-pointer">Criteria and rationale</summary>
            <div className="mt-2 space-y-2">
              <p className="whitespace-pre-wrap">
                <strong>Credit:</strong> {item.rubricCriteria}
              </p>
              {item.rationale && (
                <p className="whitespace-pre-wrap">
                  <strong>Why this item now:</strong> {item.rationale}
                </p>
              )}
            </div>
          </details>
        </div>
      )}
    </Card>
  )
}

export function ReviewControls({
  setId,
  itemCount,
  name,
}: {
  setId: string
  itemCount: number
  name: string
}) {
  const [pending, start] = useTransition()
  const [error, setError] = useState<string | null>(null)

  return (
    <Card className="space-y-3">
      <p className="text-sm">
        Releasing makes this available to {name} the next time he signs in.
      </p>
      {error && <p className="text-xs text-[#9b3232]">{error}</p>}
      <div className="flex flex-wrap gap-2">
        <Button
          disabled={pending || itemCount === 0}
          onClick={() =>
            start(async () => {
              const result = await approveSetAction(setId)
              if (result?.error) setError(result.error)
            })
          }
        >
          {pending ? 'Releasing…' : `Release ${itemCount} items to ${name}`}
        </Button>
        <Button
          variant="danger"
          disabled={pending}
          onClick={() => start(async () => void (await discardSetAction(setId)))}
        >
          Discard this draft
        </Button>
      </div>
      <p className="text-xs text-[var(--color-muted)]">
        A discarded draft is kept, not deleted &mdash; the generator needs to know
        these items were written so it does not produce them again.
      </p>
    </Card>
  )
}
