import Link from "next/link";
import { redirect } from "next/navigation";
import { createJournalAction } from "@/app/dashboard/actions";
import { DashboardPageHeader } from "@/components/dashboard/page-header";
import { DashboardShell } from "@/components/dashboard/dashboard-shell";
import { requireDashboardContext } from "@/core/auth/dashboard-context";

export default async function NewJournalPage() {
  await requireDashboardContext("journal:manage");

  async function action(formData: FormData) {
    "use server";
    const result = await createJournalAction(formData);
    if (result.ok && result.id) {
      redirect(`/dashboard/journal/${result.id}`);
    }
    redirect("/dashboard/journal/new?error=1");
  }

  return (
    <DashboardShell width="narrow">
      <Link
        href="/dashboard/journal"
        className="text-sm text-[var(--archi-ink-muted)] transition hover:text-[var(--archi-ink)]"
      >
        ← Journal
      </Link>
      <div className="mt-4">
        <DashboardPageHeader
          eyebrow="Content"
          title="New journal post"
          description="Starts as draft. Publish when ready."
        />
      </div>

      <form action={action} className="archi-panel mt-10 space-y-4 p-5 sm:p-6">
        <label className="block text-sm">
          Title
          <input name="title" required className="archi-input mt-2" />
        </label>
        <label className="block text-sm">
          Slug (optional)
          <input name="slug" className="archi-input mt-2" />
        </label>
        <label className="block text-sm">
          Excerpt
          <textarea name="excerpt" rows={2} className="archi-input mt-2" />
        </label>
        <label className="block text-sm">
          Content
          <textarea name="content" rows={12} className="archi-input mt-2" />
        </label>
        <label className="block text-sm">
          SEO title
          <input name="seoTitle" className="archi-input mt-2" />
        </label>
        <label className="block text-sm">
          SEO description
          <textarea
            name="seoDescription"
            rows={2}
            className="archi-input mt-2"
          />
        </label>
        <button type="submit" className="archi-btn-primary">
          Create draft
        </button>
      </form>
    </DashboardShell>
  );
}
