"use client";

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

interface ProductFormData {
  id?: string;
  title: string; slug: string; locale: string;
  description: string; price: string; currency: string;
  coverImage: string; purchaseUrl: string;
  productType: string; featured: boolean; sortOrder: number;
  seoTitle: string; seoDesc: string;
}

interface Props { initialData?: Partial<ProductFormData> }

export function ProductForm({ 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<ProductFormData>({
    title: "", slug: "", locale: "fa", description: "",
    price: "", currency: "IRR", coverImage: "", purchaseUrl: "",
    productType: "digital", featured: false, sortOrder: 0,
    seoTitle: "", seoDesc: "", ...initialData,
  });
  function set(key: keyof ProductFormData, value: unknown) {
    setForm((prev) => ({ ...prev, [key]: value }));
  }

  async function handleSave(e: React.FormEvent) {
    e.preventDefault();
    if (!form.title || !form.slug) { setError("عنوان و اسلاگ الزامی است"); return; }
    setError(null); setSaving(true);
    try {
      const method = initialData?.id ? "PUT" : "POST";
      const url = initialData?.id ? `/api/admin/products/${initialData.id}` : "/api/admin/products";
      const res = await fetch(url, {
        method, headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...form,
          price: form.price !== "" ? parseFloat(form.price) : null,
          sortOrder: parseInt(String(form.sortOrder)) || 0,
        }),
      });
      if (!res.ok) throw new Error((await res.json()).error ?? "Save failed");
      setSuccess(true);
      setTimeout(() => router.push("/admin/products"), 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>}

      <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) => { set("title", e.target.value); if (!initialData?.id) set("slug", slugify(e.target.value)); }} required className="admin-input w-full" />
          </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.productType} onChange={(e) => set("productType", e.target.value)} className="admin-input w-full">
              <option value="digital">دیجیتال</option>
              <option value="node-product">NODE Product</option>
            </select>
          </div>
          <div className="grid grid-cols-2 gap-2">
            <div>
              <label className="block text-sm font-medium text-text-primary mb-1.5">قیمت</label>
              <input type="number" min="0" step="0.01" value={form.price} onChange={(e) => set("price", e.target.value)} className="admin-input w-full" placeholder="0 = رایگان" />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-primary mb-1.5">ارز</label>
              <select value={form.currency} onChange={(e) => set("currency", e.target.value)} className="admin-input w-full">
                <option value="IRR">تومان</option>
                <option value="USD">USD</option>
              </select>
            </div>
          </div>
          <div>
            <label className="block text-sm font-medium text-text-primary mb-1.5">لینک خرید</label>
            <input type="url" value={form.purchaseUrl} onChange={(e) => set("purchaseUrl", e.target.value)} dir="ltr" className="admin-input w-full" placeholder="https://..." />
          </div>
          <div className="sm:col-span-2">
            <label className="block text-sm font-medium text-text-primary mb-1.5">توضیحات</label>
            <textarea value={form.description} onChange={(e) => set("description", e.target.value)} rows={3} className="admin-input w-full resize-none" />
          </div>
        </div>
        <div className="flex items-center gap-3">
          <input type="checkbox" id="featured-product" checked={form.featured} onChange={(e) => set("featured", e.target.checked)} className="h-4 w-4 rounded border-border accent-accent" />
          <label htmlFor="featured-product" className="text-sm text-text-primary">محصول ویژه</label>
        </div>
      </div>

      <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>

      <div className="flex items-center gap-3 justify-end">
        <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>
  );
}
