"use client";

import Link from "next/link";
import { ChevronDown, ChevronRight, CircleHelp, KeyRound, LogOut } from "lucide-react";
import { useEffect, useMemo, useState } from "react";

import { AppLogo } from "@/components/branding/app-logo";
import { LogoutButton } from "@/components/auth/logout-button";
import { useLocale } from "@/components/providers/locale-provider";
import { getNavigationForRole, isNavGroup } from "@/config/navigation";
import type { SessionUser } from "@/lib/auth";
import { cn } from "@/lib/utils";

type SidebarProps = {
  pathname: string;
  user: SessionUser;
};

function matchesPath(currentPath: string, href: string) {
  return currentPath === href || currentPath.startsWith(`${href}/`);
}

function findActiveHref(currentPath: string, items: Array<{ href: string }>) {
  return items
    .filter((item) => matchesPath(currentPath, item.href))
    .sort((a, b) => b.href.length - a.href.length)[0]?.href;
}

export function Sidebar({ pathname, user }: SidebarProps) {
  const { dict } = useLocale();
  const navigation = useMemo(() => getNavigationForRole(user.role as never), [user.role]);
  const buildOpenGroups = () => {
    const grouped = navigation.filter(isNavGroup);
    return grouped.reduce<Record<string, boolean>>((acc, item) => {
      const isGroupActive = Boolean(findActiveHref(pathname, item.children));
      acc[item.key] = isGroupActive;
      return acc;
    }, {});
  };

  const [openGroups, setOpenGroups] = useState<Record<string, boolean>>(buildOpenGroups);

  useEffect(() => {
    setOpenGroups((current) => {
      const next = { ...current };
      navigation.filter(isNavGroup).forEach((item) => {
        const isGroupActive = Boolean(findActiveHref(pathname, item.children));
        if (isGroupActive) {
          next[item.key] = true;
        }
      });
      return next;
    });
  }, [pathname, navigation]);

  return (
    <aside className="hidden h-screen w-64 shrink-0 border-r border-line/70 bg-slate-50 xl:fixed xl:left-0 xl:top-0 xl:block">
      <div className="flex h-full min-h-0 flex-col py-4">
        <div className="mb-8 flex shrink-0 items-center gap-3 px-6">
          <AppLogo size={48} className="h-12 w-12 rounded-lg object-contain" priority />
          <div>
            <p className="whitespace-nowrap text-[14px] font-black leading-none text-moss">
              AbelBirdnest Stock
            </p>
            <p className="mt-1 text-[11px] font-medium text-slate-500">
              {user.role} · {user.name}
            </p>
          </div>
        </div>

        <div className="min-h-0 flex-1 overflow-y-auto px-3">
          <nav className="space-y-1 pr-1">
            {navigation.map((item) => {
              if (isNavGroup(item)) {
                const activeChildHref = findActiveHref(pathname, item.children);
                const isGroupActive = Boolean(activeChildHref);
                const isOpen = openGroups[item.key] ?? isGroupActive;

                return (
                  <div key={item.key} className="rounded-lg">
                    <button
                      type="button"
                      onClick={() =>
                        setOpenGroups((current) => ({
                          ...current,
                          [item.key]: !isOpen
                        }))
                      }
                      className={cn(
                        "flex w-full items-center gap-3 rounded px-3 py-2 text-left text-[13px] font-medium transition-all duration-150",
                        isGroupActive
                          ? "bg-white text-moss shadow-panel"
                          : "text-slate-500 hover:bg-slate-100 hover:text-moss"
                      )}
                    >
                      <item.icon className="h-[18px] w-[18px]" />
                      <span>
                        {dict.navigationGroups?.[
                          item.key as keyof typeof dict.navigationGroups
                        ] ?? item.label}
                      </span>
                      <ChevronDown
                        className={cn(
                          "ml-auto h-4 w-4 transition-transform",
                          isOpen ? "rotate-180" : ""
                        )}
                      />
                    </button>
                    {isOpen ? (
                      <div className="mt-1 space-y-1 pl-3">
                        {item.children.map((child) => {
                          const isActive = activeChildHref === child.href;

                          return (
                            <Link
                              key={child.href}
                              href={child.href}
                              className={cn(
                                "group flex items-center gap-3 rounded px-3 py-2 text-[13px] font-medium transition-all duration-150 active:scale-[0.98]",
                                isActive
                                  ? "border-r-4 border-moss bg-white text-moss shadow-panel"
                                  : "text-slate-500 hover:bg-slate-100 hover:text-moss"
                              )}
                            >
                              <child.icon className="h-[16px] w-[16px]" />
                              <span>
                                {dict.navigation[child.href as keyof typeof dict.navigation] ??
                                  child.label}
                              </span>
                              <ChevronRight className="ml-auto h-4 w-4 opacity-0 transition group-hover:opacity-40" />
                            </Link>
                          );
                        })}
                      </div>
                    ) : null}
                  </div>
                );
              }

              const isActive =
                matchesPath(pathname, item.href);

              return (
                <Link
                  key={item.href}
                  href={item.href}
                  className={cn(
                    "group flex items-center gap-3 rounded px-3 py-2 text-[13px] font-medium transition-all duration-150 active:scale-[0.98]",
                    isActive
                      ? "border-r-4 border-moss bg-white text-moss shadow-panel"
                      : "text-slate-500 hover:bg-slate-100 hover:text-moss"
                  )}
                >
                  <item.icon className="h-[18px] w-[18px]" />
                  <span>
                    {dict.navigation[item.href as keyof typeof dict.navigation] ?? item.label}
                  </span>
                  <ChevronRight className="ml-auto h-4 w-4 opacity-0 transition group-hover:opacity-40" />
                </Link>
              );
            })}
          </nav>
        </div>

        <div className="mt-4 shrink-0 px-3">
          <div className="space-y-1 border-t border-line/70 pt-4">
            <Link
              href="/change-password"
              className="flex items-center gap-3 rounded px-3 py-2 text-[13px] font-medium text-slate-500 transition hover:bg-slate-100 hover:text-moss"
            >
              <KeyRound className="h-[16px] w-[16px]" />
              <span>{dict.common.changePassword}</span>
            </Link>
            <Link
              href="/help"
              className="flex items-center gap-3 rounded px-3 py-2 text-[13px] font-medium text-slate-500 transition hover:bg-slate-100 hover:text-moss"
            >
              <CircleHelp className="h-[16px] w-[16px]" />
              <span>{dict.common.help}</span>
            </Link>
            <LogoutButton
              className="flex w-full items-center gap-3 rounded px-3 py-2 text-left text-[13px] font-medium text-red-600 transition hover:bg-red-50"
              label={dict.common.logout}
              icon={<LogOut className="h-[16px] w-[16px]" />}
            />
          </div>
        </div>
      </div>
    </aside>
  );
}
