import { NavLink, useLocation } from "react-router-dom";
import { useMagicBag } from "../context/MagicBagContext";
import { useInbox } from "../context/InboxContext";
import profileIcon from "../../assets/nav-icons/nav-icon-profile.png";
import chatbotIcon from "../../assets/nav-icons/nav-icon-chatbot.png";
import magicBagIcon from "../../assets/nav-icons/nav-icon-bag.png";
import homeIcon from "../../assets/nav-icons/nav-icon-home.png";
import bellIcon from "../../assets/nav-icons/nav-icon-bell.png";

const navItems = [
  { id: "chatbot", label: "چت با ربات", path: "/public-chat", icon: chatbotIcon },
  { id: "magic-bag", label: "کیف جادویی", path: "/magic-bag", icon: magicBagIcon },
  { id: "home", label: "خانه", path: "/", icon: homeIcon },
  { id: "messages", label: "اعلان‌ها", path: "/messages", icon: bellIcon },
  { id: "profile", label: "پروفایل", path: "/profile", icon: profileIcon },
] as const;

const ACTIVE_GLOW =
  "drop-shadow(0 0 8px rgba(255, 104, 205, 0.55)) drop-shadow(0 0 14px rgba(255, 104, 205, 0.2))";
const IDLE_GLOW = "drop-shadow(0 3px 6px rgba(0, 0, 0, 0.34))";
const UNDERGLOW_BG =
  "radial-gradient(ellipse at center, rgba(255, 106, 207, 0.22) 0%, rgba(255, 106, 207, 0.08) 56%, transparent 100%)";

const toPersianBadge = (count: number): string => {
  if (count > 99) return "۹۹+";

  const persianDigits = "۰۱۲۳۴۵۶۷۸۹";
  return String(count).replace(/\d/g, (digit) => persianDigits[parseInt(digit, 10)]);
};

const isNavActive = (
  id: (typeof navItems)[number]["id"],
  path: string,
  pathname: string,
) => {
  if (id === "home") return pathname === "/";
  if (id === "chatbot") return pathname === "/public-chat" || pathname.startsWith("/chatbot");
  if (id === "profile") return pathname === "/profile" || pathname === "/edit-profile";

  return pathname === path;
};

interface BottomNavProps {
  fixed?: boolean;
}

export function BottomNav({ fixed = true }: BottomNavProps) {
  const location = useLocation();
  const { hasNewItem, clearBadge } = useMagicBag();
  const { unreadCount } = useInbox();

  return (
    <div
      className={
        fixed
          ? "app-bottom-nav pointer-events-none fixed bottom-0 left-0 right-0 z-50 w-full transition-opacity duration-200"
          : "bottom-nav app-bottom-nav pointer-events-none w-full transition-opacity duration-200"
      }
    >
      <nav
        className="pointer-events-auto relative mx-auto w-full max-w-[392px] px-1"
        aria-label="ناوبری اصلی"
        style={{
          paddingBottom: "calc(env(safe-area-inset-bottom, 0px) + 8px)",
        }}
      >
        <div
          className="relative h-[86px] rounded-[999px] border-[0.5px] border-transparent px-1"
          style={{
            backgroundImage: `
              linear-gradient(180deg, #2E1B3D 0%, #23183E 100%),
              linear-gradient(120deg, #7c3aed 0%, #f97316 58%, #facc15 100%)
            `,
            backgroundOrigin: "border-box",
            backgroundClip: "padding-box, border-box",
            boxShadow:
              "0 -7px 20px rgba(7, 0, 18, 0.5), 0 6px 14px rgba(5, 2, 12, 0.26), inset 0 1px 0 rgba(255, 255, 255, 0.2), inset 0 2px 5px rgba(255, 222, 255, 0.09), inset 0 -2px 0 rgba(12, 7, 27, 0.72), inset 0 -8px 14px rgba(8, 4, 18, 0.34), inset 0 0 0 1px rgba(255, 255, 255, 0.045), inset 0 0 0 2px rgba(17, 10, 35, 0.32)",
            backdropFilter: "blur(14px)",
            WebkitBackdropFilter: "blur(14px)",
          }}
        >
          <div className="relative mx-auto grid h-full w-[calc(100%-14px)] grid-cols-5 items-start pt-1.5" dir="ltr">
            {navItems.map((item) => {
              const isMagicBag = item.id === "magic-bag";
              const hasMessageBadge = item.id === "messages" && unreadCount > 0;

              return (
                <NavLink
                  key={item.id}
                  to={item.path}
                  end={item.path === "/"}
                  onClick={() => {
                    if (isMagicBag && hasNewItem) {
                      clearBadge();
                    }
                  }}
                  className="relative flex h-full min-w-0 flex-col items-center justify-start pb-1 pt-0.5 outline-none"
                  aria-label={item.label}
                  dir="rtl"
                >
                  {({ isActive }) => {
                    const active = isActive || isNavActive(item.id, item.path, location.pathname);

                    return (
                      <>
                        <div className="relative">
                          <div
                            className="relative flex h-[37px] w-[37px] items-center justify-center"
                            style={{
                              filter: active ? ACTIVE_GLOW : IDLE_GLOW,
                            }}
                          >
                            <img
                              src={item.icon}
                              alt=""
                              className="h-[37px] w-[37px] object-contain"
                              style={{
                                opacity: active ? 1 : 0.92,
                              }}
                            />

                            {isMagicBag && hasNewItem && (
                              <span
                                className="absolute -right-0.5 top-0.5 h-3 w-3 rounded-full border border-white"
                                style={{
                                  background: "linear-gradient(135deg, #ff4d66 0%, #d7193f 100%)",
                                  boxShadow: "0 0 10px rgba(255, 57, 92, 0.8)",
                                }}
                              />
                            )}

                            {hasMessageBadge && (
                              <span
                                className="absolute -right-2 -top-1 flex h-5 min-w-5 items-center justify-center rounded-full border border-red-200 px-1 text-[12px] font-bold leading-none text-white"
                                style={{
                                  background: "linear-gradient(180deg, #ff403f 0%, #d51d28 100%)",
                                  boxShadow: "0 0 12px rgba(255, 58, 70, 0.85)",
                                }}
                              >
                                {toPersianBadge(unreadCount)}
                              </span>
                            )}
                          </div>
                          {active && (
                            <span
                              className="pointer-events-none absolute left-1/2 top-[39px] h-[12px] w-[40px] -translate-x-1/2 rounded-full"
                              style={{ background: UNDERGLOW_BG }}
                            />
                          )}
                        </div>

                        <span
                          className="absolute bottom-[14px] left-1/2 block w-[92%] -translate-x-1/2 truncate px-0.5 text-center font-[Alibaba] text-[10px] font-bold leading-4 sm:text-[11px]"
                          style={{
                            opacity: active ? 1 : 0.92,
                            color: active ? "#ff79cf" : "#ffd6f0",
                            textShadow: active
                              ? "0 0 10px rgba(255, 83, 198, 0.72), 0 2px 4px rgba(0, 0, 0, 0.65)"
                              : "0 2px 5px rgba(0, 0, 0, 0.7)",
                          }}
                        >
                          {item.label}
                        </span>
                      </>
                    );
                  }}
                </NavLink>
              );
            })}
          </div>
        </div>
      </nav>
    </div>
  );
}
