import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, ExternalLink, Eye, EyeOff, Trash2 } from "lucide-react";
import { prisma } from "@/lib/db";
import { requireAdmin } from "@/lib/admin-guard";
import { BLOG_CATEGORIES, statusOf } from "@/lib/blog";
import { updateBlogPost, togglePublishFormAction, deleteBlogPostFormAction } from "../../_actions";
import { MarkdownEditor } from "@/components/blog/markdown-editor";
import { TitleSlugInputs } from "@/components/blog/title-slug-inputs";

export const dynamic = "force-dynamic";

type Params = Promise<{ id: string }>;

export default async function EditBlogPost({ params }: { params: Params }) {
  await requireAdmin();
  const { id } = await params;

  const post = await prisma.blogPost.findUnique({ where: { id } });
  if (!post) notFound();

  const status = statusOf(post.publishedAt);

  // Bind id into the update action so the form action receives only formData.
  async function updateAction(formData: FormData): Promise<void> {
    "use server";
    const result = await updateBlogPost(id, formData);
    if (!result.ok) {
      const { redirect } = await import("next/navigation");
      redirect(`/admin/blog/${id}/edit?error=${encodeURIComponent(result.message ?? "error")}`);
    }
  }

  return (
    <div>
      <div className="mb-6 flex flex-wrap items-start justify-between gap-3">
        <div>
          <Link
            href="/admin/blog"
            className="text-ink-muted hover:text-brand-gold inline-flex items-center gap-1.5 text-xs"
          >
            <ArrowLeft className="h-3.5 w-3.5" /> Quay lại danh sách
          </Link>
          <h1 className="font-display text-ink-primary mt-2 text-2xl font-semibold">
            Chỉnh sửa bài
          </h1>
          <div className="text-ink-muted mt-1 flex items-center gap-3 text-xs">
            <span>
              Trạng thái:{" "}
              {status === "published" ? (
                <span className="text-brand-green">Đã xuất bản</span>
              ) : (
                <span>Bản nháp</span>
              )}
            </span>
            <span>·</span>
            <span>{post.views.toLocaleString("vi-VN")} lượt xem</span>
            <span>·</span>
            <span>~{post.readMinutes} phút đọc</span>
          </div>
        </div>

        <div className="flex flex-wrap gap-2">
          {status === "published" && (
            <Link
              href={`/blog/${post.slug}`}
              target="_blank"
              className="border-stroke-subtle text-ink-secondary hover:text-brand-gold inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs transition"
            >
              <ExternalLink className="h-3.5 w-3.5" />
              Xem trang
            </Link>
          )}
          <form action={togglePublishFormAction}>
            <input type="hidden" name="id" value={post.id} />
            <button
              type="submit"
              className="border-stroke-subtle hover:border-brand-gold/40 text-ink-secondary hover:text-brand-gold inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs transition"
            >
              {status === "published" ? (
                <>
                  <EyeOff className="h-3.5 w-3.5" />
                  Gỡ xuất bản
                </>
              ) : (
                <>
                  <Eye className="h-3.5 w-3.5" />
                  Xuất bản
                </>
              )}
            </button>
          </form>
          <form action={deleteBlogPostFormAction}>
            <input type="hidden" name="id" value={post.id} />
            <button
              type="submit"
              className="border-brand-red/30 text-brand-red hover:bg-brand-red/10 inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs transition"
            >
              <Trash2 className="h-3.5 w-3.5" />
              Xóa bài
            </button>
          </form>
        </div>
      </div>

      <form action={updateAction} className="max-w-4xl space-y-6">
        <section className="border-stroke-subtle bg-bg-elevated/40 rounded-xl border p-5">
          <TitleSlugInputs defaultTitle={post.title} defaultSlug={post.slug} slugLocked={true} />

          <label className="mt-4 block">
            <span className="text-ink-muted mb-1 block text-[11px] tracking-[0.15em] uppercase">
              Tóm tắt <span className="text-brand-red">*</span>
            </span>
            <textarea
              name="excerpt"
              required
              maxLength={500}
              rows={3}
              defaultValue={post.excerpt}
              className="border-stroke-subtle bg-bg-base text-ink-primary focus:border-brand-gold/50 w-full rounded-md border px-3 py-2 text-sm transition outline-none"
            />
          </label>
        </section>

        <section className="border-stroke-subtle bg-bg-elevated/40 rounded-xl border p-5">
          <span className="text-ink-muted mb-2 block text-[11px] tracking-[0.15em] uppercase">
            Nội dung (Markdown) <span className="text-brand-red">*</span>
          </span>
          <MarkdownEditor name="content" defaultValue={post.content} />
        </section>

        <section className="border-stroke-subtle bg-bg-elevated/40 rounded-xl border p-5">
          <div className="grid gap-4 md:grid-cols-2">
            <label className="block">
              <span className="text-ink-muted mb-1 block text-[11px] tracking-[0.15em] uppercase">
                Chuyên mục <span className="text-brand-red">*</span>
              </span>
              <select
                name="category"
                required
                defaultValue={post.category}
                className="border-stroke-subtle bg-bg-base text-ink-primary focus:border-brand-gold/50 w-full rounded-md border px-3 py-2 text-sm transition outline-none"
              >
                {BLOG_CATEGORIES.map((c) => (
                  <option key={c.key} value={c.key}>
                    {c.label}
                  </option>
                ))}
              </select>
            </label>

            <label className="block">
              <span className="text-ink-muted mb-1 block text-[11px] tracking-[0.15em] uppercase">
                Tác giả
              </span>
              <input
                type="text"
                name="authorName"
                defaultValue={post.authorName}
                className="border-stroke-subtle bg-bg-base text-ink-primary focus:border-brand-gold/50 w-full rounded-md border px-3 py-2 text-sm transition outline-none"
              />
            </label>

            <label className="block md:col-span-2">
              <span className="text-ink-muted mb-1 block text-[11px] tracking-[0.15em] uppercase">
                Tags
              </span>
              <input
                type="text"
                name="tags"
                defaultValue={post.tags.join(", ")}
                placeholder="tu vi, mệnh, cung mệnh"
                className="border-stroke-subtle bg-bg-base text-ink-primary focus:border-brand-gold/50 w-full rounded-md border px-3 py-2 text-sm transition outline-none"
              />
              <span className="text-ink-muted mt-1 block text-xs">
                Phân cách bằng dấu phẩy. Tối đa 20 tag.
              </span>
            </label>

            <label className="block md:col-span-2">
              <span className="text-ink-muted mb-1 block text-[11px] tracking-[0.15em] uppercase">
                Cover Image (URL)
              </span>
              <input
                type="url"
                name="coverImage"
                defaultValue={post.coverImage ?? ""}
                placeholder="https://..."
                className="border-stroke-subtle bg-bg-base text-ink-primary focus:border-brand-gold/50 w-full rounded-md border px-3 py-2 text-sm transition outline-none"
              />
            </label>
          </div>
        </section>

        <section className="border-stroke-subtle bg-bg-elevated/40 flex items-center justify-between rounded-xl border p-5">
          <div className="text-ink-muted text-xs">
            Tạo: {post.createdAt.toLocaleString("vi-VN")} · Cập nhật:{" "}
            {post.updatedAt.toLocaleString("vi-VN")}
          </div>
          <div className="flex gap-2">
            <Link
              href="/admin/blog"
              className="border-stroke-subtle text-ink-secondary hover:text-ink-primary rounded-md border px-4 py-2 text-sm transition"
            >
              Hủy
            </Link>
            <button
              type="submit"
              className="bg-brand-gold/90 hover:bg-brand-gold text-bg-base rounded-md px-5 py-2 text-sm font-medium transition"
            >
              Lưu thay đổi
            </button>
          </div>
        </section>
      </form>
    </div>
  );
}
