import { useState, useRef, useEffect } from "react";
import axios from "axios";
import {
    Search,
    SlidersHorizontal,
    ChevronDown,
    Plus,
    DownloadCloud,
    UploadCloud,
    Edit,
    Trash2,
    AlertTriangle,
} from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";

import login_side_banner from "../../../../assets/images/login_side_banner.jpg";

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

export default function ProductManagement() {
    const navigate = useNavigate();
    const [products, setProducts] = useState([]);
    const [filtered, setFiltered] = useState([]);
    const [search, setSearch] = useState("");

    const [selectedProducts, setSelectedProducts] = useState([]);

    const [showMoreActions, setShowMoreActions] = useState(false);
    const [openNewProduct, setOpenNewProduct] = useState(false);

    const moreActionsRef = useRef(null);
    const newProductRef = useRef(null);

    const API_URL = import.meta.env.VITE_API_URL;

    /* -------------------- FETCH PRODUCTS -------------------- */
    useEffect(() => {
        axios
            .get(`${API_URL}/api/product/allproducts`)
            .then((res) => {
                if (!res.data || !Array.isArray(res.data.products)) {
                    console.error("Invalid product response:", res.data);
                    toast.error("Invalid server response");
                    return;
                }

                const data = res.data.products.map((p) => {
                    let imageUrl = p.media?.find((m) => m.type === "image")?.url;

                    if (imageUrl) {
                        imageUrl = imageUrl.replace(/^\//, "");
                        imageUrl = `${API_URL}/${imageUrl}`;
                    }

                    return {
                        id: p._id,
                        name: p.name,
                        sku: p.sku || "-",
                        type: "Physical",
                        price: p.price || 0,
                        inventory: p.status === "in_stock" ? "In stock" : "Out of stock",
                        image: imageUrl || login_side_banner,
                    };
                });

                setProducts(data);
                setFiltered(data);
            })
            .catch((err) => console.error("Error fetching products:", err));
    }, [API_URL]);

    /* -------------------- SEARCH FILTER -------------------- */
    useEffect(() => {
        if (!search.trim()) return setFiltered(products);

        const s = search.toLowerCase();

        setFiltered(
            products.filter(
                (p) =>
                    p.name.toLowerCase().includes(s) ||
                    p.sku.toLowerCase().includes(s) ||
                    p.type.toLowerCase().includes(s)
            )
        );
    }, [search, products]);

    /* -------------------- DELETE PRODUCT -------------------- */
    const handleDelete = async (id) => {
        try {
            await axios.delete(`${API_URL}/api/product/removeproduct/${id}`);

            setProducts((prev) => prev.filter((p) => p.id !== id));
            setFiltered((prev) => prev.filter((p) => p.id !== id));

            toast.success("Product removed successfully!");
        } catch (err) {
            console.error(err);
            toast.error("Failed to delete product.");
        }
    };

    /* -------------------- OUTSIDE CLICK HANDLER -------------------- */
    useEffect(() => {
        function handleClickOutside(event) {
            if (
                moreActionsRef.current &&
                !moreActionsRef.current.contains(event.target)
            ) {
                setShowMoreActions(false);
            }
            if (
                newProductRef.current &&
                !newProductRef.current.contains(event.target)
            ) {
                setOpenNewProduct(false);
            }
        }

        document.addEventListener("mousedown", handleClickOutside);
        return () => document.removeEventListener("mousedown", handleClickOutside);
    }, []);

    /* -------------------- CHECKBOX LOGIC -------------------- */
    const toggleProduct = (id) => {
        setSelectedProducts((prev) =>
            prev.includes(id)
                ? prev.filter((pid) => pid !== id)
                : [...prev, id]
        );
    };

    const toggleSelectAll = () => {
        if (selectedProducts.length === filtered.length) {
            setSelectedProducts([]);
        } else {
            setSelectedProducts(filtered.map((p) => p.id));
        }
    };

    const allSelected =
        filtered.length > 0 && selectedProducts.length === filtered.length;

    /* -------------------- ANIMATION -------------------- */
    const dropdownAnimation = {
        initial: { opacity: 0, scale: 0.95, y: -8 },
        animate: { opacity: 1, scale: 1, y: 0 },
        exit: { opacity: 0, scale: 0.95, y: -8 },
        transition: { duration: 0.15, ease: "easeOut" },
    };

    /* -------------------- UI -------------------- */
    return (
        <div className="min-h-screen bg-gray-100 p-4 sm:p-6">
            <div className="max-w-7xl mx-auto">

                {/* HEADER */}
                <div className="flex flex-wrap items-center justify-between mb-6 gap-4">
                    <h1 className="text-2xl sm:text-3xl font-semibold">
                        Products{" "}
                        <span className="text-orange-500">
                            {filtered.length}
                        </span>
                    </h1>

                    <div className="flex gap-2 sm:gap-3 items-center cursor-pointer">

                        {/* More Actions */}
                        <div className="relative" ref={moreActionsRef}>
                            <button
                                onClick={() => {
                                    setShowMoreActions((prev) => !prev);
                                    setOpenNewProduct(false);
                                }}
                                className="hidden sm:flex px-3 md:px-4 py-2 bg-white rounded-lg border border-gray-200 hover:bg-gray-50 items-center gap-2 cursor-pointer"
                            >
                                <span className="font-medium text-sm md:text-base">More Actions</span>
                                <ChevronDown className="w-3 h-3 md:w-4 md:h-4" />
                            </button>

                            <AnimatePresence>
                                {showMoreActions && (
                                    <motion.div
                                        {...dropdownAnimation}
                                        className="absolute top-full right-0 mt-2 w-64 bg-white border border-gray-200 rounded-lg shadow-lg z-10"
                                    >
                                        <button
                                            onClick={() => navigate("/admin/products/import")}
                                            className="w-full flex items-start gap-3 px-4 py-3 hover:bg-orange-200 rounded-t-lg cursor-pointer"
                                        >
                                            <UploadCloud className="w-6 h-6 text-blue-600 mt-1" />
                                            <div className="text-left">
                                                <p className="font-medium text-gray-900 text-sm">Import</p>
                                                <p className="text-gray-500 text-xs">Import multiple products</p>
                                            </div>
                                        </button>

                                        <button className="w-full flex items-start gap-3 px-4 py-3 hover:bg-orange-200 rounded-b-lg cursor-pointer">
                                            <DownloadCloud className="w-6 h-6 text-green-600 mt-1" />
                                            <div className="text-left">
                                                <p className="font-medium text-gray-900 text-sm">Export</p>
                                                <p className="text-gray-500 text-xs">Export to CSV file</p>
                                            </div>
                                        </button>
                                    </motion.div>
                                )}
                            </AnimatePresence>
                        </div>

                        {/* New Product */}
                        <div className="relative cursor-pointer" ref={newProductRef}>
                            <button
                                onClick={() => {
                                    setOpenNewProduct((prev) => !prev);
                                    setShowMoreActions(false);
                                }}
                                className="px-3 md:px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 flex items-center gap-2 cursor-pointer"
                            >
                                <Plus className="w-4 h-4 md:w-5 md:h-5" />
                                <span className="font-medium text-sm md:text-base hidden sm:inline">
                                    New Product
                                </span>
                                <span className="font-medium text-sm sm:hidden">
                                    New
                                </span>
                            </button>

                            <AnimatePresence>
                                {openNewProduct && (
                                    <motion.div
                                        {...dropdownAnimation}
                                        className="absolute top-full right-0 mt-2 w-64 bg-white border border-gray-200 rounded-lg shadow-lg z-10"
                                    >
                                        <button
                                            onClick={() => navigate("/admin/products/newproducts")}
                                            className="w-full text-left px-4 py-3 hover:bg-orange-200 cursor-pointer"
                                        >
                                            <p className="font-medium text-gray-900 text-sm">Physical Products</p>
                                            <p className="text-gray-500 text-xs">e.g., t-shirt, shoes, or skateboard</p>
                                        </button>

                                        <button className="w-full text-left px-4 py-3 hover:bg-orange-200">
                                            <p className="font-medium text-gray-900 text-sm">Digital File</p>
                                            <p className="text-gray-500 text-xs">e.g., eBook, printable, or digital album</p>
                                        </button>

                                        <button className="w-full text-left px-4 py-3 hover:bg-orange-200 rounded-b-lg">
                                            <p className="font-medium text-gray-900 text-sm">Print on Demand</p>
                                            <p className="text-gray-500 text-xs">Custom product without inventory</p>
                                        </button>
                                    </motion.div>
                                )}
                            </AnimatePresence>
                        </div>
                    </div>
                </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 products..."
                            className="flex-1 outline-none"
                            value={search}
                            onChange={(e) => setSearch(e.target.value)}
                        />
                    </div>
                </div>

                {/* TABLE WRAPPER (RESPONSIVE) */}
                <div className="bg-white rounded-xl shadow border-none overflow-x-auto">
                    <table className="w-full min-w-[700px] text-sm text-gray-600">
                        <thead className="bg-gray-100">
                            <tr>
                                <th className="p-3">
                                    <input
                                        type="checkbox"
                                        checked={allSelected}
                                        onChange={toggleSelectAll}
                                    />
                                </th>
                                <th className="p-3">Name</th>
                                <th className="p-3 hidden sm:table-cell">Type</th>
                                <th className="p-3 hidden sm:table-cell">SKU</th>
                                <th className="p-3">Price</th>
                                <th className="p-3 hidden sm:table-cell">Inventory</th>
                                <th className="p-3 text-center">Actions</th>
                            </tr>
                        </thead>

                        <tbody>
                            {filtered.map((p) => (
                                <tr key={p.id} className="border-t hover:bg-gray-50">
                                    <td className="p-3">
                                        <input
                                            type="checkbox"
                                            checked={selectedProducts.includes(p.id)}
                                            onChange={() => toggleProduct(p.id)}
                                        />
                                    </td>

                                    <td className="p-3 flex items-center gap-3 min-w-[200px]">
                                        <img
                                            src={p.image}
                                            className="w-10 h-10 rounded object-cover border"
                                            alt={p.name}
                                        />
                                        {p.name}
                                    </td>

                                    <td className="p-3 hidden sm:table-cell">{p.type}</td>
                                    <td className="p-3 hidden sm:table-cell">{p.sku}</td>
                                    <td className="p-3">${p.price}</td>
                                    <td className="p-3 hidden sm:table-cell">{p.inventory}</td>

                                    <td className="p-3">
                                        <div className="flex justify-center gap-4">
                                            <button
                                                onClick={() =>
                                                    navigate("/admin/products/newproducts", {
                                                        state: { product: p },
                                                    })
                                                }
                                                className="text-blue-600 hover:text-blue-800"
                                            >
                                                <Edit size={18} />
                                            </button>

                                            <AlertDialog>
                                                <AlertDialogTrigger asChild>
                                                    <button className="text-orange-500 hover:text-orange-600">
                                                        <Trash2 size={18} />
                                                    </button>
                                                </AlertDialogTrigger>

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

                                                    <AlertDialogFooter>
                                                        <AlertDialogCancel>
                                                            Cancel
                                                        </AlertDialogCancel>
                                                        <AlertDialogAction
                                                            onClick={() => handleDelete(p.id)}
                                                            className="bg-orange-500 text-white"
                                                        >
                                                            Delete
                                                        </AlertDialogAction>
                                                    </AlertDialogFooter>
                                                </AlertDialogContent>
                                            </AlertDialog>
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    );
} 