import type { Metadata } from "next";
import Link from "next/link";
import { FileText, Archive } from "lucide-react";
import { Button } from "@/components/Button";
import { listBlogPostsForAdmin } from "@/lib/blog/queries";
import { getLegacyPosts } from "@/lib/legacy/content";
import {
  AdminHeading,
  DataTable,
  StatusBadge,
  FormSection,
  InputField,
  TextareaField,
  EmptyState,
  Toolbar,
  FilterPill,
  SearchInput,
  KpiCard,
  formatAdminDate,
  type Column,
} from "@/components/admin";
import { createBlogPost, importLegacyContent } from "./actions";

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

type Post = Awaited<ReturnType<typeof listBlogPostsForAdmin>>[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 AdminBlogPage({
  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 posts = await listBlogPostsForAdmin();
  const counts = posts.reduce<Record<string, number>>((acc, p) => {
    acc[p.status] = (acc[p.status] ?? 0) + 1;
    return acc;
  }, {});
  const total = posts.length;
  const published = counts.published ?? 0;
  const draft = counts.draft ?? 0;
  const legacyPosts = getLegacyPosts();
  const legacyImported = posts.filter((p) => p.slug.startsWith("legacy-")).length;
  const legacyPending = Math.max(0, legacyPosts.length - legacyImported);

  let filtered = posts;
  if (statusFilter !== "all") filtered = filtered.filter((p) => p.status === statusFilter);
  if (query) {
    filtered = filtered.filter((p) =>
      [p.title, p.slug].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/blog${parts.length ? `?${parts.join("&")}` : ""}`;
  };

  const columns: Column<Post>[] = [
    {
      key: "title",
      header: "Title",
      cell: (p) => (
        <div className="min-w-0">
          <Link
            href={`/admin/blog/${p.id}`}
            className="truncate font-semibold text-[var(--color-ink)] hover:text-[var(--color-blue)]"
          >
            {p.title}
          </Link>
          <div className="truncate text-[12px] text-[var(--color-slate)]">{p.slug}</div>
        </div>
      ),
    },
    {
      key: "status",
      header: "Status",
      cell: (p) => <StatusBadge label={p.status} dot />,
    },
    {
      key: "created",
      header: "Created",
      cell: (p) => (
        <span className="text-[13px] text-[var(--color-slate)]">
          {formatAdminDate(p.createdAt)}
        </span>
      ),
    },
    {
      key: "actions",
      header: "",
      align: "right",
      cell: (p) => (
        <Link
          href={`/admin/blog/${p.id}`}
          className="text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
        >
          Edit →
        </Link>
      ),
    },
  ];

  return (
    <>
      <AdminHeading
        eyebrow="Content"
        title="Blog"
        lede="Drafts, scheduled stories, and the live archive."
      />

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

      <div className="mb-6 grid gap-6 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
        <FormSection title="New post" description="Create the skeleton — edit on the next screen.">
          <form action={createBlogPost} className="grid gap-4">
            <InputField
              label="Title"
              name="title"
              type="text"
              required
              minLength={3}
              maxLength={200}
            />
            <TextareaField
              label="Excerpt"
              name="excerpt"
              rows={2}
              maxLength={600}
              hint="Shown on listing pages and in search results. 600 chars max."
            />
            <div>
              <Button type="submit" variant="primary" className="!px-4 !py-2 !text-[13px]">
                Create post
              </Button>
            </div>
          </form>
        </FormSection>

        <FormSection
          title="Legacy archive"
          description={`${legacyPosts.length} posts staged from the old WordPress site. Imports as drafts — review before publishing.`}
        >
          <dl className="grid grid-cols-2 gap-3 text-[13px]">
            <div className="rounded-lg border border-[var(--color-line)] bg-[var(--color-line)]/20 p-3">
              <dt className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                Imported
              </dt>
              <dd className="mt-1 font-display text-[22px] font-extrabold text-[var(--color-ink)]">
                {legacyImported}
              </dd>
            </div>
            <div className="rounded-lg border border-[var(--color-line)] bg-[var(--color-line)]/20 p-3">
              <dt className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                Pending
              </dt>
              <dd className="mt-1 font-display text-[22px] font-extrabold text-[var(--color-ink)]">
                {legacyPending}
              </dd>
            </div>
          </dl>
          <form action={importLegacyContent} className="mt-4 flex flex-wrap gap-2">
            <Button type="submit" variant="secondary" className="!px-4 !py-2 !text-[13px]">
              <Archive className="h-4 w-4" aria-hidden />
              {legacyImported > 0 ? "Re-import & refresh" : "Import legacy posts"}
            </Button>
            <a
              href="/legacy"
              className="inline-flex items-center rounded-lg border border-[var(--color-line)] bg-white px-4 py-2 text-[13px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
            >
              Preview staged
            </a>
          </form>
          <p className="mt-3 text-[12px] text-[var(--color-slate)]">
            Safe to run repeatedly — existing entries update, new ones create as drafts.
          </p>
        </FormSection>
      </div>

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

      {filtered.length === 0 ? (
        <EmptyState
          Icon={FileText}
          title="No posts yet"
          description="Use the form above to create your first post."
        />
      ) : (
        <DataTable columns={columns} rows={filtered} rowKey={(p) => p.id} />
      )}
    </>
  );
}
