"use client";

import { useEffect } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  LayoutDashboard,
  Send,
  ArrowDownLeft,
  ArrowUpRight,
  Users,
  UserCheck,
  TrendingUp,
  Receipt,
  FileText,
  ShieldCheck,
  Lock,
  UserCircle,
  X,
  Bell,
  type LucideIcon,
} from "lucide-react";
import { Logo } from "@/components/common/Logo";
import { useTranslation } from "@/hooks/useTranslation";
import { cn } from "@/lib/utils";

interface NavItem {
  href: string;
  key: string;
  icon: LucideIcon;
}

interface NavGroup {
  items: NavItem[];
}

const NAV_GROUPS: NavGroup[] = [
  {
    items: [
      { href: "/agent/dashboard",       key: "agent.sidebar.dashboard",       icon: LayoutDashboard },
    ],
  },
  {
    items: [
      { href: "/agent/send-remittance", key: "agent.sidebar.sendRemittance", icon: Send        },
      { href: "/agent/my-recipients",   key: "agent.sidebar.myRecipients",   icon: UserCheck    },
      { href: "/agent/my-senders",      key: "agent.sidebar.mySenders",      icon: Users        },
      { href: "/agent/money-in",        key: "agent.sidebar.moneyIn",        icon: ArrowDownLeft },
      { href: "/agent/money-out",       key: "agent.sidebar.moneyOut",       icon: ArrowUpRight  },
    ],
  },
  {
    items: [
      { href: "/agent/transactions",    key: "agent.sidebar.transactions",    icon: Receipt      },
      { href: "/agent/statements",      key: "agent.sidebar.statements",      icon: FileText     },
      { href: "/agent/profit-log",      key: "agent.sidebar.profitLog",      icon: TrendingUp   },
    ],
  },
  {
    items: [
      { href: "/agent/notifications",   key: "agent.sidebar.notifications",   icon: Bell         },
      { href: "/agent/profile",         key: "agent.sidebar.profile",         icon: UserCircle   },
    ],
  },
  {
    items: [
      { href: "/agent/security",        key: "agent.sidebar.security",        icon: Lock         },
      { href: "/agent/kyc",             key: "agent.sidebar.kyc",             icon: ShieldCheck  },
    ],
  },
];

interface Props {
  open: boolean;
  onClose: () => void;
}

export function AgentSidebar({ open, onClose }: Props) {
  const pathname = usePathname();
  const { t, dir } = useTranslation();

  // Below 1440px it's a drawer — auto-close on navigation. At 1440px+ it's a
  // persistent panel the user folds manually, so a route change shouldn't close it.
  useEffect(() => {
    if (open && !window.matchMedia("(min-width: 1440px)").matches) onClose();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pathname]);

  // Below 1440px it's an overlay drawer, so scroll needs locking while open. At
  // 1440px+ it's a persistent panel that pushes content — page scroll is unaffected there.
  useEffect(() => {
    if (!open || window.matchMedia("(min-width: 1440px)").matches) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = prev;
    };
  }, [open]);

  const slideClosed = dir === "rtl" ? "translate-x-full" : "-translate-x-full";

  return (
    <>
      <div
        className={cn(
          "fixed inset-0 z-40 bg-slate-900/60 backdrop-blur-md transition-opacity duration-300 min-[1440px]:hidden",
          open ? "opacity-100" : "pointer-events-none opacity-0",
        )}
        onClick={onClose}
        aria-hidden
      />

      <aside
        aria-label={t("agent.sidebar.navLabel")}
        className={cn(
          "fixed inset-y-0 start-0 z-50 flex h-screen w-full flex-col overflow-hidden border-e border-slate-200/70 bg-white shadow-elevated transition-transform duration-300 ease-snappy dark:border-slate-800/70 dark:bg-slate-950 sm:w-72 min-[1440px]:sticky min-[1440px]:top-0 min-[1440px]:w-full min-[1440px]:translate-x-0 min-[1440px]:shadow-none",
          open ? "translate-x-0" : slideClosed,
        )}
      >
        {/* Header */}
        <div className="flex h-16 items-center justify-between border-b border-slate-200/70 px-5 dark:border-slate-800/70">
          <div className="flex items-center gap-2.5">
            <Logo />
          </div>
          <button
            type="button"
            onClick={onClose}
            aria-label={t("agent.sidebar.closeMenu")}
            className="inline-flex h-9 w-9 items-center justify-center rounded-full border border-slate-200 text-slate-600 dark:border-slate-700 dark:text-slate-300 min-[1440px]:hidden"
          >
            <X className="icon-md" />
          </button>
        </div>

        {/* Nav */}
        <nav className="flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto p-4">
          {NAV_GROUPS.flatMap((group) => group.items).map((item) => {
            const active =
              item.href === "/agent/dashboard"
                ? pathname === "/agent/dashboard"
                : pathname.startsWith(item.href);
            const Icon = item.icon;
            return (
              <Link
                key={item.href}
                href={item.href}
                aria-current={active ? "page" : undefined}
                className={cn(
                  "group flex items-center gap-3 rounded-2xl px-3.5 py-3.5 text-[length:var(--text-sm-fixed)] font-medium transition-all duration-200",
                  active
                    ? "bg-brand-50 text-brand-700 shadow-soft dark:bg-brand-500/15 dark:text-brand-300"
                    : "text-slate-600 hover:bg-slate-100 hover:text-slate-900 dark:text-slate-300 dark:hover:bg-slate-800/60 dark:hover:text-white",
                )}
              >
                <Icon
                  className={cn(
                    "h-[18px] w-[18px] shrink-0 transition-transform duration-200 group-hover:scale-110",
                    active ? "text-brand-600 dark:text-brand-300" : "text-slate-400",
                  )}
                />
                <span className="flex-1">{t(item.key)}</span>
              </Link>
            );
          })}
        </nav>

      </aside>
    </>
  );
}
