import { Link, useLocation, useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
import {
  Menu,
  X,
  LogIn,
  LogOut,
  Wifi,
  Clock,
} from "lucide-react";

import NotificationBell from "./NotificationBell";

const navByRole = {
  admin: [
    { label: "Dashboard Admin", path: "/admin" },
    { label: "Data SPPG", path: "/admin/sppg" },
    { label: "Pengaduan", path: "/admin/pengaduan" },
    { label: "Pengiriman", path: "/admin/pengiriman" },
    { label: "Manajemen User", path: "/admin/users" },
    { label: "Audit Log", path: "/admin/audit-log" },
    { label: "Backup Data", path: "/admin/backup" },
    { label: "Statistik", path: "/statistik" },
    { label: "Laporan", path: "/laporan" },
  ],

  pemerintah: [
    { label: "Dashboard Nasional", path: "/pemerintah/dashboard" },
    { label: "Monitoring SPPG", path: "/daftar-sppg" },
    { label: "Pengaduan", path: "/pengaduan" },
    { label: "Pengiriman MBG", path: "/pemerintah/pengiriman" },
    { label: "Aktivitas SPPG", path: "/pemerintah/aktivitas" },
    { label: "Statistik", path: "/statistik" },
    { label: "Laporan Dana", path: "/laporan" },
  ],

  sppg: [
    { label: "SPPG Saya", path: "/sppg/saya" },
    { label: "Pengaduan", path: "/pengaduan" },
    { label: "Pengiriman", path: "/sppg/pengiriman" },
    { label: "Daftar SPPG", path: "/daftar-sppg" },
  ],

  validator: [
    { label: "Validasi Data", path: "/validator/validasi" },
    { label: "Validasi Pengaduan", path: "/validator/pengaduan" },
    { label: "Pengiriman", path: "/validator/pengiriman" },
    { label: "Daftar SPPG", path: "/daftar-sppg" },
    { label: "Statistik", path: "/statistik" },
  ],

  publik: [
    { label: "Beranda", path: "/" },
    { label: "Daftar SPPG", path: "/daftar-sppg" },
    { label: "Tracking", path: "/tracking" },
    { label: "Statistik", path: "/statistik" },
    { label: "Pengaduan", path: "/pengaduan" },
    { label: "FAQ", path: "/faq" },
  ],
};

const isActivePath = (currentPath, menuPath) => {
  if (menuPath === "/") return currentPath === "/";

  if (
    menuPath === "/tracking" ||
    menuPath === "/daftar-sppg" ||
    menuPath === "/statistik" ||
    menuPath === "/pengaduan" ||
    menuPath === "/faq" ||
    menuPath === "/laporan"
  ) {
    return currentPath === menuPath;
  }

  if (menuPath === "/admin") return currentPath === "/admin";
  if (menuPath === "/validator/validasi") {
    return currentPath === "/validator/validasi";
  }
  if (menuPath === "/validator/pengaduan") {
    return currentPath === "/validator/pengaduan";
  }
  if (menuPath === "/validator/pengiriman") {
    return currentPath === "/validator/pengiriman";
  }

  return currentPath === menuPath || currentPath.startsWith(`${menuPath}/`);
};

const getLogoPath = (role) => {
  if (role === "admin") return "/admin";
  if (role === "pemerintah") return "/pemerintah/dashboard";
  if (role === "sppg") return "/sppg/saya";
  if (role === "validator") return "/validator/validasi";
  return "/";
};

export default function Navbar() {
  const [mobileOpen, setMobileOpen] = useState(false);
  const [role, setRole] = useState("publik");
  const [username, setUsername] = useState("");
  const [currentTime, setCurrentTime] = useState("");

  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    const savedToken = localStorage.getItem("token");
    const savedRole = localStorage.getItem("role");
    const savedUsername = localStorage.getItem("username");

    if (
      savedToken &&
      savedRole &&
      savedRole !== "masyarakat" &&
      navByRole[savedRole]
    ) {
      setRole(savedRole);
      setUsername(savedUsername || "");
    } else {
      setRole("publik");
      setUsername("");
    }

    setMobileOpen(false);
  }, [location.pathname]);

  useEffect(() => {
    const updateTime = () => {
      const now = new Date();

      const formatted = now.toLocaleTimeString("id-ID", {
        hour: "2-digit",
        minute: "2-digit",
      });

      setCurrentTime(formatted);
    };

    updateTime();

    const timer = setInterval(updateTime, 1000);

    return () => clearInterval(timer);
  }, []);

  const isLoggedIn = role !== "publik";
  const navLinks = navByRole[role] || navByRole.publik;
  const logoPath = getLogoPath(role);

  const getDesktopLinkClass = (active) => {
    if (active) {
      return "bg-blue-700 text-white shadow-sm";
    }

    return "text-slate-600 hover:bg-blue-50 hover:text-blue-700";
  };

  const getMobileLinkClass = (active) => {
    if (active) {
      return "bg-blue-700 text-white shadow-sm";
    }

    return "text-slate-600 hover:bg-blue-50 hover:text-blue-700";
  };

  const handleLogout = () => {
    localStorage.removeItem("token");
    localStorage.removeItem("role");
    localStorage.removeItem("username");
    localStorage.removeItem("user_id");

    setRole("publik");
    setUsername("");
    setMobileOpen(false);

    navigate("/");
  };

  return (
    <header className="sticky top-0 z-50 border-b border-blue-100/70 bg-white/90 shadow-sm shadow-slate-200/60 backdrop-blur-xl">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-16 gap-4">
          <Link
            to={logoPath}
            onClick={() => setMobileOpen(false)}
            className="flex items-center gap-3 flex-shrink-0 rounded-full border border-blue-100 bg-white px-3 py-1.5 shadow-sm transition hover:-translate-y-0.5 hover:shadow-md"
          >
            <img
              src="/logo-open-plate.png"
              alt="Logo OPEN PLATE"
              className="h-10 w-10 object-contain"
            />

            <div className="leading-tight">
              <p className="text-sm font-black tracking-wide text-slate-900">
                OPEN PLATE
              </p>
              <p className="text-[10px] font-bold uppercase tracking-[0.16em] text-blue-600">
                Portal MBG
              </p>
            </div>
          </Link>

          <nav className="hidden md:flex items-center gap-1 flex-1 overflow-x-auto">
            {navLinks.map((link) => {
              const active = isActivePath(location.pathname, link.path);

              return (
                <Link
                  key={link.path}
                  to={link.path}
                  className={`px-3.5 py-2 rounded-full text-sm font-bold transition-colors whitespace-nowrap ${getDesktopLinkClass(
                    active
                  )}`}
                >
                  {link.label}
                </Link>
              );
            })}
          </nav>

          <div className="hidden md:flex items-center gap-2 flex-shrink-0">
            <div className="flex items-center gap-1.5 rounded-full border border-emerald-100 bg-emerald-50 px-3 py-2 text-xs font-bold text-emerald-700">
              <Wifi className="w-4 h-4" />
              Online
            </div>

            <NotificationBell />

            <div className="flex items-center gap-1.5 rounded-full border border-blue-100 bg-white px-3 py-2 text-xs font-bold text-slate-700 shadow-sm">
              <Clock className="w-4 h-4 text-primary" />
              {currentTime}
            </div>

            {isLoggedIn && (
              <div className="text-right leading-tight px-2">
                <p className="text-xs text-muted-foreground">Masuk sebagai</p>
                <p className="text-sm font-semibold text-primary">
                  {username || role}
                </p>
              </div>
            )}

            {isLoggedIn ? (
              <button
                type="button"
                onClick={handleLogout}
                className="flex items-center gap-1 px-3 py-2 rounded-full text-sm font-bold bg-red-50 text-red-600 hover:bg-red-100 transition"
              >
                <LogOut className="w-4 h-4" />
                Logout
              </button>
            ) : (
              <Link
                to="/login"
                className="flex items-center gap-1 px-4 py-2 rounded-full text-sm font-bold bg-blue-700 text-white hover:bg-blue-800 transition shadow-sm"
              >
                <LogIn className="w-4 h-4" />
                Login
              </Link>
            )}
          </div>

          <button
            type="button"
            className="md:hidden p-2 rounded-full hover:bg-blue-50 transition"
            onClick={() => setMobileOpen((prev) => !prev)}
            aria-label="Buka menu navigasi"
          >
            {mobileOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
          </button>
        </div>
      </div>

      {mobileOpen && (
        <div className="md:hidden border-t border-blue-100 bg-white/95 shadow-sm backdrop-blur-xl">
          <div className="px-4 py-3 flex items-center gap-2 border-b border-border">
            <div className="flex items-center gap-1.5 rounded-full border border-emerald-100 bg-emerald-50 px-3 py-2 text-xs font-bold text-emerald-700">
              <Wifi className="w-4 h-4" />
              Online
            </div>

            <div className="flex items-center gap-1.5 rounded-lg border bg-white px-2.5 py-2 text-xs font-bold text-slate-700">
              <Clock className="w-4 h-4 text-primary" />
              {currentTime}
            </div>

            <div className="ml-auto flex items-center gap-2">
              <NotificationBell />

              {isLoggedIn && (
                <div className="text-right leading-tight">
                  <p className="text-xs text-muted-foreground">
                    {username || role}
                  </p>
                  <p className="text-xs font-semibold text-primary">{role}</p>
                </div>
              )}
            </div>
          </div>

          <nav className="px-4 py-3 space-y-1">
            {navLinks.map((link) => {
              const active = isActivePath(location.pathname, link.path);

              return (
                <Link
                  key={link.path}
                  to={link.path}
                  onClick={() => setMobileOpen(false)}
                  className={`block px-3 py-2.5 rounded-2xl text-sm font-bold transition-colors ${getMobileLinkClass(
                    active
                  )}`}
                >
                  {link.label}
                </Link>
              );
            })}

            {isLoggedIn ? (
              <button
                type="button"
                onClick={handleLogout}
                className="w-full text-left px-3 py-2.5 rounded-2xl text-sm font-bold bg-red-50 text-red-600 hover:bg-red-100"
              >
                Logout
              </button>
            ) : (
              <Link
                to="/login"
                onClick={() => setMobileOpen(false)}
                className="block px-3 py-2.5 rounded-2xl text-sm font-bold bg-blue-700 text-white"
              >
                Login
              </Link>
            )}
          </nav>
        </div>
      )}
    </header>
  );
}