"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Loader2, Save, Eye } from "lucide-react";
import { RichTextEditor } from "@/components/admin/RichTextEditor";
import { ImageUpload } from "@/components/admin/ImageUpload";
import { TagsInput } from "@/components/admin/TagsInput";
import { slugify } from "@/lib/types";

const CATEGORIES = [
  { value: "founder-notes", label: "یادداشت‌های بنیان‌گذار" },
  { value: "marketing-branding", label: "بازاریابی و برندینگ" },
  { value: "product-thinking", label: "تفکر محصول" },
  { value: "tech-builds", label: "ساخت‌های فنی" },
  { value: "business-experiments", label: "آزمایش‌های کسب‌وکار" },
  { value: "systems-productivity", label: "سیستم‌ها و بهره‌وری" },
];

interface PostFormData {
  id?: string;
  title: string;
  slug: string;
  locale: string;
  category: string;
  excerpt: string;
  body: string;
  coverImage: string;
  featured: boolean;
  publishedAt: string;
  seoTitle: string;
  seoDesc: string;
  tagIds: string[];
}

interface Props {
  initialData?: Partial<PostFormData>;
}

export function PostForm({ initialData }: Props) {
  const router = useRouter();
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const [form, setForm] = useState<PostFormData>({
    title: "",
    slug: "",
    locale: "fa",
    category: "founder-notes",
    excerpt: "",
    body: "",
    coverImage: "",
    featured: false,
    publishedAt: new Date().toISOString().split("T")[0],
    seoTitle: "",
    seoDesc: "",
    tagIds: [],
    ...initialData,
  });

  function set(key: keyof PostFormData, value: unknown) {
    setForm((prev) => ({ ...prev, [key]: value }));
  }

  function handleTitleChange(title: string) {
    set("title", title);
    if (!initialData?.id) {
      set("slug", slugify(title));
    }
  }

  async function handleSave(e: React.FormEvent) {
    e.preventDefault();
    if (!form.title || !form.slug || !form.category) {
      setError("عنوان، اسلاگ و دسته‌بندی الزامی است");
      return;
    }
    setError(null);
    setSaving(true);
    try {
      const method = initialData?.id ? "PUT" : "POST";
      const url = initialData?.id ? `/api/admin/posts/${initialData.id}` : "/api/admin/posts";
      const { tagIds, ...rest } = form;
      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...rest,
          publishedAt: new Date(form.publishedAt).toISOString(),
          tagIds,
        }),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error ?? "Save failed");
      }
      setSuccess(true);
      setTimeout(() => {
        router.push("/admin/posts");
      }, 800);
    } catch (e) {
      setError(e instanceof Error ? e.message : "خطا در ذخیره");
    } finally {
      setSaving(false);
    }
  }

  return (
    <form onSubmit={handleSave} className="space-y-8">
      {error && (
        <div className="rounded-lg border border-danger/30 bg-danger/10 px-4 py-3 text-sm text-danger">{error}</div>
      )}
      {success && (
        <div className="rounded-lg border border-success/30 bg-success/10 px-4 py-3 text-sm text-success">ذخیره شد ✓</div>
      )}

      {/* Basic info */}
      <div className="rounded-xl border border-border bg-surface p-6 space-y-4">
        <h2 className="font-semibold text-text-primary border-b border-border pb-3">اطلاعات اصلی</h2>

        <div className="grid gap-4 sm:grid-cols-2">
          <div className="sm:col-span-2">
            <label className="block text-sm font-medium text-text-primary mb-1.5">عنوان *</label>
            <input
              type="text"
              value={form.title}
              onChange={(e) => handleTitleChange(e.target.value)}
              required
              className="admin-input w-full"
              placeholder="عنوان نوشته را وارد کنید..."
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1.5">اسلاگ *</label>
            <input
              type="text"
              value={form.slug}
              onChange={(e) => set("slug", e.target.value)}
              required
              dir="ltr"
              className="admin-input w-full font-mono text-sm"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1.5">زبان</label>
            <select value={form.locale} onChange={(e) => set("locale", e.target.value)} className="admin-input w-full">
              <option value="fa">فارسی</option>
              <option value="en">English</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1.5">دسته‌بندی *</label>
            <select value={form.category} onChange={(e) => set("category", e.target.value)} className="admin-input w-full">
              {CATEGORIES.map((c) => (
                <option key={c.value} value={c.value}>{c.label}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1.5">تاریخ انتشار</label>
            <input
              type="date"
              value={form.publishedAt}
              onChange={(e) => set("publishedAt", e.target.value)}
              dir="ltr"
              className="admin-input w-full"
            />
          </div>
          <div className="sm:col-span-2">
            <label className="block text-sm font-medium text-text-primary mb-1.5">چکیده</label>
            <textarea
              value={form.excerpt}
              onChange={(e) => set("excerpt", e.target.value)}
              rows={2}
              className="admin-input w-full resize-none"
              placeholder="خلاصه کوتاه از نوشته..."
            />
          </div>
        </div>

        <div className="flex items-center gap-3">
          <input
            type="checkbox"
            id="featured"
            checked={form.featured}
            onChange={(e) => set("featured", e.target.checked)}
            className="h-4 w-4 rounded border-border accent-accent"
          />
          <label htmlFor="featured" className="text-sm text-text-primary">نوشته ویژه (Featured)</label>
        </div>
      </div>

      {/* Cover image */}
      <div className="rounded-xl border border-border bg-surface p-6 space-y-3">
        <h2 className="font-semibold text-text-primary border-b border-border pb-3">تصویر کاور</h2>
        <ImageUpload value={form.coverImage} onChange={(url) => set("coverImage", url)} />
      </div>

      {/* Tags */}
      <div className="rounded-xl border border-border bg-surface p-6 space-y-3">
        <h2 className="font-semibold text-text-primary border-b border-border pb-3">تگ‌ها</h2>
        <TagsInput value={form.tagIds} onChange={(ids) => set("tagIds", ids)} />
      </div>

      {/* Body */}
      <div className="rounded-xl border border-border bg-surface p-6 space-y-3">
        <h2 className="font-semibold text-text-primary border-b border-border pb-3">محتوا</h2>
        <RichTextEditor
          value={form.body}
          onChange={(html) => set("body", html)}
          placeholder="محتوای نوشته را اینجا بنویسید..."
        />
      </div>

      {/* SEO */}
      <div className="rounded-xl border border-border bg-surface p-6 space-y-4">
        <h2 className="font-semibold text-text-primary border-b border-border pb-3">SEO (اختیاری)</h2>
        <div>
          <label className="block text-sm font-medium text-text-primary mb-1.5">عنوان SEO</label>
          <input
            type="text"
            value={form.seoTitle}
            onChange={(e) => set("seoTitle", e.target.value)}
            className="admin-input w-full"
            placeholder="پیش‌فرض: عنوان نوشته"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-text-primary mb-1.5">توضیحات SEO</label>
          <textarea
            value={form.seoDesc}
            onChange={(e) => set("seoDesc", e.target.value)}
            rows={2}
            className="admin-input w-full resize-none"
            placeholder="پیش‌فرض: چکیده نوشته"
          />
        </div>
      </div>

      {/* Actions */}
      <div className="flex items-center gap-3 justify-end sticky bottom-6">
        <a
          href={`/${form.locale}/writing/${form.slug}`}
          target="_blank"
          className="flex items-center gap-2 rounded-lg border border-border px-4 py-2 text-sm text-text-secondary hover:text-text-primary transition-colors"
        >
          <Eye size={14} />
          پیش‌نمایش
        </a>
        <button
          type="submit"
          disabled={saving}
          className="flex items-center gap-2 rounded-lg bg-accent px-5 py-2 text-sm font-semibold text-background hover:bg-accent-hover disabled:opacity-60 transition-colors"
        >
          {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
          {initialData?.id ? "ذخیره تغییرات" : "انتشار نوشته"}
        </button>
      </div>
    </form>
  );
}
