"use client";

import { useEffect, useState, type FormEvent } from "react";
import Link from "next/link";
import { ExternalLink, FileText, Plus, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/Button";
import { useToast } from "@/context/toast-context";
import { pageHref } from "@/lib/page-href";
import type { ContentPageDTO, FooterGroup } from "@/lib/pages";

const footerGroups: { value: FooterGroup; label: string }[] = [
  { value: "company", label: "Company" },
  { value: "support", label: "Support" },
  { value: "legal", label: "Legal" },
  { value: "none", label: "Hidden from footer" },
];

const emptyForm = {
  title: "",
  slug: "",
  excerpt: "",
  content: "",
  published: true,
  showInFooter: true,
  footerGroup: "legal" as FooterGroup,
  sortOrder: 100,
};

export default function AdminPagesPage() {
  const { toast } = useToast();
  const [pages, setPages] = useState<ContentPageDTO[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState(emptyForm);

  const load = async () => {
    const res = await fetch("/api/admin/pages", { credentials: "include" });
    const data = (await res.json()) as { pages?: ContentPageDTO[] };
    setPages(data.pages ?? []);
    setLoading(false);
  };

  useEffect(() => {
    void load();
  }, []);

  const startCreate = () => {
    setEditingId(null);
    setForm(emptyForm);
  };

  const startEdit = (page: ContentPageDTO) => {
    setEditingId(page.id);
    setForm({
      title: page.title,
      slug: page.slug,
      excerpt: page.excerpt,
      content: page.content,
      published: page.published,
      showInFooter: page.showInFooter,
      footerGroup: page.footerGroup,
      sortOrder: page.sortOrder,
    });
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const onSave = async (event: FormEvent) => {
    event.preventDefault();
    if (!form.title.trim()) {
      toast("Title is required", "error");
      return;
    }
    setSaving(true);
    try {
      const res = await fetch("/api/admin/pages", {
        method: editingId ? "PATCH" : "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(
          editingId ? { id: editingId, ...form } : form,
        ),
      });
      const data = (await res.json()) as { error?: string };
      if (!res.ok) {
        toast(data.error ?? "Could not save page", "error");
        return;
      }
      toast(editingId ? "Page updated" : "Page created");
      startCreate();
      await load();
    } finally {
      setSaving(false);
    }
  };

  const onDelete = async (id: string) => {
    if (!confirm("Delete this page? This cannot be undone.")) return;
    const res = await fetch(
      `/api/admin/pages?id=${encodeURIComponent(id)}`,
      { method: "DELETE", credentials: "include" },
    );
    if (!res.ok) {
      toast("Could not delete page", "error");
      return;
    }
    if (editingId === id) startCreate();
    await load();
    toast("Page deleted");
  };

  const fieldClass =
    "w-full rounded-xl border border-border bg-background px-3 text-sm text-foreground outline-none focus:border-emerald-500/50";

  return (
    <div className="mx-auto max-w-6xl space-y-8">
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div>
          <h1 className="text-2xl font-semibold text-foreground">
            Content pages
          </h1>
          <p className="mt-1 text-sm text-muted">
            Edit privacy, terms, refunds, about, contact, and create any custom
            page. Footer links update automatically.
          </p>
        </div>
        <Button
          type="button"
          variant="secondary"
          className="h-10 rounded-xl"
          onClick={startCreate}
        >
          <Plus className="mr-1.5 h-4 w-4" />
          New page
        </Button>
      </div>

      <form
        onSubmit={onSave}
        className="space-y-4 rounded-2xl border border-border bg-card p-5"
      >
        <div className="flex items-center gap-2 text-sm font-medium text-foreground">
          <FileText className="h-4 w-4 text-emerald-500" />
          {editingId ? "Edit page" : "Create page"}
        </div>

        <div className="grid gap-4 sm:grid-cols-2">
          <label className="block space-y-1.5 text-sm">
            <span className="text-muted">Title</span>
            <input
              value={form.title}
              onChange={(event) =>
                setForm((prev) => ({
                  ...prev,
                  title: event.target.value,
                  slug: editingId
                    ? prev.slug
                    : event.target.value
                        .toLowerCase()
                        .trim()
                        .replace(/[^a-z0-9]+/g, "-")
                        .replace(/(^-|-$)/g, ""),
                }))
              }
              className={`${fieldClass} h-11`}
              required
            />
          </label>
          <label className="block space-y-1.5 text-sm">
            <span className="text-muted">Slug (URL)</span>
            <input
              value={form.slug}
              onChange={(event) =>
                setForm((prev) => ({ ...prev, slug: event.target.value }))
              }
              className={`${fieldClass} h-11`}
              placeholder="privacy"
            />
            {form.slug ? (
              <span className="block text-xs text-muted">
                Public URL: {pageHref(form.slug)}
              </span>
            ) : null}
          </label>
        </div>

        <label className="block space-y-1.5 text-sm">
          <span className="text-muted">Short excerpt</span>
          <input
            value={form.excerpt}
            onChange={(event) =>
              setForm((prev) => ({ ...prev, excerpt: event.target.value }))
            }
            className={`${fieldClass} h-11`}
            placeholder="Shown under the page title"
          />
        </label>

        <label className="block space-y-1.5 text-sm">
          <span className="text-muted">Page content</span>
          <textarea
            value={form.content}
            onChange={(event) =>
              setForm((prev) => ({ ...prev, content: event.target.value }))
            }
            rows={14}
            className={`${fieldClass} py-3 font-mono text-[13px] leading-relaxed`}
            placeholder="Write page content. Use blank lines to separate paragraphs."
          />
        </label>

        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <label className="block space-y-1.5 text-sm">
            <span className="text-muted">Footer group</span>
            <select
              value={form.footerGroup}
              onChange={(event) =>
                setForm((prev) => ({
                  ...prev,
                  footerGroup: event.target.value as FooterGroup,
                }))
              }
              className={`${fieldClass} h-11`}
            >
              {footerGroups.map((group) => (
                <option key={group.value} value={group.value}>
                  {group.label}
                </option>
              ))}
            </select>
          </label>
          <label className="block space-y-1.5 text-sm">
            <span className="text-muted">Sort order</span>
            <input
              type="number"
              value={form.sortOrder}
              onChange={(event) =>
                setForm((prev) => ({
                  ...prev,
                  sortOrder: Number(event.target.value) || 0,
                }))
              }
              className={`${fieldClass} h-11`}
            />
          </label>
          <label className="flex h-11 items-center gap-2 self-end text-sm text-foreground">
            <input
              type="checkbox"
              checked={form.published}
              onChange={(event) =>
                setForm((prev) => ({
                  ...prev,
                  published: event.target.checked,
                }))
              }
              className="rounded border-border"
            />
            Published
          </label>
          <label className="flex h-11 items-center gap-2 self-end text-sm text-foreground">
            <input
              type="checkbox"
              checked={form.showInFooter}
              onChange={(event) =>
                setForm((prev) => ({
                  ...prev,
                  showInFooter: event.target.checked,
                }))
              }
              className="rounded border-border"
            />
            Show in footer
          </label>
        </div>

        <div className="flex flex-wrap justify-end gap-2">
          {editingId ? (
            <Button
              type="button"
              variant="secondary"
              className="h-11 rounded-xl"
              onClick={startCreate}
            >
              Cancel
            </Button>
          ) : null}
          <Button type="submit" disabled={saving} className="h-11 rounded-xl">
            {saving
              ? "Saving…"
              : editingId
                ? "Save changes"
                : "Create page"}
          </Button>
        </div>
      </form>

      <section className="overflow-hidden rounded-2xl border border-border bg-card">
        <div className="border-b border-border px-5 py-3">
          <p className="text-sm font-medium text-foreground">
            All pages ({pages.length})
          </p>
        </div>
        {loading ? (
          <p className="px-5 py-8 text-sm text-muted">Loading pages…</p>
        ) : pages.length === 0 ? (
          <p className="px-5 py-8 text-sm text-muted">No pages yet.</p>
        ) : (
          <ul className="divide-y divide-border">
            {pages.map((page) => (
              <li
                key={page.id}
                className="flex flex-col gap-3 px-5 py-4 sm:flex-row sm:items-center sm:justify-between"
              >
                <div className="min-w-0">
                  <div className="flex flex-wrap items-center gap-2">
                    <p className="font-medium text-foreground">{page.title}</p>
                    {!page.published ? (
                      <span className="rounded-full bg-surface px-2 py-0.5 text-[10px] uppercase tracking-wide text-muted">
                        Draft
                      </span>
                    ) : null}
                    {page.showInFooter ? (
                      <span className="rounded-full bg-emerald-500/10 px-2 py-0.5 text-[10px] uppercase tracking-wide text-emerald-700 dark:text-emerald-400">
                        {page.footerGroup}
                      </span>
                    ) : null}
                  </div>
                  <p className="mt-1 truncate text-xs text-muted">
                    /{page.slug}
                    {page.excerpt ? ` · ${page.excerpt}` : ""}
                  </p>
                </div>
                <div className="flex shrink-0 flex-wrap gap-2">
                  <Link
                    href={pageHref(page.slug)}
                    target="_blank"
                    className="inline-flex h-9 items-center gap-1.5 rounded-xl border border-border px-3 text-xs font-medium text-foreground transition hover:bg-surface"
                  >
                    <ExternalLink className="h-3.5 w-3.5" />
                    View
                  </Link>
                  <button
                    type="button"
                    onClick={() => startEdit(page)}
                    className="h-9 rounded-xl bg-foreground px-3 text-xs font-medium text-background"
                  >
                    Edit
                  </button>
                  <button
                    type="button"
                    onClick={() => void onDelete(page.id)}
                    className="inline-flex h-9 items-center gap-1 rounded-xl border border-border px-3 text-xs font-medium text-red-600 transition hover:bg-red-500/10 dark:text-red-400"
                  >
                    <Trash2 className="h-3.5 w-3.5" />
                    Delete
                  </button>
                </div>
              </li>
            ))}
          </ul>
        )}
      </section>
    </div>
  );
}
