"use client";

import React, { useEffect, useState } from "react";
import {
  FolderTree,
  Edit3,
  Trash2,
  Plus,
  ChevronRight,
  ChevronDown,
} from "lucide-react";
import { createCategory, deleteCategory, getTree, updateCategory } from "@/lib/categories.api";
import { slugify } from "@/lib/slug";

interface Category {
  id: string;
  name: string;
  slug: string;
  parentId?: string | null;
  children?: Category[];
}

export default function ManageCategoryClient() {
  const [tree, setTree] = useState<Category[]>([]);
  const [loading, setLoading] = useState(false);

  const [modalOpen, setModalOpen] = useState(false);

  const [form, setForm] = useState({
    id: null as string | null,
    name: "",
    slug: "",
    parentId: null as string | null,
  });

  async function load() {
    setLoading(true);
    try {
      const t = await getTree();
      setTree(t);
    } finally {
      setLoading(false);
    }
  }

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

  async function save() {
    const payload = {
      name: form.name,
      slug: form.slug || slugify(form.name),
      parentId: form.parentId,
    };

    if (form.id) {
      await updateCategory(form.id, payload);
    } else {
      await createCategory(payload);
    }

    closeModal();
    load();
  }

  async function remove(id: string) {
    if (!confirm("Delete this category?")) return;
    await deleteCategory(id);
    load();
  }

  function openCreate(parentId?: string) {
    setForm({
      id: null,
      name: "",
      slug: "",
      parentId: parentId || null,
    });
    setModalOpen(true);
  }

  function openEdit(cat: Category) {
    setForm({
      id: cat.id,
      name: cat.name,
      slug: cat.slug,
      parentId: cat.parentId || null,
    });
    setModalOpen(true);
  }

  function closeModal() {
    setModalOpen(false);
    setForm({ id: null, name: "", slug: "", parentId: null });
  }

  function TreeNode({
    node,
    level = 0,
  }: {
    node: Category;
    level?: number;
  }) {
    const [open, setOpen] = useState(true);

    return (
      <div style={{ marginLeft: level * 14 }} className="border-l pl-3">
        <div className="flex items-center justify-between py-2 group">
          <div className="flex items-center gap-2">
            <button onClick={() => setOpen(!open)}>
              {open ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
            </button>

            <FolderTree size={14} className="text-blue-500" />

            <span
              onClick={() => openEdit(node)}
              className="text-sm font-medium cursor-pointer hover:text-blue-600"
            >
              {node.name}
            </span>
          </div>

          <div className="flex gap-2 opacity-0 group-hover:opacity-100 transition">
            <button onClick={() => openCreate(node.id)} className="text-green-600">
              <Plus size={14} />
            </button>

            <button onClick={() => openEdit(node)}>
              <Edit3 size={14} />
            </button>

            <button onClick={() => remove(node.id)}>
              <Trash2 size={14} className="text-red-500" />
            </button>
          </div>
        </div>

        {open &&
          node.children?.map((child) => <TreeNode key={child.id} node={child} level={level + 1} />)}
      </div>
    );
  }

  return (
    <>
      <main className="flex-1 p-6 overflow-y-auto min-h-0">
        <div className="flex justify-between mb-6">
          <h1 className="text-xl font-semibold">Categories</h1>

          <button onClick={() => openCreate()} className="bg-blue-600 text-white px-4 py-2 rounded">
            + New Category
          </button>
        </div>

        <div className="bg-white border rounded-xl p-4">
          {loading ? (
            <p>Loading...</p>
          ) : (
            tree.map((node) => <TreeNode key={node.id} node={node} />)
          )}
        </div>
      </main>

      {modalOpen && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
          <div className="bg-white w-[420px] p-5 rounded-xl">
            <h2 className="font-semibold mb-4">{form.id ? "Edit Category" : "Create Category"}</h2>

            <input
              className="w-full border p-2 rounded mb-2"
              placeholder="Name"
              value={form.name}
              onChange={(e) =>
                setForm({
                  ...form,
                  name: e.target.value,
                  slug: slugify(e.target.value),
                })
              }
            />

            <input
              className="w-full border p-2 rounded mb-3"
              placeholder="Slug"
              value={form.slug}
              onChange={(e) => setForm({ ...form, slug: e.target.value })}
            />

            <div className="flex justify-end gap-2">
              <button onClick={closeModal}>Cancel</button>

              <button onClick={save} className="bg-blue-600 text-white px-3 py-1 rounded">
                Save
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
