import { useEffect, useMemo, useState } from "react";
import { Package, Plus, Pencil, Trash2, X, Search } from "lucide-react";
import { createClient } from "@metagptx/web-sdk";
import CmsLayout from "./CmsLayout";
import { PageHeader } from "./ui";
import LoadingSpinner from "@/components/LoadingSpinner";
import { toast } from "sonner";

const client = createClient();

interface Category {
  id: number;
  name: string;
}

interface Product {
  id: number;
  name: string;
  slug: string;
  description?: string | null;
  long_description?: string | null;
  product_type: string;
  price: number;
  compare_at_price?: number | null;
  currency?: string | null;
  category_id?: number | null;
  tags?: string | null;
  image_url?: string | null;
  gallery?: string | null;
  stock?: number | null;
  weight_grams?: number | null;
  sku?: string | null;
  download_url?: string | null;
  variants?: string | null;
  is_active?: boolean | null;
  featured?: boolean | null;
}

function Field({
  label,
  children,
  span = 1,
}: {
  label: string;
  children: React.ReactNode;
  span?: 1 | 2;
}) {
  return (
    <div className={span === 2 ? "md:col-span-2" : ""}>
      <div className="text-xs uppercase tracking-wider font-semibold text-slate-600 mb-1">
        {label}
      </div>
      {children}
    </div>
  );
}

const emptyForm: Partial<Product> = {
  name: "",
  slug: "",
  description: "",
  long_description: "",
  product_type: "physical",
  price: 0,
  compare_at_price: 0,
  currency: "SAR",
  category_id: undefined,
  tags: "",
  image_url: "",
  gallery: "[]",
  stock: 0,
  weight_grams: 0,
  sku: "",
  download_url: "",
  variants: "[]",
  is_active: true,
  featured: false,
};

