import { notFound } from "next/navigation";
import Link from "next/link";
import { ArrowLeft } from "lucide-react";
import { Button } from "@/components/Button";
import {
  AdminHeading,
  StatusBadge,
  ImageUpload,
  FormSection,
  RepeaterField,
  type RepeaterFieldDef,
} from "@/components/admin";
import { getCourseForAdmin } from "@/lib/academy/queries";
import { listCourseResources } from "@/lib/academy/resources";
import {
  updateCourse,
  setCourseStatus,
  deleteCourse,
  createModule,
  renameModule,
  deleteModule,
  createLesson,
  updateLesson,
  deleteLesson,
  saveCourseResources,
} from "../actions";

export const dynamic = "force-dynamic";

const levelOptions = ["Foundation", "Intermediate", "Advanced"] as const;
const statusOptions = ["draft", "published", "archived"] as const;
const lessonTypeOptions = ["video", "reading", "quiz"] as const;
const videoProviderOptions = [
  { value: "none", label: "No video" },
  { value: "youtube", label: "YouTube" },
  { value: "vimeo", label: "Vimeo" },
  { value: "mp4", label: "MP4 / HLS (direct URL)" },
];

const courseResourceTypeOptions = [
  { value: "pdf", label: "PDF" },
  { value: "poster", label: "Poster" },
  { value: "slide_deck", label: "Slide deck" },
  { value: "article", label: "Article" },
  { value: "link", label: "External link" },
  { value: "image", label: "Image" },
  { value: "video", label: "Video file" },
  { value: "other", label: "Other" },
];

const courseResourceFields: RepeaterFieldDef[] = [
  { key: "type", label: "Type", type: "select", options: courseResourceTypeOptions, span: 1 },
  { key: "title", label: "Title", type: "text", span: 2, maxLength: 300 },
  { key: "description", label: "Description (optional)", type: "text", span: 3, maxLength: 1000 },
  { key: "url", label: "URL (upload to /uploads/ or paste external link)", type: "text", span: 3, maxLength: 600 },
];

