"use client";

import React, { useMemo, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { useRouter, usePathname } from "next/navigation";
import { useTranslation } from "react-i18next";
import ReactCountryFlag from "react-country-flag";

import {
  Drawer,
  IconButton,
  Box,
  Divider,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
} from "@mui/material";

import MenuIcon from "@mui/icons-material/Menu";
import CloseIcon from "@mui/icons-material/Close";
import LanguageOutlinedIcon from "@mui/icons-material/LanguageOutlined";
import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
import AccountCircleIcon from "@mui/icons-material/AccountCircle";
import LogoutIcon from "@mui/icons-material/Logout";

import HomeOutlinedIcon from "@mui/icons-material/HomeOutlined";
import StorefrontOutlinedIcon from "@mui/icons-material/StorefrontOutlined";
import LocalOfferOutlinedIcon from "@mui/icons-material/LocalOfferOutlined";
import FavoriteBorderOutlinedIcon from "@mui/icons-material/FavoriteBorderOutlined";
import ShoppingCartOutlinedIcon from "@mui/icons-material/ShoppingCartOutlined";
import ReceiptLongOutlinedIcon from "@mui/icons-material/ReceiptLongOutlined";

import Button from "./ui/Button";
import { getUserInitials } from "@/utils/functions";
import { useAuth } from "@/context/AuthContext";
import LogoutConfirmModal from "@/components/modals/LogoutConfirmModal";
import { useModal } from "@/context/ModalContext";
import PartnerModal from "./modals/PartnerModal";

// نفس الروابط الموجودة في الـ Navbar الرئيسي
const NAV_ITEMS = [
  {
    key: "home",
    href: "/",
    icon: HomeOutlinedIcon,
    match: (p) => p === "/",
    labelKey: "nav.home",
  },
  {
    key: "restaurants",
    href: "/restaurants",
    icon: StorefrontOutlinedIcon,
    match: (p) => p.startsWith("/restaurants"),
    labelKey: "nav.restaurants",
  },
  {
    key: "offers",
    href: "/offers",
    icon: LocalOfferOutlinedIcon,
    match: (p) => p.startsWith("/offers"),
    labelKey: "nav.offers",
  },
  {
    key: "favorites",
    href: "/favorites",
    icon: FavoriteBorderOutlinedIcon,
    match: (p) => p.startsWith("/favorites"),
    labelKey: "nav.favorites",
    withBadge: "favorites",
  },
  {
    key: "cart",
    href: "/cart",
    icon: ShoppingCartOutlinedIcon,
    match: (p) => p.startsWith("/cart"),
    labelKey: "nav.cart",
    withBadge: "cart",
  },
  {
    key: "orders",
    href: "/orders",
    icon: ReceiptLongOutlinedIcon,
    match: (p) => p.startsWith("/orders"),
    labelKey: "nav.orders",
  },
];

const LANGS = [
  { code: "en", label: "English", country: "US" },
  { code: "ar", label: "العربية", country: "SA" },
];

const Badge = ({ children }) => (
  <span className="ml-2 rounded-full bg-brand px-2 py-0.5 text-[11px] text-white">
    {children}
  </span>
);

export default function MobileNavbar({ favCount = 0, cartCount = 0 }) {
  const [open, setOpen] = useState(false);
  const [logoutOpen, setLogoutOpen] = useState(false);
  const [langOpen, setLangOpen] = useState(false);

  const { t, i18n } = useTranslation();
  const pathname = usePathname() || "/";
  const router = useRouter();

  const { user, authReady } = useAuth();
  const authenticated = !!user;

  const { openModal, closeModal, isModalOpen } = useModal();

  const anchor = i18n.language === "ar" ? "right" : "left";

  const currentLang = useMemo(
    () => LANGS.find((l) => l.code === i18n.language) || LANGS[0],
    [i18n.language],
  );

  const closeDrawer = () => {
    setOpen(false);
    setLangOpen(false);
  };

  const handleNavClick = (href) => {
    router.push(href);
    closeDrawer();
  };

  const onLogoutClick = () => {
    closeDrawer();
    setLogoutOpen(true);
  };

  const getBadgeValue = (item) => {
    if (item.withBadge === "favorites") return favCount;
    if (item.withBadge === "cart") return cartCount;
    return 0;
  };

  const changeLang = (code) => {
    localStorage.setItem("lang", code);
    i18n.changeLanguage(code);
    setLangOpen(false);
  };

  return (
    <>
      {/* شريط علوي للموبايل فقط: شعار + زر منيو */}
      <div
        className="lg:hidden w-full bg-white border-b border-gray-200"
        suppressHydrationWarning
      >
        <div className="custom-container flex items-center justify-between py-2">
          <Link href="/" className="flex items-center gap-2">
            <Image src="/Logo Otlob.png" alt="logo" width={80} height={70} />
            {/*
            <span className="text-brand font-semibold text-[15px]">
              {t("brand")}
            </span>       
            */}
          </Link>

          <IconButton
            onClick={() => setOpen(true)}
            sx={{
              bgcolor: "#FFF7F1",
              border: "1px solid #FFE3CC",
              borderRadius: "14px",
              color: "#FF7A00",
              p: 1.2,
              boxShadow: "0 3px 6px rgba(255, 122, 0, 0.12)",
              "&:hover": { bgcolor: "#FFEEDD" },
            }}
          >
            <MenuIcon sx={{ fontSize: 22 }} />
          </IconButton>
        </div>
      </div>

      {/* Drawer جانبي */}
      <Drawer
        anchor={anchor}
        open={open}
        onClose={closeDrawer}
        PaperProps={{ sx: { borderRadius: 0 } }}
      >
        <Box sx={{ width: 280, p: 2 }}>
          {/* هيدر داخل الدروار: شعار + X */}
          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              mb: 1,
            }}
          >
            <Link
              href="/"
              onClick={closeDrawer}
              className="flex items-center gap-2"
            >
              <Image src="/Logo Otlob.png" alt="logo" width={80} height={60} />
              {/**                       
                <span className="text-brand font-semibold text-[15px]">
                  {t("brand")}
                </span>         
               */}
            </Link>

            <IconButton onClick={closeDrawer} size="small">
              <CloseIcon />
            </IconButton>
          </Box>

          <Divider sx={{ mb: 1.5 }} />

          {/* الروابط */}
          <List>
            {NAV_ITEMS.map((item) => {
              const active = item.match(pathname);
              const Icon = item.icon;
              const badge = getBadgeValue(item);

              return (
                <ListItemButton
                  key={item.key}
                  onClick={() => handleNavClick(item.href)}
                  sx={{
                    borderRadius: 1.5,
                    mb: 0.5,
                    "&:hover": { bgcolor: "#FFF7F1" },
                    ...(active && {
                      bgcolor: "#FFF7F1",
                      "& .MuiListItemIcon-root": { color: "#FF7A00" },
                    }),
                  }}
                >
                  <ListItemIcon sx={{ minWidth: 32, color: "#555" }}>
                    <Icon fontSize="small" />
                  </ListItemIcon>

                  <ListItemText
                    primary={t(item.labelKey)}
                    primaryTypographyProps={{ fontSize: 14 }}
                  />

                  {badge > 0 && <Badge>{badge > 99 ? "99+" : badge}</Badge>}
                </ListItemButton>
              );
            })}
          </List>

          <Divider sx={{ my: 2 }} />

          {/* User Info Section (if authenticated) */}
          {authenticated && user && (
            <>
              <Box
                sx={{
                  p: 2,
                  mb: 2,
                  bgcolor: "#FFF7F1",
                  borderRadius: 2,
                  border: "1px solid #FFE3CC",
                }}
              >
                <Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
                  <Box
                    sx={{
                      width: 48,
                      height: 48,
                      borderRadius: "50%",
                      bgcolor: "#FF7A00",
                      color: "white",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      fontSize: 16,
                      fontWeight: 600,
                    }}
                  >
                    {getUserInitials(user?.name || user?.email)}
                  </Box>

                  <Box sx={{ flex: 1, minWidth: 0 }}>
                    <Box
                      sx={{
                        fontSize: 15,
                        fontWeight: 600,
                        color: "#333",
                        mb: 0.5,
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap",
                      }}
                    >
                      {user?.name || t("nav.profile")}
                    </Box>
                    <Box
                      sx={{
                        fontSize: 12,
                        color: "#666",
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        whiteSpace: "nowrap",
                      }}
                    >
                      {user?.email}
                    </Box>
                  </Box>
                </Box>
              </Box>

              {/* Profile Link */}
              <ListItemButton
                onClick={() => handleNavClick("/profile")}
                sx={{
                  borderRadius: 1.5,
                  mb: 0.5,
                  "&:hover": { bgcolor: "#FFF7F1" },
                }}
              >
                <ListItemIcon sx={{ minWidth: 32, color: "#555" }}>
                  <AccountCircleIcon fontSize="small" />
                </ListItemIcon>
                <ListItemText
                  primary={t("nav.profile")}
                  primaryTypographyProps={{ fontSize: 14 }}
                />
              </ListItemButton>

              <Divider sx={{ my: 1.5 }} />
            </>
          )}

          {/* Language Switcher (Strong UI) */}
          <div className="relative mb-3">
            <button
              type="button"
              onClick={() => setLangOpen((v) => !v)}
              className="flex w-full items-center justify-between rounded-xl border border-gray-200 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50"
            >
              <span className="flex items-center gap-2">
                <LanguageOutlinedIcon fontSize="small" />
                <span>{t("nav.lang")}</span>
              </span>

              <span className="flex items-center gap-2">
                <ReactCountryFlag
                  svg
                  countryCode={currentLang.country}
                  style={{
                    width: "1.2em",
                    height: "1.2em",
                    borderRadius: "4px",
                  }}
                />
                <span className="text-xs font-semibold text-gray-700 uppercase">
                  {currentLang.code}
                </span>
                <KeyboardArrowDownIcon
                  fontSize="small"
                  className={`text-gray-500 transition-transform ${
                    langOpen ? "rotate-180" : ""
                  }`}
                />
              </span>
            </button>

            {langOpen && (
              <div className="mt-2 overflow-hidden rounded-xl border border-gray-200 bg-white shadow-sm">
                {LANGS.map((lang) => {
                  const active = i18n.language === lang.code;
                  return (
                    <button
                      key={lang.code}
                      type="button"
                      onClick={() => changeLang(lang.code)}
                      className={`flex w-full items-center gap-3 px-3 py-2 text-sm transition-colors ${
                        active
                          ? "bg-orange-50 text-brand"
                          : "text-gray-700 hover:bg-gray-50"
                      }`}
                    >
                      <ReactCountryFlag
                        svg
                        countryCode={lang.country}
                        style={{
                          width: "1.2em",
                          height: "1.2em",
                          borderRadius: "4px",
                        }}
                      />
                      <span className={active ? "font-medium" : ""}>
                        {lang.label}
                      </span>
                    </button>
                  );
                })}
              </div>
            )}
          </div>

          {/* أزرار الدخول والانضمام أو تسجيل الخروج */}
          {authenticated && user ? (
            <>
              <button
                onClick={onLogoutClick}
                className="w-full flex items-center justify-center gap-2 mb-3 px-4 py-2 border-2 border-red-500 text-red-600 rounded-xl font-medium text-sm hover:bg-red-50 transition-colors"
              >
                <LogoutIcon sx={{ fontSize: 18 }} />
                {t("nav.logout")}
              </button>

              <Button
                variant="primary"
                fullWidth
                size="sm"
                onClick={() => {
                  closeDrawer();
                  openModal("partner");
                }}
              >
                {t("nav.join")}
              </Button>
            </>
          ) : (
            <>
              {!authReady ? (
                <div className="w-full h-10 rounded-xl bg-gray-100 animate-pulse" />
              ) : (
                <div className="flex flex-col gap-2">
                  <Button
                    variant="outline"
                    fullWidth
                    size="sm"
                    onClick={() => {
                      closeDrawer();
                      router.push("/auth/login");
                    }}
                  >
                    {t("nav.login")}
                  </Button>

                  <Button
                    variant="primary"
                    fullWidth
                    size="sm"
                    onClick={() => {
                      closeDrawer();
                      openModal("partner");
                    }}
                  >
                    {t("nav.join")}
                  </Button>
                </div>
              )}
            </>
          )}
        </Box>
      </Drawer>

      <LogoutConfirmModal
        open={logoutOpen}
        onClose={() => setLogoutOpen(false)}
        redirectTo="/"
      />

      <PartnerModal
        open={isModalOpen("partner")}
        onClose={() => closeModal("partner")}
      />
    </>
  );
}
