"use client";

import { useMemo, useRef, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Sparkles } from "lucide-react";
import { AdminGuard } from "@/components/admin/AdminGuard";
import { AdminShell } from "@/components/admin/AdminShell";
import { BlogBodyEditor } from "@/components/admin/BlogBodyEditor";
import { BlogImageUploader } from "@/components/admin/BlogImageUploader";
import { adminRequest } from "@/lib/admin-api";
import { formatBlogDate } from "@/lib/blog-date";

function slugify(value: string) {
  return value
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

export default function AddBlogPage() {
  const router = useRouter();
  const formRef = useRef<HTMLFormElement>(null);
  const [title, setTitle] = useState("");
  const [slug, setSlug] = useState("");
  const [assistTopic, setAssistTopic] = useState("");
  const [publishedDate, setPublishedDate] = useState("");
  const [imageUrl, setImageUrl] = useState("");
  const [imageAlt, setImageAlt] = useState("");
  const [editorText, setEditorText] = useState("");
  const [status, setStatus] = useState<"idle" | "saving" | "error">("idle");
  const [errorMessage, setErrorMessage] = useState("");
  const generatedSlug = useMemo(() => slugify(title), [title]);

  function updateTitle(value: string) {
    setTitle(value);

    if (!slug || slug === generatedSlug) {
      setSlug(slugify(value));
    }
  }

  function setField(name: string, value: string) {
    const field = formRef.current?.elements.namedItem(name);

    if (field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement) {
      field.value = value;
    }
  }

  function createAssistedDraft() {
    const topic = assistTopic.trim() || "vehicle service tips";
    const cleanTopic = topic.charAt(0).toUpperCase() + topic.slice(1);
    const nextTitle = `${cleanTopic}: what every rider should know`;
    const nextSlug = slugify(nextTitle);
    const today = new Date().toISOString().slice(0, 10);

    setTitle(nextTitle);
    setSlug(nextSlug);
    setField("category", "Vehicle Care");
    setPublishedDate(today);
    setField("readTime", "4 min read");
    setImageUrl("/images/blog-signs-your-car-needs-service.webp");
    setImageAlt(`${cleanTopic} service guide for Ride N Revive customers`);
    setField(
      "excerpt",
      `A simple guide to ${topic.toLowerCase()} so customers can spot issues early, plan service better, and avoid stressful repairs.`,
    );
    setField("sectionHeading", `Why ${topic.toLowerCase()} matters`);
    setField(
      "body",
      `Small vehicle issues often become expensive when they are ignored. Understanding ${topic.toLowerCase()} helps riders notice early warning signs and book support before the problem grows.\n\nA quick inspection can check the basics like fluids, brakes, battery, tyres, lights, and unusual sounds. For daily riders, this keeps the vehicle safer and more predictable.\n\nRide N Revive can help with doorstep inspection and service support, making it easier to handle maintenance without losing time at a workshop.`,
    );
    setEditorText(
      `Small vehicle issues often become expensive when they are ignored. Understanding ${topic.toLowerCase()} helps riders notice early warning signs and book support before the problem grows.\n\nA quick inspection can check the basics like fluids, brakes, battery, tyres, lights, and unusual sounds. For daily riders, this keeps the vehicle safer and more predictable.\n\nRide N Revive can help with doorstep inspection and service support, making it easier to handle maintenance without losing time at a workshop.`,
    );
  }

  async function submit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setStatus("saving");
    setErrorMessage("");

    const formData = new FormData(e.currentTarget);
    const body = String(formData.get("body") ?? "")
      .split(/\n+/)
      .map((paragraph) => paragraph.trim())
      .filter(Boolean);

    try {
      await adminRequest("/api/admin/blogs", {
        method: "POST",
        body: JSON.stringify({
          slug: String(formData.get("slug") || generatedSlug),
          title: String(formData.get("title") ?? ""),
          excerpt: String(formData.get("excerpt") ?? ""),
          category: String(formData.get("category") ?? ""),
          date: formatBlogDate(String(formData.get("date") ?? "")),
          readTime: String(formData.get("readTime") ?? ""),
          image: String(formData.get("image") ?? ""),
          metaImage: String(formData.get("image") ?? ""),
          ogImage: String(formData.get("image") ?? ""),
          imageAlt: String(formData.get("imageAlt") ?? ""),
          metaDescription: String(formData.get("excerpt") ?? ""),
          ogDescription: String(formData.get("excerpt") ?? ""),
          sections: [
            {
              heading: String(formData.get("sectionHeading") ?? ""),
              body,
            },
          ],
        }),
      });

      router.push("/admin/blogs");
    } catch (error) {
      setStatus("error");
      setErrorMessage(error instanceof Error ? error.message : "Could not save blog");
    }
  }

  const input =
    "h-11 w-full rounded-md border border-border bg-white px-3 text-sm font-semibold outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/15";
  const textarea =
    "min-h-28 w-full rounded-md border border-border bg-white px-3 py-3 text-sm font-semibold outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/15";
  const label = "mb-1.5 block text-xs font-black uppercase tracking-[0.14em] text-muted-foreground";

  return (
    <AdminGuard>
      <AdminShell
        title="Add blog"
        lead="Create a blog entry using the same fields as the website blog system."
      >
        <div className="mb-5 rounded-lg border border-primary/20 bg-primary/5 p-5">
          <div className="flex flex-col gap-4 lg:flex-row lg:items-end">
            <div className="flex-1">
              <div className="mb-2 flex items-center gap-2 text-sm font-black text-primary">
                <Sparkles className="h-4 w-4" />
                AI Assist
              </div>
              <label className={label}>Blog topic</label>
              <input
                value={assistTopic}
                onChange={(event) => setAssistTopic(event.target.value)}
                className={input}
                placeholder="Example: monsoon car care tips"
              />
            </div>
            <button
              type="button"
              onClick={createAssistedDraft}
              className="h-11 rounded-md bg-primary px-5 text-sm font-black text-primary-foreground transition hover:opacity-95"
            >
              Generate draft
            </button>
          </div>
        </div>

        <form
          ref={formRef}
          onSubmit={submit}
          className="rounded-lg border border-border bg-white p-5 shadow-sm"
        >
          <div className="grid gap-5 lg:grid-cols-2">
            <div>
              <label className={label}>Title</label>
              <input
                required
                name="title"
                value={title}
                onChange={(event) => updateTitle(event.target.value)}
                className={input}
              />
            </div>
            <div>
              <label className={label}>Slug</label>
              <input
                required
                name="slug"
                value={slug}
                onChange={(event) => setSlug(slugify(event.target.value))}
                className={input}
              />
            </div>
            <div>
              <label className={label}>Category</label>
              <input required name="category" className={input} placeholder="Car Care" />
            </div>
            <div>
              <label className={label}>Date</label>
              <input
                required
                type="date"
                name="date"
                value={publishedDate}
                onChange={(event) => setPublishedDate(event.target.value)}
                className={input}
              />
            </div>
            <div>
              <label className={label}>Read time</label>
              <input required name="readTime" className={input} placeholder="4 min read" />
            </div>
            <input type="hidden" name="image" value={imageUrl} readOnly />
            <div className="lg:col-span-2">
              <BlogImageUploader
                slug={slug || generatedSlug}
                title={title}
                currentImageUrl={imageUrl}
                currentImageAlt={imageAlt}
                onUploaded={(imageUrl) => {
                  setImageUrl(imageUrl);
                  setImageAlt(`${title || slug || generatedSlug} image`);
                }}
              />
            </div>
            <div className="lg:col-span-2">
              <label className={label}>Image alt text</label>
              <input
                required
                name="imageAlt"
                value={imageAlt}
                onChange={(event) => setImageAlt(event.target.value)}
                className={input}
              />
            </div>
            <div className="lg:col-span-2">
              <label className={label}>Short description</label>
              <textarea required name="excerpt" className={textarea} />
              <p className="mt-2 text-xs font-semibold text-muted-foreground">
                Used as meta description and OG description.
              </p>
            </div>
            <div className="lg:col-span-2">
              <label className={label}>Section heading</label>
              <input required name="sectionHeading" className={input} />
            </div>
            <div className="lg:col-span-2">
              <label className={label}>Section body</label>
              <BlogBodyEditor value={editorText} onChange={setEditorText} />
            </div>
          </div>

          {status === "error" ? (
            <p className="mt-5 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm font-semibold text-destructive">
              {errorMessage}
            </p>
          ) : null}

          <div className="sticky bottom-0 z-20 -mx-5 mt-6 flex items-center justify-end gap-3 border-t border-border bg-white/95 px-5 py-4 backdrop-blur">
            <Link
              href="/admin/blogs"
              className="inline-flex h-11 items-center justify-center rounded-md border border-border px-5 text-sm font-black text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
            >
              Cancel
            </Link>
            <button
              disabled={status === "saving"}
              className="h-11 rounded-md bg-primary px-5 text-sm font-black text-primary-foreground transition hover:opacity-95 disabled:opacity-70"
            >
              {status === "saving" ? "Saving..." : "Add blog"}
            </button>
          </div>
        </form>
      </AdminShell>
    </AdminGuard>
  );
}