export default async function AdminAcademyCourseEditor({
  params,
}: {
  params: Promise<{ courseId: string }>;
}) {
  const { courseId } = await params;
  const data = await getCourseForAdmin(courseId);
  if (!data) notFound();

  const { course, modules, enrolmentCount } = data;
  const resources = await listCourseResources(course.id);
  const resourceDefaultValue = resources.map((r) => ({
    type: r.type,
    title: r.title,
    description: r.description,
    url: r.url,
  }));

  return (
    <>
      <div className="mb-4">
        <Link
          href="/admin/academy"
          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 courses
        </Link>
      </div>

      <AdminHeading
        eyebrow={`Course · ${course.slug}`}
        title={course.title}
        lede={`${modules.length} modules · ${enrolmentCount} enrolled`}
        actions={
          <div className="flex items-center gap-2">
            <StatusBadge label={course.level} />
            <StatusBadge label={course.status} dot />
          </div>
        }
      />

      <div className="mb-6 flex flex-wrap items-center gap-2">
        <span className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
          Publication
        </span>
        {statusOptions.map((s) => (
          <form key={s} action={setCourseStatus}>
            <input type="hidden" name="id" value={course.id} />
            <input type="hidden" name="status" value={s} />
            <button
              type="submit"
              disabled={course.status === s}
              className={
                course.status === s
                  ? "rounded-full bg-[var(--color-blue)] px-3 py-1 text-[12px] font-semibold text-white"
                  : "rounded-full bg-[var(--color-line)]/50 px-3 py-1 text-[12px] font-semibold text-[var(--color-ink)] hover:bg-[var(--color-mist)] hover:text-[var(--color-blue)]"
              }
            >
              {course.status === s ? `Current · ${s}` : `Set ${s}`}
            </button>
          </form>
        ))}
      </div>

      <div className="space-y-8">

          <section className="rounded-2xl border border-[var(--color-line)] bg-white p-6">
            <h2 className="font-display text-[22px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
              Course details
            </h2>
            <form action={updateCourse} className="mt-6 grid gap-5 md:grid-cols-2">
              <input type="hidden" name="id" value={course.id} />
              <Field label="Title" name="title" defaultValue={course.title} span="md:col-span-2" required />
              <SelectField label="Level" name="level" defaultValue={course.level} options={levelOptions} />
              <Field label="Topic" name="topic" defaultValue={course.topic} required />
              <TextareaField
                label="Short description (for cards)"
                name="shortDescription"
                defaultValue={course.shortDescription}
                rows={2}
                maxLength={400}
                span="md:col-span-2"
              />
              <TextareaField
                label="Description"
                name="description"
                defaultValue={course.description}
                rows={6}
                maxLength={5000}
                span="md:col-span-2"
              />
              <TextareaField
                label="Outcomes (one per line)"
                name="outcomes"
                defaultValue={(course.outcomes ?? []).join("\n")}
                rows={5}
                maxLength={2000}
              />
              <TextareaField
                label="Prerequisites (one per line)"
                name="prerequisites"
                defaultValue={(course.prerequisites ?? []).join("\n")}
                rows={5}
                maxLength={2000}
              />
              <Field
                label="Instructor name"
                name="instructorName"
                defaultValue={course.instructorName ?? ""}
              />
              <Field
                label="Instructor title"
                name="instructorTitle"
                defaultValue={course.instructorTitle ?? ""}
              />
              <TextareaField
                label="Instructor bio"
                name="instructorBio"
                defaultValue={course.instructorBio ?? ""}
                rows={4}
                maxLength={2000}
                span="md:col-span-2"
              />
              <div className="md:col-span-2">
                <ImageUpload
                  name="coverPhoto"
                  altName="coverPhotoAlt"
                  folder="academy"
                  label="Cover photo"
                  defaultValue={course.coverPhoto}
                  defaultAlt={course.coverPhotoAlt}
                />
              </div>
              <div className="md:col-span-2">
                <Button type="submit">Save course</Button>
              </div>
            </form>
          </section>

          <section>
            <h2 className="font-display text-[22px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
              Modules & lessons
            </h2>

            <form
              action={createModule}
              className="mt-5 flex items-end gap-3 rounded-xl border border-[var(--color-line)] bg-white p-4"
            >
              <input type="hidden" name="courseId" value={course.id} />
              <label className="flex-1 text-sm">
                <span className="mb-1 block font-semibold text-[var(--color-ink)]">New module</span>
                <input
                  name="title"
                  type="text"
                  required
                  maxLength={200}
                  placeholder="e.g. Introduction to orthopaedics"
                  className="w-full rounded-md border border-[var(--color-line)] px-3 py-2"
                />
              </label>
              <Button type="submit" variant="secondary">
                Add module
              </Button>
            </form>

            <div className="mt-6 space-y-8">
              {modules.length === 0 && (
                <p className="text-sm text-[var(--color-slate)]">No modules yet.</p>
              )}
              {modules.map((m) => (
                <div key={m.id} className="rounded-2xl border border-[var(--color-line)] bg-white p-6">
                  <div className="flex flex-wrap items-end gap-3">
                    <form action={renameModule} className="flex flex-1 items-end gap-3">
                      <input type="hidden" name="id" value={m.id} />
                      <input type="hidden" name="courseId" value={course.id} />
                      <label className="flex-1 text-sm">
                        <span className="mb-1 block font-semibold text-[var(--color-ink)]">
                          Module title
                        </span>
                        <input
                          name="title"
                          type="text"
                          required
                          maxLength={200}
                          defaultValue={m.title}
                          className="w-full rounded-md border border-[var(--color-line)] px-3 py-2"
                        />
                      </label>
                      <Button type="submit" variant="ghost">
                        Rename
                      </Button>
                    </form>
                    <form action={deleteModule}>
                      <input type="hidden" name="id" value={m.id} />
                      <input type="hidden" name="courseId" value={course.id} />
                      <Button type="submit" variant="ghost">
                        Delete module
                      </Button>
                    </form>
                  </div>

                  <div className="mt-6 space-y-4">
                    {m.lessons.length === 0 && (
                      <p className="text-sm text-[var(--color-slate)]">No lessons in this module yet.</p>
                    )}
                    {m.lessons.map((l) => (
                      <details
                        key={l.id}
                        className="rounded-lg border border-[var(--color-line)] bg-[var(--color-mist)]/40"
                      >
                        <summary className="cursor-pointer px-4 py-3 text-sm">
                          <span className="font-semibold text-[var(--color-ink)]">{l.title}</span>
                          <span className="ml-3 text-[var(--color-slate)]">
                            {l.type} · {l.durationMin} min
                          </span>
                        </summary>
                        <div className="space-y-4 border-t border-[var(--color-line)] bg-white p-4">
                          <form action={updateLesson} className="grid gap-4 md:grid-cols-2">
                            <input type="hidden" name="id" value={l.id} />
                            <input type="hidden" name="courseId" value={course.id} />
                            <Field
                              label="Title"
                              name="title"
                              defaultValue={l.title}
                              required
                              span="md:col-span-2"
                            />
                            <SelectField
                              label="Type"
                              name="type"
                              defaultValue={l.type}
                              options={lessonTypeOptions}
                            />
                            <Field
                              label="Duration (min)"
                              name="durationMin"
                              type="number"
                              defaultValue={String(l.durationMin)}
                            />
                            <SelectField
                              label="Video provider"
                              name="videoProvider"
                              defaultValue={l.videoProvider ?? "none"}
                              options={videoProviderOptions}
                            />
                            <Field
                              label="Video URL"
                              name="videoUrl"
                              defaultValue={l.videoUrl ?? ""}
                              placeholder="https://www.youtube.com/watch?v=... | https://vimeo.com/... | https://cdn.example.com/lesson.mp4"
                              span="md:col-span-2"
                            />
                            <Field
                              label="Video poster image (optional, MP4 only)"
                              name="videoPoster"
                              defaultValue={l.videoPoster ?? ""}
                              placeholder="/uploads/... or full URL"
                              span="md:col-span-2"
                            />
                            <TextareaField
                              label="Content (markdown)"
                              name="content"
                              defaultValue={l.content}
                              rows={10}
                              maxLength={20000}
                              span="md:col-span-2"
                            />
                            <TextareaField
                              label="Transcript"
                              name="transcript"
                              defaultValue={l.transcript ?? ""}
                              rows={6}
                              maxLength={20000}
                              span="md:col-span-2"
                            />
                            <TextareaField
                              label="Key points (one per line)"
                              name="keyPoints"
                              defaultValue={(l.keyPoints ?? []).join("\n")}
                              rows={4}
                              maxLength={4000}
                              span="md:col-span-2"
                            />
                            <div className="md:col-span-2">
                              <Button type="submit">Save lesson</Button>
                            </div>
                          </form>
                          <form action={deleteLesson}>
                            <input type="hidden" name="id" value={l.id} />
                            <input type="hidden" name="courseId" value={course.id} />
                            <Button type="submit" variant="ghost">
                              Delete lesson
                            </Button>
                          </form>
                        </div>
                      </details>
                    ))}

                    <form
                      action={createLesson}
                      className="grid gap-3 rounded-lg border border-dashed border-[var(--color-line)] p-4 md:grid-cols-4"
                    >
                      <input type="hidden" name="moduleId" value={m.id} />
                      <input type="hidden" name="courseId" value={course.id} />
                      <label className="text-sm md:col-span-2">
                        <span className="mb-1 block font-semibold text-[var(--color-ink)]">
                          New lesson title
                        </span>
                        <input
                          name="title"
                          type="text"
                          required
                          maxLength={200}
                          className="w-full rounded-md border border-[var(--color-line)] px-3 py-2"
                        />
                      </label>
                      <label className="text-sm">
                        <span className="mb-1 block font-semibold text-[var(--color-ink)]">Type</span>
                        <select
                          name="type"
                          defaultValue="reading"
                          className="w-full rounded-md border border-[var(--color-line)] px-3 py-2"
                        >
                          {lessonTypeOptions.map((t) => (
                            <option key={t} value={t}>
                              {t}
                            </option>
                          ))}
                        </select>
                      </label>
                      <label className="text-sm">
                        <span className="mb-1 block font-semibold text-[var(--color-ink)]">Duration (min)</span>
                        <input
                          name="durationMin"
                          type="number"
                          min={0}
                          max={600}
                          defaultValue={0}
                          className="w-full rounded-md border border-[var(--color-line)] px-3 py-2"
                        />
                      </label>
                      <div className="md:col-span-4">
                        <Button type="submit" variant="secondary">
                          Add lesson
                        </Button>
                      </div>
                    </form>
                  </div>
                </div>
              ))}
            </div>
          </section>

          <FormSection
            title="Course resources"
            description="Downloadable extras enrolled learners get on the course page — PDFs, posters, slide decks, articles, or external links."
          >
            <form action={saveCourseResources} className="flex flex-col gap-4">
              <input type="hidden" name="courseId" value={course.id} />
              <RepeaterField
                name="resources"
                label="Resources"
                fields={courseResourceFields}
                defaultValue={resourceDefaultValue as unknown as Array<Record<string, string>>}
                addLabel="Add resource"
                emptyRow={{ type: "link", title: "", description: "", url: "" }}
                max={30}
              />
              <div>
                <Button type="submit" variant="primary" className="!px-4 !py-2 !text-[13px]">
                  Save resources
                </Button>
              </div>
            </form>
          </FormSection>

          <section className="rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-6">
            <h2 className="font-display text-[20px] font-extrabold tracking-[-0.01em] text-[var(--color-ink)]">
              Danger zone
            </h2>
            <p className="mt-2 text-sm text-[var(--color-slate)]">
              Deleting a course removes all of its modules, lessons, enrolments and progress. This cannot be undone.
            </p>
            <form action={deleteCourse} className="mt-4">
              <input type="hidden" name="id" value={course.id} />
              <Button type="submit" variant="ghost">
                Delete course
              </Button>
            </form>
          </section>
      </div>
    </>
  );
}

