"use client";

import {useEffect, useState} from "react";
import {motion, AnimatePresence} from "framer-motion";
import Link from "next/link";
import Image from "next/image";
import {FaAngleUp, FaTimes} from "react-icons/fa";
import defaultMenuIcon from "../../../../public/icons/defaulMenuIcon.svg";
import defaultMenuImage from "../../../../public/image/introImage.png";


export default function MegaMenu({items = [], mobileOpen, setMobileOpen}) {
    const [openMenu, setOpenMenu] = useState(null);
    const [openMenus, setOpenMenus] = useState({});

    const toggleMenu = (key) => {
        setOpenMenus((prev) => ({
            ...prev,
            [key]: !prev[key],
        }));
    };

    useEffect(() => {
        if (openMenu || mobileOpen) {
            document.body.style.overflow = "hidden";
            document.documentElement.style.overflow = "hidden";
        } else {
            document.body.style.overflow = "auto";
            document.documentElement.style.overflow = "auto";
        }
        return () => {
            document.body.style.overflow = "auto";
            document.documentElement.style.overflow = "auto";
        }
    }, [openMenu, mobileOpen])


    return (
        <>
            <div className="relative px-8 bg-white shadow-md">

                <div
                    className="relative py-6"
                    onMouseLeave={() => setOpenMenu(null)}
                >

                    <nav className="flex items-center justify-center max-w-full md:hidden">

                        {/* Desktop + Tablet */}
                        <ul className="md:hidden flex items-center gap-5">
                            {items.map((item, index) => (
                                <li key={index}>
                                    {item.name ? (
                                        <Link
                                            href={item.url || "#"}
                                            onMouseEnter={() =>
                                                setOpenMenu(openMenu === index ? index : index)
                                            }
                                            className={`py-6 hover:text-primary-main transition-colors ${openMenu === index ? "text-primary-main" : "text-secondary-main"}`}
                                        >
                                            {item.name}
                                        </Link>
                                    ) : (
                                        <Link
                                            href={item.url || "#"}
                                            className="py-6 text-secondary-main hover:text-primary-main transition-colors"
                                            onMouseEnter={() => setOpenMenu(null)}
                                        >
                                            {item.name}
                                        </Link>
                                    )}
                                </li>
                            ))}
                        </ul>

                    </nav>

                    <AnimatePresence>
                        {openMenu !== null && (() => {
                            const currentItem = items[openMenu];
                            if (!currentItem) return null;

                            // استخراج شماره ستون‌هایی که count شون صفر نیست
                            const validColumnIndexes = Object.entries(currentItem.counts || {})
                                .filter(([_, value]) => value !== 0)
                                .map(([key]) => Number(key.replace("col", "")));

                            // فیلتر کردن ستون‌های واقعی براساس index
                            const filteredColumns = currentItem.columns?.filter(col =>
                                validColumnIndexes.includes(col.index)
                            ) || [];

                            // تعداد ستون‌ها برای grid داینامیک
                            const colCount = filteredColumns.length;

                            if (filteredColumns.length === 0) return null;

                            return (
                                <motion.div
                                    key="mega"
                                    initial={{opacity: 0, y: -20}}
                                    animate={{opacity: 1, y: 0}}
                                    exit={{opacity: 0, y: -20}}
                                    transition={{duration: 0.3}}
                                    style={{display: "grid", gridTemplateColumns: `repeat(${colCount}, minmax(0, 1fr))`}}
                                    className="absolute bg-center bg-no-repeat bg-[url('@ /../public/icons/raviBg.png')] right-[90px] left-[90px] top-[72px] bg-white shadow-lg z-50 py-5 md:hidden border-t-2 border-primary-main rounded-2xl"
                                >
                                    {filteredColumns.map((col, idx) => (
                                        <div
                                            key={idx}
                                            className={`${idx !== filteredColumns.length - 1 ? "border-l border-dashed border-primary-main" : ""}`}
                                            style={{gridColumn: "span 1"}}
                                        >
                                            {/* عنوان ستون */}
                                            <h3 className="text-lg pr-[15px] pb-1 text-primary-main font-bold border-b border-dashed border-primary-main">
                                                {col?.title || "موارد"}
                                            </h3>

                                            {/* متن ساده */}
                                            {col.type === "link" && (
                                                <ul className="grid gap-3 py-[9px] px-[15px]">
                                                    {col.items?.map((link, i) => (
                                                        <li key={i}>
                                                            <Link
                                                                href={link.url || "#"}
                                                                className="text-secondary-main text-[15px] leading-8 hover:text-primary-main cursor-pointer transition-colors"
                                                                onClick={() => setOpenMenu(null)}
                                                            >
                                                                {link?.title}
                                                            </Link>
                                                        </li>
                                                    ))}
                                                </ul>
                                            )}

                                            {/* متن + آیکون کوچک */}
                                            {col.type === "icon_link" && (
                                                <ul className="grid gap-4 py-10 px-[30px]">
                                                    {col.items?.map((link, i) => (
                                                        <Link
                                                            href={link.url || "#"}
                                                            key={i}
                                                            className="grid grid-cols-4 justify-start items-center gap-2 group transform transition-all hover:scale-110 hover:pr-3"
                                                            onClick={() => setOpenMenu(null)}
                                                        >
                                                    <span
                                                        className="col-span-1 border-2 border-border rounded-full w-14 h-14 flex items-center justify-center">
                                                      {link?.icon}
                                                    </span>
                                                            <span
                                                                className="col-span-3 text-secondary-main text-sm font-bold group-hover:text-primary-main">
                                                      {link?.title}
                                                    </span>
                                                        </Link>
                                                    ))}
                                                </ul>
                                            )}

                                            {/* آیکون بزرگ (icon_link_6) */}
                                            {col.type === "icon_link_6" && (
                                                <div className="grid grid-cols-2 gap-x-[50px] gap-y-[30px] pt-14 px-[42px]">
                                                    {col.items?.map((link, i) => (
                                                        <Link
                                                            key={i}
                                                            href={link.url || "#"}
                                                            className="flex flex-col items-center text-center gap-3 rounded-2xl group hover:scale-110 transition transform"
                                                            onClick={() => setOpenMenu(null)}
                                                        >
                                                    <span
                                                        className="flex items-center justify-center pt-2 text-4xl min-w-24 min-h-24 rounded-full border-2 border-border">
                                                      {link?.icon}
                                                    </span>
                                                            <span
                                                                className="text-sm font-bold text-secondary-main group-hover:text-primary-main">
                                                      {link?.title}
                                                    </span>
                                                        </Link>
                                                    ))}
                                                </div>
                                            )}

                                            {/* تصویر بزرگ */}
                                            {col.type === "image" && col.items?.[0] && (
                                                <Link
                                                    href={col.items[0].url || "#"}
                                                    onClick={() => setOpenMenu(null)}
                                                    className="block w-full overflow-hidden py-20 px-[15px] rounded-2xl"
                                                >
                                                    <Image
                                                        width={500}
                                                        height={500}
                                                        src={col.items[0].image_path !== null && col.items[0].image_path.startsWith('http') ? col.items[0].image_path : defaultMenuImage}
                                                        alt={col.items[0].image_alt || "Promo"}
                                                        className="hover:scale-[1.02] transition-transform mx-auto"
                                                    />
                                                </Link>
                                            )}
                                        </div>
                                    ))}
                                </motion.div>
                            );
                        })()}
                    </AnimatePresence>
                </div>

                {/* Overlay Desktop */}
                <AnimatePresence>
                    {openMenu !== null && (() => {
                        const currentItem = items[openMenu];
                        if (!currentItem) return null;

                        const validColumnIndexes = Object.entries(currentItem.counts || {})
                            .filter(([_, value]) => value !== 0)
                            .map(([key]) => Number(key.replace("col", "")));

                        const filteredColumns =
                            currentItem.columns?.filter(col =>
                                validColumnIndexes.includes(col.index)
                            ) || [];

                        // if (filteredColumns.length === 0) return null;

                        return (
                            <motion.div
                                key="overlay"
                                initial={{ opacity: 0 }}
                                animate={{ opacity: 0.6 }}
                                exit={{ opacity: 0 }}
                                className={`absolute top-[72px] inset-0 bg-black/50 z-40 w-[100vw] h-screen sm:hidden ${filteredColumns.length === 0 && "bg-transparent"}`}
                                // onMouseEnter={() => setOpenMenu(null)}
                            />
                        );
                    })()}
                </AnimatePresence>


                {/* Mobile Drawer */}
                <AnimatePresence>
                    {mobileOpen && (
                        <>
                            {/* Overlay */}
                            <motion.div
                                key="mobile-overlay"
                                initial={{ opacity: 0 }}
                                animate={{ opacity: 0.5 }}
                                exit={{ opacity: 0 }}
                                transition={{ duration: 0.25 }}
                                className="fixed inset-0 bg-black z-40 md:block lg:hidden tablet10:hidden"
                                onClick={() => setMobileOpen(false)}
                            />

                            {/* Drawer */}
                            <motion.div
                                key="mobile-drawer"
                                initial={{ x: "-100%" }}
                                animate={{ x: 0 }}
                                exit={{ x: "-100%" }}
                                transition={{ type: "tween", duration: 0.35 }}
                                className="fixed top-0 left-0 w-72 h-full bg-white shadow-lg z-50 p-6 md:block lg:hidden tablet10:hidden overflow-y-auto"
                            >
                                <button
                                    className="text-2xl transition-colors duration-200 hover:text-danger-main mb-4"
                                    onClick={() => setMobileOpen(false)}
                                >
                                    <FaTimes size={22} />
                                </button>

                                <ul className="flex flex-col gap-4">
                                    {items.map((menu, menuIdx) => {
                                        const menuKey = `menu-${menuIdx}`;
                                        const isMenuOpen = openMenus[menuKey];

                                        // ستون‌های معتبر با count > 0
                                        const validColumns = (menu.columns || []).filter(
                                            (col) => menu.counts && menu.counts[`col${col.index}`] !== 0
                                        );

                                        const hasSubmenu = validColumns.length > 0;

                                        return (
                                            <li
                                                key={menu.id}
                                                className={`flex flex-col gap-4 ${
                                                    menuIdx === items.length - 1
                                                        ? "border-none"
                                                        : "border-b border-secondary-main pb-3"
                                                }`}
                                            >
                                                {hasSubmenu ? (
                                                    // منو با زیرمنو
                                                    <motion.div
                                                        layout
                                                        onClick={() => toggleMenu(menuKey)}
                                                        className="flex justify-between items-center cursor-pointer font-semibold text-lg hover:text-primary-main transition-colors"
                                                    >
                                                        <span>{menu.name}</span>
                                                        <motion.div
                                                            animate={{ rotate: isMenuOpen ? 180 : 0 }}
                                                            transition={{ duration: 0.3 }}
                                                        >
                                                            <FaAngleUp />
                                                        </motion.div>
                                                    </motion.div>
                                                ) : (
                                                    // منو بدون زیرمنو (فقط لینک)
                                                    <Link
                                                        href={menu.url || "#"}
                                                        className="block font-semibold text-lg text-secondary-main hover:text-primary-main transition-colors"
                                                        onClick={() => setMobileOpen(false)}
                                                    >
                                                        {menu.name}
                                                    </Link>
                                                )}

                                                {/* زیرمنو */}
                                                <AnimatePresence>
                                                    {isMenuOpen && hasSubmenu && (
                                                        <motion.div
                                                            key={`submenu-${menu.id}`}
                                                            initial={{ height: 0, opacity: 0 }}
                                                            animate={{ height: "auto", opacity: 1 }}
                                                            exit={{ height: 0, opacity: 0 }}
                                                            transition={{ duration: 0.35, ease: "easeInOut" }}
                                                            className="flex flex-col gap-3 overflow-hidden p-2 bg-box rounded-lg"
                                                        >
                                                            {validColumns.map((col, colIdx) => {
                                                                const colKey = `${menuKey}-col-${colIdx}`;
                                                                const isColOpen = openMenus[colKey];

                                                                return (
                                                                    <motion.div key={colIdx} layout>
                                                                        <motion.div
                                                                            layout
                                                                            className={`flex gap-4 justify-between items-center cursor-pointer ${
                                                                                colIdx === validColumns.length - 1
                                                                                    ? "border-none"
                                                                                    : "border-b-2 border-border pb-2"
                                                                            } text-secondary-main font-medium transition-colors duration-200 hover:text-primary-main`}
                                                                            onClick={() => toggleMenu(colKey)}
                                                                        >
                                                                            <span>{col.type}</span>
                                                                            <motion.div
                                                                                animate={{ rotate: isColOpen ? 180 : 0 }}
                                                                                transition={{ duration: 0.3 }}
                                                                            >
                                                                                <FaAngleUp />
                                                                            </motion.div>
                                                                        </motion.div>

                                                                        <AnimatePresence>
                                                                            {isColOpen && (
                                                                                <motion.div
                                                                                    initial={{ height: 0, opacity: 0 }}
                                                                                    animate={{ height: "auto", opacity: 1 }}
                                                                                    exit={{ height: 0, opacity: 0 }}
                                                                                    transition={{ duration: 0.3 }}
                                                                                    className="flex flex-col gap-3 py-3 overflow-hidden"
                                                                                >
                                                                                    {/* لینک‌ها */}
                                                                                    {col.type === "link" &&
                                                                                        col.items.map((link) => (
                                                                                            <motion.div
                                                                                                key={link.id}
                                                                                                initial={{ opacity: 0, x: -10 }}
                                                                                                animate={{ opacity: 1, x: 0 }}
                                                                                                exit={{ opacity: 0, x: -10 }}
                                                                                                transition={{ duration: 0.25 }}
                                                                                                className="py-2"
                                                                                            >
                                                                                                <Link
                                                                                                    href={link.url || "#"}
                                                                                                    onClick={() => setMobileOpen(false)}
                                                                                                    className="block text-secondary-main hover:text-primary-main transition-colors pr-2"
                                                                                                >
                                                                                                    {link.title}
                                                                                                </Link>
                                                                                            </motion.div>
                                                                                        ))}

                                                                                    {/* icon_link و icon_link_6 */}
                                                                                    {["icon_link", "icon_link_6"].includes(col.type) &&
                                                                                        col.items.map((link) => (
                                                                                            <motion.div
                                                                                                key={link.id}
                                                                                                initial={{ opacity: 0, x: -10 }}
                                                                                                animate={{ opacity: 1, x: 0 }}
                                                                                                exit={{ opacity: 0, x: -10 }}
                                                                                                transition={{ duration: 0.25 }}
                                                                                                className="py-2"
                                                                                            >
                                                                                                <Link
                                                                                                    href={link.url || "#"}
                                                                                                    onClick={() => setMobileOpen(false)}
                                                                                                    className="grid grid-cols-4 items-center gap-2 text-secondary-main hover:text-primary-main transition-colors pr-3"
                                                                                                >
                                                                                                    <Image
                                                                                                        src={link.image_path || defaultMenuIcon}
                                                                                                        alt={link.image_alt || ""}
                                                                                                        width={20}
                                                                                                        height={20}
                                                                                                        className="col-span-1 w-6 h-6 rounded-full"
                                                                                                    />
                                                                                                    <span className="col-span-3">{link.title}</span>
                                                                                                </Link>
                                                                                            </motion.div>
                                                                                        ))}

                                                                                    {/* تصویر */}
                                                                                    {col.type === "image" && col.items[0] && (
                                                                                        <motion.div
                                                                                            initial={{ opacity: 0 }}
                                                                                            animate={{ opacity: 1 }}
                                                                                            exit={{ opacity: 0 }}
                                                                                            transition={{ duration: 0.25 }}
                                                                                        >
                                                                                            <Link
                                                                                                href={col.items[0].url || "#"}
                                                                                                onClick={() => setMobileOpen(false)}
                                                                                                className="block overflow-hidden rounded-xl"
                                                                                            >
                                                                                                <Image
                                                                                                    src={col.items[0].image_path.startsWith('http') ? col.items[0].image_path : defaultMenuImage}
                                                                                                    alt={col.items[0].image_alt || ""}
                                                                                                    width={300}
                                                                                                    height={150}
                                                                                                    className="w-full object-cover"
                                                                                                />
                                                                                            </Link>
                                                                                        </motion.div>
                                                                                    )}
                                                                                </motion.div>
                                                                            )}
                                                                        </AnimatePresence>
                                                                    </motion.div>
                                                                );
                                                            })}
                                                        </motion.div>
                                                    )}
                                                </AnimatePresence>
                                            </li>
                                        );
                                    })}
                                </ul>
                            </motion.div>
                        </>
                    )}
                </AnimatePresence>

            </div>
        </>
    );
}
