"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Save, ArrowLeft } from "lucide-react";
import Link from "next/link";

type BlogData = {
  id?: string;
  title: string;
  slug: string;
  author: string;
  image: string;
  content: string;
};

export function BlogEditor({ initial }: { initial?: BlogData }) {
  const router = useRouter();
  const isEditing = Boolean(initial?.id);

  const [form, setForm] = useState<BlogData>(
    initial ?? { title: "", slug: "", author: "BITSOL Team", image: "", content: "" }
  );
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

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

  function handleTitleChange(title: string) {
    setForm((f) => ({ ...f, title, slug: isEditing ? f.slug : slugify(title) }));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setError("");
    try {
      const url = isEditing ? `/api/admin/blogs/${initial!.id}` : "/api/admin/blogs";
      const method = isEditing ? "PUT" : "POST";
      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      if (!res.ok) {
        const data = await res.json();
        setError(data.error || "Save failed");
        return;
      }
      router.push("/admin/blogs");
      router.refresh();
    } catch {
      setError("Network error");
    } finally {
      setSaving(false);
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6 max-w-4xl">
      <div className="flex items-center gap-4">
        <Link href="/admin/blogs" className="p-2 rounded-xl text-gray-400 hover:bg-white/5 hover:text-white transition-all">
          <ArrowLeft className="w-5 h-5" />
        </Link>
        <div>
          <h1 className="text-3xl font-bold text-white" style={{ fontFamily: "var(--font-poppins)" }}>{isEditing ? "Edit Post" : "New Post"}</h1>
          <p className="text-muted-foreground text-sm mt-0.5">Fill in the details to {isEditing ? "update" : "publish"} your article</p>
        </div>
      </div>

      <div className="glass p-6 rounded-2xl space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-2 block">Title *</label>
            <input
              required
              value={form.title}
              onChange={(e) => handleTitleChange(e.target.value)}
              placeholder="My Awesome Post"
              className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white outline-none focus:border-primary transition-colors"
            />
          </div>
          <div>
            <label className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-2 block">Slug *</label>
            <input
              required
              value={form.slug}
              onChange={(e) => setForm((f) => ({ ...f, slug: e.target.value }))}
              placeholder="my-awesome-post"
              className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white font-mono text-sm outline-none focus:border-primary transition-colors"
            />
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-2 block">Author</label>
            <input
              value={form.author}
              onChange={(e) => setForm((f) => ({ ...f, author: e.target.value }))}
              placeholder="BITSOL Team"
              className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white outline-none focus:border-primary transition-colors"
            />
          </div>
          <div>
            <label className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-2 block">Cover Image URL</label>
            <input
              value={form.image}
              onChange={(e) => setForm((f) => ({ ...f, image: e.target.value }))}
              placeholder="https://..."
              className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white outline-none focus:border-primary transition-colors"
            />
          </div>
        </div>

        <div>
          <label className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-2 block">Content * (Markdown supported)</label>
          <textarea
            required
            rows={18}
            value={form.content}
            onChange={(e) => setForm((f) => ({ ...f, content: e.target.value }))}
            placeholder="Write your blog post content here..."
            className="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white font-mono text-sm outline-none focus:border-primary transition-colors resize-y"
          />
        </div>

        {error && (
          <p className="text-red-400 text-sm bg-red-500/10 border border-red-500/20 rounded-xl px-4 py-3">{error}</p>
        )}

        <button
          type="submit"
          disabled={saving}
          className="flex items-center gap-2 px-6 py-3 bg-primary text-white font-medium rounded-xl hover:bg-primary/90 transition-colors neon-border-blue disabled:opacity-60"
        >
          <Save className="w-4 h-4" />
          {saving ? "Saving..." : isEditing ? "Update Post" : "Publish Post"}
        </button>
      </div>
    </form>
  );
}
