import { useEffect, useState } from "react";
import { Tag, Plus, Pencil, Trash2, X } 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;
  slug: string;
  description?: string | null;
  image_url?: string | null;
  sort_order?: number | null;
  is_active?: boolean | null;
}

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

export default function CmsShopCategories() {
  const [items, setItems] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<Category | null>(null);
  const [form, setForm] = useState<Partial<Category>>({});
  const [saving, setSaving] = useState(false);

  const load = async () => {
    setLoading(true);
    try {
      const res = await client.entities.product_categories.queryAll({
        query: {},
        sort: "sort_order",
        limit: 200,
      });
      setItems((res?.data?.items || []) as Category[]);
    } finally {
      setLoading(false);
    }
  };

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

  const openNew = () => {
    setEditing({ id: 0, name: "", slug: "", is_active: true, sort_order: 0 });
    setForm({
      name: "",
      slug: "",
      description: "",
      image_url: "",
      sort_order: 0,
      is_active: true,
    });
  };

  const openEdit = (c: Category) => {
    setEditing(c);
    setForm({ ...c });
  };

  const save = async () => {
    if (!form.name || !form.slug) {
      toast.error("Name and slug are required.");
      return;
    }
    setSaving(true);
    try {
      if (editing && editing.id) {
        await client.entities.product_categories.update({
          id: String(editing.id),
          data: form,
        });
        toast.success("Category updated.");
      } else {
        await client.entities.product_categories.create({ data: form });
        toast.success("Category 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 (c: Category) => {
    if (!confirm(`Delete category "${c.name}"?`)) return;
    try {
      await client.entities.product_categories.delete({ id: String(c.id) });
      toast.success("Deleted.");
      await load();
    } catch (e) {
      const msg = e instanceof Error ? e.message : "Delete failed.";
      toast.error(msg);
    }
  };

  return (
    <CmsLayout>
      <div className="flex items-center justify-between gap-4 mb-6">
        <PageHeader
          icon={<Tag className="w-6 h-6" />}
          title="Shop Categories"
          description="Group your products under shoppable categories."
        />
        <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 category
        </button>
      </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">Name</th>
                <th className="text-left p-3">Slug</th>
                <th className="text-left p-3">Sort</th>
                <th className="text-left p-3">Active</th>
                <th className="text-right p-3">Actions</th>
              </tr>
            </thead>
            <tbody>
              {items.map((c) => (
                <tr key={c.id} className="border-t border-slate-100">
                  <td className="p-3 font-semibold text-slate-900">{c.name}</td>
                  <td className="p-3 text-slate-600">{c.slug}</td>
                  <td className="p-3 text-slate-600">{c.sort_order ?? 0}</td>
                  <td className="p-3">
                    <span
                      className={`text-[11px] font-bold px-2 py-0.5 rounded-full ${
                        c.is_active
                          ? "bg-emerald-100 text-emerald-700"
                          : "bg-slate-100 text-slate-600"
                      }`}
                    >
                      {c.is_active ? "Active" : "Hidden"}
                    </span>
                  </td>
                  <td className="p-3">
                    <div className="flex justify-end gap-2">
                      <button
                        onClick={() => openEdit(c)}
                        className="p-2 rounded-lg hover:bg-slate-100"
                        aria-label="Edit"
                      >
                        <Pencil className="w-4 h-4 text-slate-600" />
                      </button>
                      <button
                        onClick={() => remove(c)}
                        className="p-2 rounded-lg hover:bg-rose-50"
                        aria-label="Delete"
                      >
                        <Trash2 className="w-4 h-4 text-rose-600" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
              {items.length === 0 && (
                <tr>
                  <td colSpan={5} className="p-6 text-center text-slate-500">
                    No categories yet.
                  </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-lg 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 category" : "New category"}
              </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 space-y-3">
              <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 })}
                  placeholder="e.g. apparel"
                  className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"
                />
              </Field>
              <Field label="Description">
                <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="Image URL">
                <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>
              <div className="grid grid-cols-2 gap-3">
                <Field label="Sort order">
                  <input
                    type="number"
                    value={form.sort_order ?? 0}
                    onChange={(e) =>
                      setForm({ ...form, sort_order: Number(e.target.value) })
                    }
                    className="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm"
                  />
                </Field>
                <Field label="Visible">
                  <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>
              </div>
            </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>
  );
}