"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Card } from "@/components/ui/card";
import { MediaPickerButton } from "@/components/admin/media-picker";
import { toast } from "sonner";
import { Loader2, Save, Trash2, Plus, X } from "lucide-react";

export type BlogFormValues = {
  id?: string;
  title: string;
  slug: string;
  excerpt: string;
  content: string;
  category: string;
  tags: string[];
  featuredImage: string | null;
  isPublished: boolean;
  publishedAt: string;
  authorName: string;
  metaTitle: string;
  metaDescription: string;
};

export function BlogForm({ initial, isNew }: { initial?: BlogFormValues; isNew?: boolean }) {
  const router = useRouter();
  const [loading, setLoading] = React.useState(false);
  const [values, setValues] = React.useState<BlogFormValues>(
    initial || {
      title: "", slug: "", excerpt: "", content: "", category: "", tags: [],
      featuredImage: null, isPublished: false, publishedAt: "", authorName: "",
      metaTitle: "", metaDescription: "",
    }
  );
  const [newTag, setNewTag] = React.useState("");

  const set = <K extends keyof BlogFormValues>(k: K, v: BlogFormValues[K]) =>
    setValues((prev) => ({ ...prev, [k]: v }));

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!values.title.trim()) return toast.error("Title is required");
    if (!values.excerpt.trim()) return toast.error("Excerpt is required");
    if (!values.content.trim()) return toast.error("Content is required");
    setLoading(true);
    try {
      const url = isNew ? "/api/admin/blog" : `/api/admin/blog/${values.id}`;
      const res = await fetch(url, {
        method: isNew ? "POST" : "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(values),
      });
      if (!res.ok) {
        const d = await res.json();
        throw new Error(d.error || "Failed");
      }
      toast.success(isNew ? "Blog post created" : "Blog post updated");
      router.push("/admin/blog");
      router.refresh();
    } catch (err: any) {
      toast.error(err.message || "Something went wrong");
    } finally {
      setLoading(false);
    }
  };

  const onDelete = async () => {
    if (!confirm("Delete this blog post? This cannot be undone.")) return;
    setLoading(true);
    try {
      await fetch(`/api/admin/blog/${values.id}`, { method: "DELETE" });
      toast.success("Blog post deleted");
      router.push("/admin/blog");
      router.refresh();
    } catch {
      toast.error("Delete failed");
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={onSubmit} className="space-y-6">
      <div className="grid lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 space-y-5">
          <Card className="p-6 rounded-2xl space-y-5">
            <h2 className="font-bold text-lg">Post Details</h2>
            <div className="space-y-1.5">
              <Label>Title *</Label>
              <Input value={values.title} onChange={(e) => {
                set("title", e.target.value);
                if (isNew) set("slug", e.target.value.toLowerCase().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").slice(0, 80));
              }} required />
            </div>
            <div className="space-y-1.5">
              <Label>Slug</Label>
              <Input value={values.slug} onChange={(e) => set("slug", e.target.value)} placeholder="auto-generated-from-title" />
            </div>
            <div className="space-y-1.5">
              <Label>Excerpt *</Label>
              <Textarea rows={2} value={values.excerpt} onChange={(e) => set("excerpt", e.target.value)} placeholder="A short summary shown in post listings." />
            </div>
            <div className="space-y-1.5">
              <Label>Content *</Label>
              <Textarea rows={12} value={values.content} onChange={(e) => set("content", e.target.value)} />
            </div>
            <div className="grid sm:grid-cols-2 gap-4">
              <div className="space-y-1.5">
                <Label>Category</Label>
                <Input value={values.category} onChange={(e) => set("category", e.target.value)} placeholder="e.g. HVAC Tips" />
              </div>
              <div className="space-y-1.5">
                <Label>Author Name</Label>
                <Input value={values.authorName} onChange={(e) => set("authorName", e.target.value)} placeholder="Author" />
              </div>
            </div>
          </Card>

          <Card className="p-6 rounded-2xl space-y-3">
            <div className="flex items-center justify-between">
              <h2 className="font-bold text-lg">Tags</h2>
            </div>
            <div className="flex gap-2">
              <Input value={newTag} onChange={(e) => setNewTag(e.target.value)} placeholder="Add a tag..." onKeyDown={(e) => {
                if (e.key === "Enter") { e.preventDefault(); if (newTag.trim()) { set("tags", [...values.tags, newTag.trim()]); setNewTag(""); } }
              }} />
              <Button type="button" onClick={() => { if (newTag.trim()) { set("tags", [...values.tags, newTag.trim()]); setNewTag(""); } }}>
                <Plus className="size-4" />
              </Button>
            </div>
            <div className="space-y-2">
              {values.tags.map((t, i) => (
                <div key={i} className="flex items-center justify-between gap-2 px-3 py-2 rounded-lg bg-muted/50">
                  <span className="text-sm">{t}</span>
                  <button type="button" onClick={() => set("tags", values.tags.filter((_, idx) => idx !== i))} className="text-muted-foreground hover:text-destructive">
                    <X className="size-4" />
                  </button>
                </div>
              ))}
            </div>
          </Card>

          <Card className="p-6 rounded-2xl space-y-4">
            <h2 className="font-bold text-lg">SEO Settings</h2>
            <div className="space-y-1.5">
              <Label>Meta Title</Label>
              <Input value={values.metaTitle} onChange={(e) => set("metaTitle", e.target.value)} placeholder="Defaults to post title" />
            </div>
            <div className="space-y-1.5">
              <Label>Meta Description</Label>
              <Textarea rows={2} value={values.metaDescription} onChange={(e) => set("metaDescription", e.target.value)} />
            </div>
          </Card>
        </div>

        {/* Sidebar */}
        <div className="space-y-5">
          <Card className="p-6 rounded-2xl space-y-4">
            <h2 className="font-bold">Publish</h2>
            <div className="flex items-center justify-between">
              <Label htmlFor="published">Published</Label>
              <Switch id="published" checked={values.isPublished} onCheckedChange={(v) => set("isPublished", v)} />
            </div>
            <div className="space-y-1.5">
              <Label>Published At</Label>
              <Input
                type="date"
                value={values.publishedAt ? values.publishedAt.slice(0, 10) : ""}
                onChange={(e) => set("publishedAt", e.target.value ? new Date(e.target.value).toISOString() : "")}
              />
              <p className="text-xs text-muted-foreground">If empty and published, current date is used.</p>
            </div>
          </Card>

          <Card className="p-6 rounded-2xl space-y-3">
            <h2 className="font-bold">Featured Image</h2>
            <MediaPickerButton value={values.featuredImage} onChange={(v) => set("featuredImage", v)} accept="image" label="Upload Image" />
          </Card>

          <div className="flex flex-col gap-2">
            <Button type="submit" disabled={loading} className="brand-gradient text-white">
              {loading ? <Loader2 className="size-4 mr-2 animate-spin" /> : <Save className="size-4 mr-2" />}
              {isNew ? "Create Post" : "Save Changes"}
            </Button>
            <Button type="button" variant="outline" onClick={() => router.back()}>Cancel</Button>
            {!isNew && (
              <Button type="button" variant="ghost" className="text-destructive" onClick={onDelete} disabled={loading}>
                <Trash2 className="size-4 mr-2" /> Delete Post
              </Button>
            )}
          </div>
        </div>
      </div>
    </form>
  );
}
