import { useTranslation } from 'react-i18next';
import { NavLink } from 'react-router-dom';

import { useAuth } from '../context/AuthContext';
import { useConversationsContext } from '../context/ConversationsContext';
import { useFriendshipsContext } from '../context/FriendshipsContext';
import { CallBar } from './CallUI';
import {
  ChatBubbleIcon,
  GearIcon,
  LogoLockup,
  ShieldIcon,
  SignOutIcon,
  UsersIcon,
} from './icons';
import { UserBar } from './UserBar';

interface NavItem {
  to: string;
  labelKey: string;
  icon: (props: React.SVGProps<SVGSVGElement>) => React.JSX.Element;
}

const BASE_NAV_ITEMS: NavItem[] = [
  { to: '/chats', labelKey: 'app:nav.chats', icon: ChatBubbleIcon },
  { to: '/friends', labelKey: 'app:nav.friends', icon: UsersIcon },
  { to: '/settings', labelKey: 'app:nav.settings', icon: GearIcon },
];
const ADMIN_NAV_ITEM: NavItem = {
  to: '/admin',
  labelKey: 'app:nav.admin',
  icon: ShieldIcon,
};

export function Sidebar() {
  const { t } = useTranslation(['app']);
  const { signOut, profile } = useAuth();
  const { incomingCount } = useFriendshipsContext();
  const { totalUnread } = useConversationsContext();

  const navItems = profile?.isAdmin ? [...BASE_NAV_ITEMS, ADMIN_NAV_ITEM] : BASE_NAV_ITEMS;

  return (
    <aside
      aria-label="Primary navigation"
      className="flex h-screen w-72 shrink-0 flex-col border-r border-white/5 bg-ink-900/70 backdrop-blur-xl"
    >
      <div className="flex items-center px-5 pb-3 pt-5">
        <LogoLockup tone="dark" className="h-8 w-auto" aria-label="Netralax" />
      </div>

      <nav className="mt-2 flex flex-col gap-0.5 px-3">
        {navItems.map((item) => {
          const badge =
            item.to === '/friends'
              ? incomingCount
              : item.to === '/chats'
                ? totalUnread
                : 0;
          const ariaLabel = badge > 0 ? `${t(item.labelKey)} (${badge})` : undefined;
          return (
            <NavLink
              key={item.to}
              to={item.to}
              aria-label={ariaLabel}
              className={({ isActive }) =>
                [
                  'group flex cursor-pointer items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition',
                  'focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-400/50',
                  isActive
                    ? 'bg-brand-500/15 text-white ring-1 ring-brand-400/30'
                    : 'text-neutral-400 hover:bg-white/5 hover:text-neutral-100',
                ].join(' ')
              }
            >
              <item.icon style={{ width: '18px', height: '18px' }} className="transition" />
              <span className="flex-1">{t(item.labelKey)}</span>
              {badge > 0 && <NavBadge count={badge} />}
            </NavLink>
          );
        })}
      </nav>

      <div className="flex-1" />

      <div className="border-t border-white/5 p-3">
        <CallBar />
        <UserBar />
        <button
          type="button"
          onClick={() => void signOut()}
          className="mt-2 flex w-full cursor-pointer items-center gap-2 rounded-lg px-3 py-2 text-xs font-medium text-neutral-400 transition hover:bg-rose-500/10 hover:text-rose-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-rose-400/40"
        >
          <SignOutIcon className="h-4 w-4" />
          <span>{t('app:sidebar.sign_out')}</span>
        </button>
      </div>
    </aside>
  );
}

function NavBadge({ count }: { count: number }) {
  const display = count > 99 ? '99+' : String(count);
  return (
    <span
      aria-hidden="true"
      className="inline-flex min-w-[20px] items-center justify-center rounded-full bg-rose-500 px-1.5 text-[10px] font-bold leading-tight text-white shadow-[0_0_0_2px_rgba(15,15,24,1)]"
    >
      {display}
    </span>
  );
}
