import React, { useEffect, useState } from "react";
import { Search, Plus, Edit, Trash2 } from "lucide-react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import { toast } from "sonner";

/* SHADCN DELETE DIALOG */
import {
  AlertDialog,
  AlertDialogTrigger,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogCancel,
  AlertDialogAction,
} from "@/components/ui/alert-dialog";

export default function ProductCategories() {
  const navigate = useNavigate();
  const API_URL = import.meta.env.VITE_API_URL;

  const [categories, setCategories] = useState([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [deleteId, setDeleteId] = useState(null);

  /* ------------------------ LOAD CATEGORIES ------------------------ */

  useEffect(() => {
      axios
      .get(`${API_URL}/api/category/allcategory`)
      .then((res) => {
            if(!res.data.categories || !Array.isArray(res.data.categories)){
              console.error("Invalid category response: ",res.data)
              return
            }
            const data = res.data.categories.map((cat) => ({
                id : cat._id,
                name : cat.name,
                image : `${API_URL}${cat.image}`,
                products : cat.productCount || 0,
                fullData : cat,  
            }))
            setCategories(data)
      })
      .catch((err) => console.error("Error fetching categories",err));
  },[])

  /* ------------------------ DELETE CATEGORY ------------------------ */
  const handleDelete = async () => {
    try {
      await axios.delete(`${API_URL}/api/category/deleteCategory/${deleteId}`);
      setCategories((prev) => prev.filter((c) => c.id !== deleteId));
      toast.success("Category deleted successfully!");
      setDeleteId(null);
    } catch (err) {
      console.error("Delete error:", err);
      toast.error("Something went wrong");
    }
  };

  /* ------------------------ SEARCH FILTER ------------------------ */
  const filteredCategories = categories.filter((cat) =>
    cat.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="min-h-screen bg-gray-100 p-6">
      <div className="max-w-7xl mx-auto">

        {/* HEADER */}
        <div className="flex items-center justify-between mb-6">
          <h1 className="text-3xl font-semibold">
            Categories{" "}
            <span className="text-orange-500">{categories.length}</span>
          </h1>

          <button
            onClick={() => navigate("/admin/category/new")}
            className="px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 flex items-center gap-2"
          >
            <Plus className="w-4 h-4" />
            <span className="font-medium">New Category</span>
          </button>
        </div>

        {/* SEARCH BAR */}
        <div className="bg-white p-4 border-none rounded-xl mb-6">
          <div className="flex items-center gap-3">
            <Search className="w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search categories..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="flex-1 outline-none"
            />
          </div>
        </div>

        {/* TABLE */}
        <div className="bg-white rounded-xl shadow border-none overflow-x-auto">
          <table className="w-full text-sm text-gray-600">
            <thead className="bg-gray-100 text-left text-gray-700">
              <tr>
                <th className="p-3">Image</th>
                <th className="p-3">Name</th>
                <th className="p-3 text-center">Products</th>
                <th className="p-3 text-center">Actions</th>
              </tr>
            </thead>

            <tbody>
              {filteredCategories.map((cat) => (
                <tr key={cat.id} className="border-t hover:bg-gray-50">

                  {/* IMAGE */}
                  <td className="p-3">
                    <img
                      src={cat.image}
                      alt={cat.name}
                      className="w-12 h-12 object-cover rounded border"
                    />
                  </td>

                  {/* NAME */}
                  <td className="p-3 font-medium text-gray-700">
                    {cat.name}
                  </td>

                  {/* PRODUCTS */}
                  <td className="p-3 text-center">{cat.products}</td>

                  {/* ACTIONS */}
                  <td className="p-3">
                    <div className="flex justify-center gap-4">

                      {/* ⭐ EDIT BUTTON WITH FULL DATA PASSED IN STATE */}
                      <button
                        onClick={() => {
                          // console.log("CLICKED CATEGORY:", cat);
                          // console.log("NAVIGATING WITH STATE:", cat.fullData);
                          navigate(`/admin/category/edit/${cat.id}`, {
                            state: { category: cat.fullData },
                          });
                        }}
                        className="text-blue-600 hover:text-blue-800"
                      >
                        <Edit size={18} />
                      </button>


                      {/* DELETE */}
                      <AlertDialog>
                        <AlertDialogTrigger asChild>
                          <button
                            onClick={() => setDeleteId(cat.id)}
                            className="text-red-500 hover:text-red-600"
                          >
                            <Trash2 size={18} />
                          </button>
                        </AlertDialogTrigger>

                        <AlertDialogContent className="bg-white">
                          <AlertDialogHeader>
                            <AlertDialogTitle>Delete Category</AlertDialogTitle>
                            <AlertDialogDescription>
                              Are you sure you want to delete{" "}
                              <b>{cat.name}</b>?
                              This action cannot be undone.
                            </AlertDialogDescription>
                          </AlertDialogHeader>

                          <AlertDialogFooter>
                            <AlertDialogCancel>Cancel</AlertDialogCancel>
                            <AlertDialogAction
                              onClick={handleDelete}
                              className="bg-red-600 text-white hover:bg-red-700"
                            >
                              Delete
                            </AlertDialogAction>
                          </AlertDialogFooter>
                        </AlertDialogContent>
                      </AlertDialog>

                    </div>
                  </td>

                </tr>
              ))}
            </tbody>
          </table>

          {filteredCategories.length === 0 && (
            <div className="text-center p-6 text-gray-500">
              No categories found.
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