export default function CmsShopProducts() {
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<Product | null>(null);
  const [form, setForm] = useState<Partial<Product>>(emptyForm);
  const [saving, setSaving] = useState(false);
  const [search, setSearch] = useState("");

  const load = async () => {
    setLoading(true);
    try {
      const [pRes, cRes] = await Promise.all([
        client.entities.products.queryAll({ query: {}, sort: "-id", limit: 500 }),
        client.entities.product_categories.queryAll({
          query: {},
          sort: "sort_order",
          limit: 200,
        }),
      ]);
      setProducts((pRes?.data?.items || []) as Product[]);
      setCategories((cRes?.data?.items || []) as Category[]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    load();
  }, []);

  const filtered = useMemo(() => {
    if (!search.trim()) return products;
    const q = search.trim().toLowerCase();
    return products.filter(
      (p) =>
        p.name.toLowerCase().includes(q) ||
        (p.slug || "").toLowerCase().includes(q) ||
        (p.sku || "").toLowerCase().includes(q),
    );
  }, [products, search]);

  const openNew = () => {
    setEditing({ id: 0 } as Product);
    setForm({ ...emptyForm });
  };

  const openEdit = (p: Product) => {
    setEditing(p);
    setForm({ ...p });
  };

  const save = async () => {
    if (!form.name || !form.slug || !form.product_type) {
      toast.error("Name, slug and type are required.");
      return;
    }
    if (form.price == null || isNaN(Number(form.price))) {
      toast.error("Price is required.");
      return;
    }
    setSaving(true);
    try {
      const payload: Partial<Product> = {
        ...form,
        price: Number(form.price),
        compare_at_price: form.compare_at_price ? Number(form.compare_at_price) : 0,
        stock: form.stock == null ? 0 : Number(form.stock),
        weight_grams: form.weight_grams == null ? 0 : Number(form.weight_grams),
        category_id:
          form.category_id == null || form.category_id === ("" as unknown)
            ? undefined
            : Number(form.category_id),
      };
      if (editing && editing.id) {
        await client.entities.products.update({
          id: String(editing.id),
          data: payload,
        });
        toast.success("Product updated.");
      } else {
        await client.entities.products.create({ data: payload });
        toast.success("Product created.");
      }
      setEditing(null);
      await load();
    } catch (e) {
      const msg = e instanceof Error ? e.message : "Save failed.";
      toast.error(msg);
    } finally {
      setSaving(false);
    }
  };

  const remove = async (p: Product) => {
    if (!confirm(`Delete product "${p.name}"?`)) return;
    try {
      await client.entities.products.delete({ id: String(p.id) });
      toast.success("Deleted.");
      await load();
    } catch (e) {
      const msg = e instanceof Error ? e.message : "Delete failed.";
      toast.error(msg);
    }
  };

  const categoryName = (id?: number | null) =>
    categories.find((c) => c.id === id)?.name || "—";

  return (
    <CmsLayout>
      <div className="flex items-center justify-between gap-4 mb-6">
        <PageHeader
          icon={<Package className="w-6 h-6" />}
          title="Shop Products"
          description="Create and manage items for sale in your online shop."
        />
        <button
          onClick={openNew}
          className="px-4 py-2 rounded-xl bg-[#0b6e3e] text-white font-semibold inline-flex items-center gap-2 hover:bg-[#0a8048] shrink-0"
        >
          <Plus className="w-4 h-4" /> New product
        </button>
      </div>

      <div className="mb-4 relative max-w-md">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
        <input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search products…"
          className="w-full pl-9 pr-3 py-2 text-sm border border-slate-200 rounded-lg bg-white"
        />
      </div>

      {loading ? (
        <div className="py-16 flex justify-center">
          <LoadingSpinner />
        </div>
      ) : (
        <div className="bg-white border border-slate-200 rounded-2xl overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-slate-50 text-slate-600 text-xs uppercase tracking-wider">
              <tr>
                <th className="text-left p-3">Product</th>
                <th className="text-left p-3">Type</th>
                <th className="text-left p-3">Category</th>
                <th className="text-left p-3">Price</th>
                <th className="text-left p-3">Stock</th>
                <th className="text-left p-3">Status</th>
                <th className="text-right p-3">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((p) => (
                <tr key={p.id} className="border-t border-slate-100 align-top">
                  <td className="p-3">
                    <div className="flex items-center gap-3">
                      {p.image_url ? (
                        <img
                          src={p.image_url}
                          alt={p.name}
                          className="w-12 h-12 rounded-lg object-cover border border-slate-200"
                        />
                      ) : (
                        <div className="w-12 h-12 rounded-lg bg-slate-100" />
                      )}
                      <div>
                        <div className="font-semibold text-slate-900">{p.name}</div>
                        <div className="text-xs text-slate-500">{p.slug}</div>
                      </div>
                    </div>
                  </td>
                  <td className="p-3 text-slate-600 capitalize">{p.product_type}</td>
                  <td className="p-3 text-slate-600">{categoryName(p.category_id)}</td>
                  <td className="p-3 font-semibold text-[#0b6e3e]">
                    SAR {Number(p.price || 0).toFixed(2)}
                  </td>
                  <td className="p-3 text-slate-600">
                    {p.stock === -1 ? "∞" : p.stock ?? 0}
                  </td>
                  <td className="p-3">
                    <div className="flex flex-wrap gap-1">
                      <span
                        className={`text-[10px] font-bold px-2 py-0.5 rounded-full ${
                          p.is_active
                            ? "bg-emerald-100 text-emerald-700"
                            : "bg-slate-100 text-slate-600"
                        }`}
                      >
                        {p.is_active ? "Active" : "Hidden"}
                      </span>
                      {p.featured && (
                        <span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-amber-100 text-amber-700">
                          Featured
                        </span>
                      )}
                    </div>
                  </td>
                  <td className="p-3">
                    <div className="flex justify-end gap-2">
                      <button
                        onClick={() => openEdit(p)}
                        className="p-2 rounded-lg hover:bg-slate-100"
                      >
                        <Pencil className="w-4 h-4 text-slate-600" />
                      </button>
                      <button
                        onClick={() => remove(p)}
                        className="p-2 rounded-lg hover:bg-rose-50"
                      >
                        <Trash2 className="w-4 h-4 text-rose-600" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
              {filtered.length === 0 && (
                <tr>
                  <td colSpan={7} className="p-6 text-center text-slate-500">
                    No products found.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      )}

      {editing && (
        <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-5 border-b border-slate-200">
              <h2 className="font-bold text-lg">
                {editing.id ? "Edit product" : "New product"}
              </h2>
              <button
                onClick={() => setEditing(null)}
                className="p-1.5 rounded-lg hover:bg-slate-100"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-5 grid md:grid-cols-2 gap-4">
              <Field label="Name">
                <input
                  value={form.name || ""}
                  onChange={(e) => setForm({ ...form, name: e.target.value })}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"
                />
              </Field>
              <Field label="Slug">
                <input
                  value={form.slug || ""}
                  onChange={(e) => setForm({ ...form, slug: e.target.value })}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"
                />
              </Field>
              <Field label="Type">
                <select
                  value={form.product_type || "physical"}
                  onChange={(e) => setForm({ ...form, product_type: e.target.value })}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm bg-white"
                >
                  <option value="physical">Physical</option>
                  <option value="digital">Digital</option>
                  <option value="hosting">Hosting add-on</option>
                </select>
              </Field>
              <Field label="Category">
                <select
                  value={form.category_id ?? ""}
                  onChange={(e) =>
                    setForm({
                      ...form,
                      category_id: e.target.value
                        ? Number(e.target.value)
                        : undefined,
                    })
                  }
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm bg-white"
                >
                  <option value="">— None —</option>
                  {categories.map((c) => (
                    <option key={c.id} value={c.id}>
                      {c.name}
                    </option>
                  ))}
                </select>
              </Field>
              <Field label="Price (SAR)">
                <input
                  type="number"
                  step="0.01"
                  value={form.price ?? 0}
                  onChange={(e) => setForm({ ...form, price: Number(e.target.value) })}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"
                />
              </Field>
              <Field label="Compare-at price">
                <input
                  type="number"
                  step="0.01"
                  value={form.compare_at_price ?? 0}
                  onChange={(e) =>
                    setForm({ ...form, compare_at_price: Number(e.target.value) })
                  }
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"
                />
              </Field>
              <Field label="Stock (-1 for unlimited)">
                <input
                  type="number"
                  value={form.stock ?? 0}
                  onChange={(e) => setForm({ ...form, stock: Number(e.target.value) })}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"
                />
              </Field>
              <Field label="SKU">
                <input
                  value={form.sku || ""}
                  onChange={(e) => setForm({ ...form, sku: e.target.value })}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"
                />
              </Field>
              <Field label="Weight (g, shipping)">
                <input
                  type="number"
                  value={form.weight_grams ?? 0}
                  onChange={(e) =>
                    setForm({ ...form, weight_grams: Number(e.target.value) })
                  }
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"
                />
              </Field>
              <Field label="Tags (comma-separated)">
                <input
                  value={form.tags || ""}
                  onChange={(e) => setForm({ ...form, tags: e.target.value })}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"
                />
              </Field>
              <Field label="Short description" span={2}>
                <textarea
                  value={form.description || ""}
                  onChange={(e) => setForm({ ...form, description: e.target.value })}
                  rows={2}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"
                />
              </Field>
              <Field label="Long description" span={2}>
                <textarea
                  value={form.long_description || ""}
                  onChange={(e) =>
                    setForm({ ...form, long_description: e.target.value })
                  }
                  rows={4}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"
                />
              </Field>
              <Field label="Primary image URL" span={2}>
                <input
                  value={form.image_url || ""}
                  onChange={(e) => setForm({ ...form, image_url: e.target.value })}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"
                />
              </Field>
              <Field label="Gallery (JSON array of URLs)" span={2}>
                <textarea
                  value={form.gallery || "[]"}
                  onChange={(e) => setForm({ ...form, gallery: e.target.value })}
                  rows={2}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm font-mono"
                />
              </Field>
              <Field label='Variants JSON e.g. [{"name":"Size","options":["S","M","L"]}]' span={2}>
                <textarea
                  value={form.variants || "[]"}
                  onChange={(e) => setForm({ ...form, variants: e.target.value })}
                  rows={2}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm font-mono"
                />
              </Field>
              <Field label="Digital download URL" span={2}>
                <input
                  value={form.download_url || ""}
                  onChange={(e) => setForm({ ...form, download_url: e.target.value })}
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"
                />
              </Field>
              <Field label="Visibility">
                <select
                  value={form.is_active ? "1" : "0"}
                  onChange={(e) =>
                    setForm({ ...form, is_active: e.target.value === "1" })
                  }
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm bg-white"
                >
                  <option value="1">Active</option>
                  <option value="0">Hidden</option>
                </select>
              </Field>
              <Field label="Featured">
                <select
                  value={form.featured ? "1" : "0"}
                  onChange={(e) =>
                    setForm({ ...form, featured: e.target.value === "1" })
                  }
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm bg-white"
                >
                  <option value="0">No</option>
                  <option value="1">Yes</option>
                </select>
              </Field>
            </div>
            <div className="p-5 border-t border-slate-200 flex justify-end gap-3">
              <button
                onClick={() => setEditing(null)}
                className="px-4 py-2 rounded-lg border border-slate-200 text-slate-700 font-semibold"
              >
                Cancel
              </button>
              <button
                onClick={save}
                disabled={saving}
                className="px-4 py-2 rounded-lg bg-[#0b6e3e] text-white font-semibold hover:bg-[#0a8048] disabled:opacity-60"
              >
                {saving ? "Saving…" : "Save"}
              </button>
            </div>
          </div>
        </div>
      )}
    </CmsLayout>
  );
}