import type { Metadata } from "next";
import Link from "next/link";
import { GraduationCap } from "lucide-react";
import { Button } from "@/components/Button";
import { listCoursesForAdmin } from "@/lib/academy/queries";
import {
  AdminHeading,
  DataTable,
  StatusBadge,
  FormSection,
  InputField,
  TextareaField,
  SelectField,
  EmptyState,
  Toolbar,
  FilterPill,
  SearchInput,
  KpiCard,
  formatAdminDate,
  type Column,
} from "@/components/admin";
import { createCourse } from "./actions";

export const metadata: Metadata = { title: "Academy" };
export const dynamic = "force-dynamic";

type Course = Awaited<ReturnType<typeof listCoursesForAdmin>>[number];

const STATUS_FILTERS = ["all", "draft", "published", "archived"] as const;
type StatusFilter = (typeof STATUS_FILTERS)[number];
function isStatusFilter(v: string | undefined): v is StatusFilter {
  return typeof v === "string" && (STATUS_FILTERS as readonly string[]).includes(v);
}

export default async function AdminAcademyPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string; q?: string }>;
}) {
  const params = await searchParams;
  const statusFilter: StatusFilter = isStatusFilter(params.status) ? params.status : "all";
  const query = (params.q ?? "").trim().toLowerCase();

  const rows = await listCoursesForAdmin();
  const counts = rows.reduce<Record<string, number>>((acc, r) => {
    acc[r.status] = (acc[r.status] ?? 0) + 1;
    return acc;
  }, {});

  let filtered = rows;
  if (statusFilter !== "all") filtered = filtered.filter((r) => r.status === statusFilter);
  if (query) {
    filtered = filtered.filter((r) =>
      [r.title, r.topic, r.level].join(" ").toLowerCase().includes(query),
    );
  }

  const buildHref = (status: StatusFilter) => {
    const parts: string[] = [];
    if (status !== "all") parts.push(`status=${status}`);
    if (query) parts.push(`q=${encodeURIComponent(query)}`);
    return `/admin/academy${parts.length ? `?${parts.join("&")}` : ""}`;
  };

  const columns: Column<Course>[] = [
    {
      key: "title",
      header: "Course",
      cell: (c) => (
        <div className="min-w-0">
          <Link
            href={`/admin/academy/${c.id}`}
            className="truncate font-semibold text-[var(--color-ink)] hover:text-[var(--color-blue)]"
          >
            {c.title}
          </Link>
          <div className="truncate text-[12px] text-[var(--color-slate)]">{c.topic}</div>
        </div>
      ),
    },
    {
      key: "level",
      header: "Level",
      cell: (c) => <StatusBadge label={c.level} />,
    },
    {
      key: "status",
      header: "Status",
      cell: (c) => <StatusBadge label={c.status} dot />,
    },
    {
      key: "updated",
      header: "Updated",
      cell: (c) => (
        <span className="text-[13px] text-[var(--color-slate)]">
          {formatAdminDate(c.updatedAt)}
        </span>
      ),
    },
    {
      key: "actions",
      header: "",
      align: "right",
      cell: (c) => (
        <Link
          href={`/admin/academy/${c.id}`}
          className="text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
        >
          Edit →
        </Link>
      ),
    },
  ];

  return (
    <>
      <AdminHeading
        eyebrow="Content"
        title="Academy"
        lede="Courses, modules, and lessons for the membership LMS."
      />

      <div className="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-4">
        <KpiCard label="Total courses" value={rows.length} Icon={GraduationCap} tone="ink" />
        <KpiCard label="Published" value={counts.published ?? 0} tone="emerald" />
        <KpiCard label="Drafts" value={counts.draft ?? 0} tone="amber" />
        <KpiCard label="Archived" value={counts.archived ?? 0} tone="slate" />
      </div>

      <div className="mb-6">
        <FormSection
          title="New course"
          description="Start with the skeleton — add modules and lessons on the detail page."
        >
          <form action={createCourse} className="grid gap-4 md:grid-cols-2">
            <InputField
              label="Title"
              name="title"
              required
              minLength={3}
              maxLength={200}
              wrapClassName="md:col-span-2"
            />
            <SelectField
              label="Level"
              name="level"
              defaultValue="Foundation"
              options={[
                { value: "Foundation", label: "Foundation" },
                { value: "Intermediate", label: "Intermediate" },
                { value: "Advanced", label: "Advanced" },
              ]}
            />
            <InputField
              label="Topic"
              name="topic"
              required
              maxLength={120}
              defaultValue="General"
            />
            <TextareaField
              label="Short description"
              name="shortDescription"
              rows={2}
              maxLength={400}
              wrapClassName="md:col-span-2"
            />
            <div className="md:col-span-2">
              <Button type="submit" variant="primary" className="!px-4 !py-2 !text-[13px]">
                Create course
              </Button>
            </div>
          </form>
        </FormSection>
      </div>

      <div className="mb-4">
        <Toolbar
          actions={
            <form method="GET" action="/admin/academy">
              {statusFilter !== "all" && <input type="hidden" name="status" value={statusFilter} />}
              <SearchInput defaultValue={params.q ?? ""} placeholder="Search title, topic, level…" />
            </form>
          }
        >
          {STATUS_FILTERS.map((s) => (
            <FilterPill
              key={s}
              href={buildHref(s)}
              label={s}
              count={s === "all" ? rows.length : counts[s] ?? 0}
              active={statusFilter === s}
            />
          ))}
        </Toolbar>
      </div>

      {filtered.length === 0 ? (
        <EmptyState
          Icon={GraduationCap}
          title="No courses match"
          description="Create a new course or clear filters."
        />
      ) : (
        <DataTable columns={columns} rows={filtered} rowKey={(c) => c.id} />
      )}
    </>
  );
}
