import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { Button } from "@/components/Button";
import { getQuestionForAdmin } from "@/lib/orthoprep/queries";
import {
  AdminHeading,
  FormSection,
  InputField,
  TextareaField,
  SelectField,
  StatusBadge,
  ConfirmButton,
} from "@/components/admin";
import { updateQuestion, setQuestionStatus, deleteQuestion } from "../actions";

export const dynamic = "force-dynamic";

const statusOptions = ["draft", "published", "archived"] as const;
const LETTERS = ["A", "B", "C", "D", "E"] as const;

export default async function AdminOrthoPrepEditor({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const q = await getQuestionForAdmin(id);
  if (!q) notFound();

  const options = [
    q.options[0] ?? "",
    q.options[1] ?? "",
    q.options[2] ?? "",
    q.options[3] ?? "",
    q.options[4] ?? "",
  ];

  return (
    <>
      <div className="mb-4">
        <Link
          href="/admin/orthoprep"
          className="inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-slate)] hover:text-[var(--color-blue)]"
        >
          <ArrowLeft className="h-3.5 w-3.5" aria-hidden />
          All questions
        </Link>
      </div>

      <AdminHeading
        eyebrow={`Question · Q${q.number}`}
        title={q.stem.slice(0, 80) + (q.stem.length > 80 ? "…" : "")}
        lede={`${q.part} · ${q.chapter || "No chapter"} · Difficulty ${q.difficulty}`}
        actions={<StatusBadge label={q.status} dot />}
      />

      <div className="grid gap-6 lg:grid-cols-[minmax(0,3fr)_minmax(0,1fr)]">
        <div className="flex flex-col gap-6">
          <FormSection title="Question">
            <form action={updateQuestion} className="grid gap-4 md:grid-cols-6">
              <input type="hidden" name="id" value={q.id} />

              <InputField
                label="Number"
                name="number"
                type="number"
                defaultValue={String(q.number)}
                required
                wrapClassName="md:col-span-1"
              />
              <InputField
                label="Part"
                name="part"
                defaultValue={q.part}
                required
                wrapClassName="md:col-span-3"
              />
              <InputField
                label="Chapter"
                name="chapter"
                defaultValue={q.chapter}
                wrapClassName="md:col-span-2"
              />

              <TextareaField
                label="Stem"
                name="stem"
                defaultValue={q.stem}
                rows={5}
                maxLength={4000}
                required
                wrapClassName="md:col-span-6"
              />

              {LETTERS.map((letter, i) => (
                <InputField
                  key={letter}
                  label={`Option ${letter}`}
                  name={`option${letter}`}
                  defaultValue={options[i]}
                  maxLength={1000}
                  wrapClassName="md:col-span-6"
                />
              ))}

              <SelectField
                label="Correct answer"
                name="answer"
                defaultValue={q.answer}
                wrapClassName="md:col-span-2"
              >
                {LETTERS.map((l) => (
                  <option key={l} value={l}>
                    {l}
                  </option>
                ))}
              </SelectField>
              <SelectField
                label="Difficulty"
                name="difficulty"
                defaultValue={q.difficulty}
                wrapClassName="md:col-span-2"
              >
                <option value="Easy">Easy</option>
                <option value="Medium">Medium</option>
                <option value="Hard">Hard</option>
              </SelectField>
              <InputField
                label="Tags (comma-separated)"
                name="tags"
                defaultValue={(q.tags ?? []).join(", ")}
                wrapClassName="md:col-span-2"
              />

              <TextareaField
                label="Explanation"
                name="explanation"
                defaultValue={q.explanation}
                rows={6}
                maxLength={6000}
                hint="Why the correct answer is correct — cite the evidence base."
                wrapClassName="md:col-span-6"
              />
              <TextareaField
                label="Distractors (why the others are wrong)"
                name="distractors"
                defaultValue={q.distractors}
                rows={4}
                maxLength={3000}
                wrapClassName="md:col-span-6"
              />
              <TextareaField
                label="Take-home point / clinical pearl"
                name="takeHome"
                defaultValue={q.takeHome}
                rows={3}
                maxLength={2000}
                wrapClassName="md:col-span-6"
              />

              <div className="md:col-span-6">
                <Button type="submit" variant="primary" className="!px-4 !py-2 !text-[13px]">
                  Save question
                </Button>
              </div>
            </form>
          </FormSection>

          <FormSection
            title="Danger zone"
            description="Deleting removes this question from the bank permanently."
            tone="danger"
          >
            <form action={deleteQuestion}>
              <input type="hidden" name="id" value={q.id} />
              <ConfirmButton
                label="Delete question"
                confirmLabel="Click again to delete permanently"
                tone="danger"
              />
            </form>
          </FormSection>
        </div>

        <aside className="flex flex-col gap-6">
          <FormSection title="Status">
            <div className="flex flex-col gap-2">
              {statusOptions.map((s) => (
                <form key={s} action={setQuestionStatus}>
                  <input type="hidden" name="id" value={q.id} />
                  <input type="hidden" name="status" value={s} />
                  <button
                    type="submit"
                    disabled={q.status === s}
                    className={
                      q.status === s
                        ? "w-full rounded-lg bg-[var(--color-blue)] px-3 py-2 text-[13px] font-semibold text-white"
                        : "w-full rounded-lg border border-[var(--color-line)] bg-white px-3 py-2 text-[13px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                    }
                  >
                    {q.status === s ? `Current · ${s}` : `Set to ${s}`}
                  </button>
                </form>
              ))}
            </div>
          </FormSection>
        </aside>
      </div>
    </>
  );
}
