import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { Button } from "@/components/Button";
import { getBlogPostForAdmin } from "@/lib/blog/queries";
import {
  AdminHeading,
  FormSection,
  InputField,
  TextareaField,
  StatusBadge,
  ConfirmButton,
  ImageUpload,
  MarkdownEditor,
  formatAdminDateTime,
} from "@/components/admin";
import { updateBlogPost, setBlogPostStatus, deleteBlogPost } from "../actions";

export const dynamic = "force-dynamic";

const statusOptions = ["draft", "published", "archived"] as const;

export default async function AdminBlogPostEditor({
  params,
}: {
  params: Promise<{ postId: string }>;
}) {
  const { postId } = await params;
  const post = await getBlogPostForAdmin(postId);
  if (!post) notFound();

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

      <AdminHeading
        eyebrow={`Post · ${post.slug}`}
        title={post.title}
        lede={
          post.publishedAt
            ? `Published ${formatAdminDateTime(post.publishedAt)}`
            : `Created ${formatAdminDateTime(post.createdAt)}`
        }
        actions={<StatusBadge label={post.status} dot />}
      />

      <div className="grid gap-6 lg:grid-cols-[minmax(0,3fr)_minmax(0,1fr)]">
        <div className="flex flex-col gap-6">
          <FormSection title="Content" description="Edit title, copy, and media. Save when done.">
            <form action={updateBlogPost} className="grid gap-5 md:grid-cols-2">
              <input type="hidden" name="id" value={post.id} />
              <InputField
                label="Title (H1)"
                name="title"
                defaultValue={post.title}
                required
                minLength={3}
                maxLength={200}
                wrapClassName="md:col-span-2"
                hint="This is the post's top-level headline and meta title."
              />
              <InputField
                label="Author name"
                name="authorName"
                defaultValue={post.authorName}
                hint="Displayed as the byline."
              />
              <InputField
                label="Tags (comma-separated)"
                name="tags"
                defaultValue={(post.tags ?? []).join(", ")}
                hint="e.g. shoulder, frcs, rotator-cuff"
              />
              <InputField
                label="Scheduled publish (optional)"
                name="scheduledAt"
                type="datetime-local"
                defaultValue={
                  post.scheduledAt
                    ? new Date(post.scheduledAt.getTime() - post.scheduledAt.getTimezoneOffset() * 60_000)
                        .toISOString()
                        .slice(0, 16)
                    : ""
                }
                hint="Even if you Publish now, the post is hidden from /blog until this time passes. Leave blank for immediate release."
              />
              <div className="md:col-span-2">
                <ImageUpload
                  name="coverImage"
                  altName="coverImageAlt"
                  folder="blog"
                  label="Cover image"
                  defaultValue={post.coverImage}
                  defaultAlt={post.coverImageAlt}
                />
              </div>
              <TextareaField
                label="Excerpt (subheader / meta description)"
                name="excerpt"
                defaultValue={post.excerpt}
                rows={3}
                maxLength={600}
                wrapClassName="md:col-span-2"
                hint="One or two sentences. Shown on listing pages, search results, and social shares. Up to 600 characters."
              />
              <div className="md:col-span-2">
                <MarkdownEditor
                  name="content"
                  label="Body"
                  defaultValue={post.content}
                  rows={22}
                  maxLength={100_000}
                  folder="blog"
                  hint="Use the toolbar for headings, bold, lists, links, and inline images"
                />
              </div>
              <div className="md:col-span-2 flex flex-wrap items-center gap-3">
                <Button type="submit" variant="primary" className="!px-4 !py-2 !text-[13px]">
                  Save post
                </Button>
                <span className="text-[12px] text-[var(--color-slate)]">
                  Saving does not change the publication status — use the
                  Status panel on the right to publish or archive.
                </span>
              </div>
            </form>
          </FormSection>

          <FormSection
            title="Danger zone"
            description="Deleting this post is permanent. Readers get a 404."
            tone="danger"
          >
            <form action={deleteBlogPost}>
              <input type="hidden" name="id" value={post.id} />
              <ConfirmButton
                label="Delete post"
                confirmLabel="Click again to delete permanently"
                tone="danger"
              />
            </form>
          </FormSection>
        </div>

        <aside className="flex flex-col gap-6">
          <FormSection title="Status" description="Control where this post appears on the site.">
            <div className="flex flex-col gap-2">
              {statusOptions.map((s) => (
                <form key={s} action={setBlogPostStatus}>
                  <input type="hidden" name="id" value={post.id} />
                  <input type="hidden" name="status" value={s} />
                  <button
                    type="submit"
                    disabled={post.status === s}
                    className={
                      post.status === s
                        ? "w-full rounded-lg bg-[var(--color-blue)] px-3 py-2 text-[13px] font-semibold text-white"
                        : "w-full rounded-lg border border-[var(--color-line)] bg-white px-3 py-2 text-[13px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
                    }
                  >
                    {post.status === s ? `Current · ${s}` : `Set to ${s}`}
                  </button>
                </form>
              ))}
            </div>
          </FormSection>

          <FormSection title="Preview">
            <Link
              href={`/blog/${post.slug}`}
              target="_blank"
              className="inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
            >
              Open preview →
            </Link>
          </FormSection>
        </aside>
      </div>
    </>
  );
}
