"use client";
import { useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { slugify } from "@/lib/id";
import RichTextEditor from "@/components/admin/RichTextEditor";
import QrCodeCard from "@/components/QrCodeCard";

export default function BlogPostForm({
  initial,
  postId,
  allCategories = [],
  initialCategoryIds = [],
}: {
  initial?: any;
  postId?: string;
  allCategories?: { id: string; name: string; slug: string }[];
  initialCategoryIds?: string[];
}) {
  const router = useRouter();
  const featuredInputRef = useRef<HTMLInputElement>(null);
  const galleryInputRef = useRef<HTMLInputElement>(null);
  const [uploadingFeatured, setUploadingFeatured] = useState(false);
  const [uploadingGallery, setUploadingGallery] = useState(false);
  const [slugTouched, setSlugTouched] = useState(!!initial?.slug);
  const [saving, setSaving] = useState(false);
  const [categoryIds, setCategoryIds] = useState<string[]>(initialCategoryIds);
  const [activeTab, setActiveTab] = useState<"write" | "preview">("write");

  function toggleCategory(id: string) {
    setCategoryIds((prev) => (prev.includes(id) ? prev.filter((c) => c !== id) : [...prev, id]));
  }

  const [form, setForm] = useState({
    title: initial?.title || "",
    slug: initial?.slug || "",
    excerpt: initial?.excerpt || "",
    contentHtml: initial?.contentHtml || "",
    featuredImageUrl: initial?.featuredImageUrl || "",
    galleryImages: (initial?.galleryImages ? JSON.parse(initial.galleryImages) : []) as string[],
    status: initial?.status || "draft",
    metaTitle: initial?.metaTitle || "",
    metaDescription: initial?.metaDescription || "",
  });

  function update(key: string, value: any) {
    setForm((f) => ({ ...f, [key]: value }));
  }

  function handleTitleChange(title: string) {
    update("title", title);
    if (!slugTouched) update("slug", slugify(title));
  }

  async function uploadTo(file: File): Promise<string | null> {
    const formData = new FormData();
    formData.append("file", file);
    const res = await fetch("/api/upload", { method: "POST", body: formData });
    const data = await res.json();
    return res.ok ? data.url : null;
  }

  async function handleFeaturedUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploadingFeatured(true);
    const url = await uploadTo(file);
    setUploadingFeatured(false);
    if (url) update("featuredImageUrl", url);
    e.target.value = "";
  }

  async function handleGalleryUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const files = Array.from(e.target.files || []);
    if (!files.length) return;
    setUploadingGallery(true);
    const urls = (await Promise.all(files.map(uploadTo))).filter(Boolean) as string[];
    setUploadingGallery(false);
    update("galleryImages", [...form.galleryImages, ...urls]);
    e.target.value = "";
  }

  function removeGalleryImage(url: string) {
    update("galleryImages", form.galleryImages.filter((u: string) => u !== url));
  }

  async function save(status: "draft" | "published") {
    setSaving(true);
    const payload = { ...form, status, galleryImages: JSON.stringify(form.galleryImages), categoryIds };
    const url = postId ? `/api/admin/blog/${postId}` : "/api/admin/blog";
    const res = await fetch(url, {
      method: postId ? "PATCH" : "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    setSaving(false);
    if (res.ok) {
      router.push("/admin/blog");
      router.refresh();
    }
  }

  const inputCls = "w-full bg-neutral-950 border border-neutral-800 rounded-md px-3 py-2 text-sm outline-none focus:border-red-600";

  return (
    <div className="h-[calc(100vh-140px)] flex flex-col">
      {/* Top action bar */}
      <div className="flex items-center justify-between mb-3 shrink-0">
        <div className="flex gap-1 bg-neutral-900 rounded-lg p-1 border border-neutral-800">
          <button
            type="button"
            onClick={() => setActiveTab("write")}
            className={`px-4 py-1.5 rounded text-sm font-medium transition-colors ${activeTab === "write" ? "bg-neutral-700 text-white" : "text-neutral-400 hover:text-white"}`}
          >
            ✏️ Write
          </button>
          <button
            type="button"
            onClick={() => setActiveTab("preview")}
            className={`px-4 py-1.5 rounded text-sm font-medium transition-colors ${activeTab === "preview" ? "bg-neutral-700 text-white" : "text-neutral-400 hover:text-white"}`}
          >
            👁 Preview
          </button>
        </div>
        <div className="flex items-center gap-2">
          {form.status === "published" && (
            <span className="text-xs text-green-500 border border-green-800 rounded-full px-3 py-1">Live</span>
          )}
          <button onClick={() => save("draft")} disabled={saving || !form.title} className="btn-secondary px-4 py-2 text-sm">
            {saving ? "Saving..." : "Save Draft"}
          </button>
          <button onClick={() => save("published")} disabled={saving || !form.title} className="btn-primary px-4 py-2 text-sm">
            {saving ? "Saving..." : "✓ Publish"}
          </button>
        </div>
      </div>

      {/* PREVIEW tab */}
      {activeTab === "preview" ? (
        <div className="flex-1 overflow-y-auto card p-6">
          {form.featuredImageUrl && (
            <img src={form.featuredImageUrl} className="w-full aspect-video object-cover rounded-xl mb-6" alt="" />
          )}
          <h1 className="text-3xl font-bold mb-3">{form.title || <span className="text-neutral-600">No title yet</span>}</h1>
          {form.excerpt && <p className="text-neutral-400 mb-6 text-base">{form.excerpt}</p>}
          <div
            className="prose prose-invert max-w-none"
            dangerouslySetInnerHTML={{ __html: form.contentHtml || "<p class='text-neutral-500'>No content yet</p>" }}
          />
        </div>
      ) : (
        /* WRITE tab — 2 columns on xl screens */
        <div className="flex-1 overflow-hidden grid grid-cols-1 xl:grid-cols-[320px_1fr] gap-4 min-h-0">

          {/* LEFT — metadata sidebar */}
          <div className="overflow-y-auto space-y-3 thin-scrollbar">
            <div className="card p-4 space-y-3">
              <div>
                <label className="block text-xs mb-1 text-neutral-500 font-medium uppercase tracking-wide">Title *</label>
                <input
                  value={form.title}
                  onChange={(e) => handleTitleChange(e.target.value)}
                  placeholder="Post title"
                  className={inputCls}
                />
              </div>
              <div>
                <label className="block text-xs mb-1 text-neutral-500 font-medium uppercase tracking-wide">Slug</label>
                <div className="flex items-center gap-1.5">
                  <span className="text-xs text-neutral-600 shrink-0">/blog/</span>
                  <input
                    value={form.slug}
                    onChange={(e) => { setSlugTouched(true); update("slug", slugify(e.target.value)); }}
                    className={inputCls}
                  />
                </div>
              </div>
              <div>
                <label className="block text-xs mb-1 text-neutral-500 font-medium uppercase tracking-wide">Excerpt</label>
                <textarea
                  value={form.excerpt}
                  onChange={(e) => update("excerpt", e.target.value)}
                  rows={2}
                  placeholder="Short description for listing page"
                  className={inputCls}
                />
              </div>
            </div>

            <div className="card p-4">
              <p className="text-xs font-medium text-neutral-500 uppercase tracking-wide mb-2">Categories</p>
              {allCategories.length === 0 ? (
                <p className="text-xs text-neutral-600">No categories yet — <a href="/admin/categories" className="text-red-500 underline">add some</a>.</p>
              ) : (
                <div className="flex flex-wrap gap-1.5">
                  {allCategories.map((c) => {
                    const active = categoryIds.includes(c.id);
                    return (
                      <button
                        type="button"
                        key={c.id}
                        onClick={() => toggleCategory(c.id)}
                        className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${active ? "bg-red-600 text-white" : "bg-neutral-900 border border-neutral-800 text-neutral-400 hover:border-neutral-600"}`}
                      >
                        {c.name}
                      </button>
                    );
                  })}
                </div>
              )}
            </div>

            <div className="card p-4 space-y-3">
              <p className="text-xs font-medium text-neutral-500 uppercase tracking-wide">Featured Image</p>
              <div className="flex items-start gap-3">
                <div className="w-20 h-20 rounded-lg bg-neutral-900 border border-neutral-800 flex items-center justify-center overflow-hidden shrink-0">
                  {form.featuredImageUrl
                    ? <img src={form.featuredImageUrl} className="w-full h-full object-cover" />
                    : <span className="text-xl opacity-30">🖼</span>
                  }
                </div>
                <div className="space-y-1.5 flex-1">
                  <input ref={featuredInputRef} type="file" accept="image/*" className="hidden" onChange={handleFeaturedUpload} />
                  <button type="button" onClick={() => featuredInputRef.current?.click()} disabled={uploadingFeatured} className="btn-secondary px-3 py-1.5 text-xs w-full">
                    {uploadingFeatured ? "Uploading..." : "Upload Image"}
                  </button>
                  {form.featuredImageUrl && (
                    <button type="button" onClick={() => update("featuredImageUrl", "")} className="text-xs text-red-500 hover:text-red-400 w-full text-center">Remove</button>
                  )}
                </div>
              </div>

              <p className="text-xs font-medium text-neutral-500 uppercase tracking-wide">Gallery</p>
              <div className="flex flex-wrap gap-1.5">
                {form.galleryImages.map((url: string) => (
                  <div key={url} className="relative w-14 h-14 rounded overflow-hidden group">
                    <img src={url} className="w-full h-full object-cover" />
                    <button type="button" onClick={() => removeGalleryImage(url)} className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 flex items-center justify-center text-white text-sm transition-opacity">✕</button>
                  </div>
                ))}
                <input ref={galleryInputRef} type="file" accept="image/*" multiple className="hidden" onChange={handleGalleryUpload} />
                <button
                  type="button"
                  onClick={() => galleryInputRef.current?.click()}
                  disabled={uploadingGallery}
                  className="w-14 h-14 rounded border border-dashed border-neutral-700 flex items-center justify-center text-neutral-500 hover:border-neutral-500 text-xl"
                >
                  {uploadingGallery ? "…" : "+"}
                </button>
              </div>
            </div>

            <div className="card p-4 space-y-3">
              <p className="text-xs font-medium text-neutral-500 uppercase tracking-wide">SEO</p>
              <div>
                <div className="flex items-center justify-between mb-1">
                  <label className="text-xs text-neutral-500">Title</label>
                  <span className={`text-xs ${form.metaTitle.length > 60 ? "text-amber-500" : "text-neutral-600"}`}>{form.metaTitle.length}/60</span>
                </div>
                <input value={form.metaTitle} onChange={(e) => update("metaTitle", e.target.value)} placeholder="Defaults to post title" className={inputCls} />
              </div>
              <div>
                <div className="flex items-center justify-between mb-1">
                  <label className="text-xs text-neutral-500">Description</label>
                  <span className={`text-xs ${form.metaDescription.length > 160 ? "text-amber-500" : "text-neutral-600"}`}>{form.metaDescription.length}/160</span>
                </div>
                <textarea value={form.metaDescription} onChange={(e) => update("metaDescription", e.target.value)} rows={2} placeholder="Defaults to excerpt" className={inputCls} />
              </div>
            </div>

            {postId && form.status === "published" && form.slug && (
              <div className="card p-4">
                <p className="text-xs font-medium text-neutral-500 uppercase tracking-wide mb-2">QR Code</p>
                <QrCodeCard path={`/blog/${form.slug}`} label={`/blog/${form.slug}`} />
              </div>
            )}
          </div>

          {/* RIGHT — editor fills remaining space */}
          <div className="overflow-hidden flex flex-col min-h-0">
            <label className="block text-xs mb-1.5 text-neutral-500 font-medium uppercase tracking-wide shrink-0">Content</label>
            <div className="flex-1 min-h-0 overflow-hidden">
              <RichTextEditor value={form.contentHtml} onChange={(html) => update("contentHtml", html)} />
            </div>
          </div>

        </div>
      )}
    </div>
  );
}