function Field({
  label,
  name,
  defaultValue,
  required,
  type = "text",
  span,
  placeholder,
}: {
  label: string;
  name: string;
  defaultValue?: string;
  required?: boolean;
  type?: string;
  span?: string;
  placeholder?: string;
}) {
  return (
    <label className={`block text-sm ${span ?? ""}`}>
      <span className="mb-1 block font-semibold text-[var(--color-ink)]">{label}</span>
      <input
        name={name}
        type={type}
        defaultValue={defaultValue}
        placeholder={placeholder}
        required={required}
        className="w-full rounded-md border border-[var(--color-line)] px-3 py-2"
      />
    </label>
  );
}

function TextareaField({
  label,
  name,
  defaultValue,
  rows,
  maxLength,
  span,
}: {
  label: string;
  name: string;
  defaultValue?: string;
  rows: number;
  maxLength?: number;
  span?: string;
}) {
  return (
    <label className={`block text-sm ${span ?? ""}`}>
      <span className="mb-1 block font-semibold text-[var(--color-ink)]">{label}</span>
      <textarea
        name={name}
        rows={rows}
        maxLength={maxLength}
        defaultValue={defaultValue}
        className="w-full rounded-md border border-[var(--color-line)] px-3 py-2 font-mono text-[13px]"
      />
    </label>
  );
}

function SelectField({
  label,
  name,
  defaultValue,
  options,
}: {
  label: string;
  name: string;
  defaultValue: string;
  options: readonly string[] | ReadonlyArray<{ value: string; label: string }>;
}) {
  const normalised = (options as ReadonlyArray<string | { value: string; label: string }>).map(
    (o) => (typeof o === "string" ? { value: o, label: o } : o),
  );
  return (
    <label className="block text-sm">
      <span className="mb-1 block font-semibold text-[var(--color-ink)]">{label}</span>
      <select
        name={name}
        defaultValue={defaultValue}
        className="w-full rounded-md border border-[var(--color-line)] px-3 py-2"
      >
        {normalised.map((o) => (
          <option key={o.value} value={o.value}>
            {o.label}
          </option>
        ))}
      </select>
    </label>
  );
}
