'use client';

import { memo, useMemo } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Link, usePathname } from '@/i18n/navigation';
import {
  LayoutDashboard,
  Users,
  Calendar,
  UserCog,
  FlaskConical,
  FileText,
  CreditCard,
  Package,
  ListTodo,
  X,
} from 'lucide-react';
import type { OrgTypeName } from '@/components/shared/permissions';
import { useAuth } from '@/lib/hooks/useAuth';
import { usePendingConnectionsCount } from '@/lib/hooks/usePendingConnectionsCount';
import { useTabBadgeCounts } from '@/lib/hooks/useTabBadgeCounts';
import { badgeCountForPath } from '@/lib/tabBadgeUtils';
import { NavBadgePill } from '@/components/ui/shared/NavBadgePill';
import { BrandLockup } from '@/components/ui/shared/BrandLockup';
import {
  canViewAppointmentsTab,
  canViewCases,
  canViewTasks,
  canViewTab,
} from '@/components/shared/permissions';
import { isHiddenTabPath } from '@/components/shared/hidden-tabs';
import {
  counterpartOrganizationType,
  organizationTypeIcon,
} from '@/components/shared/organizationTypeIcon';
import { isRtlLocale } from '@/i18n/routing';

type MenuItem = {
  name: string;
  path: string;
  icon: typeof LayoutDashboard;
  read: string;
  orgTypes: OrgTypeName[];
};

type SidebarProps = {
  mobileOpen?: boolean;
  onClose?: () => void;
};

function Sidebar({ mobileOpen = false, onClose }: SidebarProps) {
  const locale = useLocale();
  const rtl = isRtlLocale(locale);
  const t = useTranslations('nav');
  const tCommon = useTranslations('common');
  const pathname = usePathname();
  const { currentOrganization } = useAuth();
  const pendingConnectionsCount = usePendingConnectionsCount();
  const tabBadgeCounts = useTabBadgeCounts();
  const orgType = currentOrganization?.type;

  const menu = useMemo((): MenuItem[] => {
    const items: MenuItem[] = [
      { name: t('dashboard'), path: '/today', icon: LayoutDashboard, read: 'TAB_TODAY_READ', orgTypes: ['CLINIC', 'LAB'] },
      { name: t('staff'), path: '/staff', icon: UserCog, read: 'TAB_STAFF_READ', orgTypes: ['CLINIC', 'LAB'] },
      {
        name: orgType === 'LAB' ? t('clinics') : t('labs'),
        path: '/organizations',
        icon: organizationTypeIcon(counterpartOrganizationType(orgType)),
        read: 'TAB_ORGANIZATIONS_READ',
        orgTypes: ['CLINIC', 'LAB'],
      },
      { name: t('patients'), path: '/patients', icon: Users, read: 'TAB_PATIENTS_READ', orgTypes: ['CLINIC'] },
      { name: t('cases'), path: '/cases', icon: Package, read: 'TAB_CASES_READ', orgTypes: ['LAB'] },
      { name: t('tasks'), path: '/tasks', icon: ListTodo, read: 'TAB_TASKS_READ', orgTypes: ['LAB'] },
      { name: t('appointment'), path: '/appointments', icon: Calendar, read: 'TAB_APPOINTMENTS_READ', orgTypes: ['CLINIC'] },
      { name: t('treatment'), path: '/treatment', icon: FlaskConical, read: 'TAB_TREATMENT_READ', orgTypes: ['CLINIC'] },
      { name: t('billing'), path: '/billing', icon: CreditCard, read: 'TAB_BILLING_READ', orgTypes: ['CLINIC', 'LAB'] },
      { name: t('reports'), path: '/reports', icon: FileText, read: 'TAB_REPORTS_READ', orgTypes: ['CLINIC', 'LAB'] },
    ];
    return items;
  }, [orgType, t]);

  const visibleMenu = useMemo(
    () =>
      menu.filter((item) => {
        if (isHiddenTabPath(item.path)) {
          return false;
        }
        if (!orgType || !item.orgTypes.includes(orgType)) {
          return false;
        }
        if (item.path === '/appointments') {
          return canViewAppointmentsTab(currentOrganization);
        }
        if (item.path === '/cases') {
          return canViewCases(currentOrganization);
        }
        if (item.path === '/tasks') {
          return canViewTasks(currentOrganization);
        }
        return canViewTab(currentOrganization, item.read);
      }),
    [currentOrganization, menu, orgType],
  );

  return (
    <aside
      className={`app-sidebar fixed inset-y-0 left-0 z-50 w-56 min-w-56 shrink-0 bg-background-secondary/95 border-r border-border text-text-primary flex flex-col backdrop-blur-sm transition-transform duration-200 ease-out lg:relative lg:translate-x-0 lg:z-auto ${
        mobileOpen ? 'translate-x-0' : rtl ? 'translate-x-full lg:translate-x-0' : '-translate-x-full lg:translate-x-0'
      }`}
    >
      <div className="h-[71px] flex flex-col shrink-0">
        <div className="flex-1 min-h-0 px-4 flex items-center justify-between gap-2">
          <h1 className="flex min-w-0 items-center leading-none">
            <BrandLockup className="text-2xl text-text-primary" />
          </h1>
          {onClose ? (
            <button
              type="button"
              className="lg:hidden inline-flex items-center justify-center h-9 w-9 rounded-[var(--radius-md)] border border-border/70 text-text-primary hover:bg-background-card/80 shrink-0"
              onClick={onClose}
              aria-label={tCommon('closeMenu')}
            >
              <X className="h-5 w-5 icon-flat" />
            </button>
          ) : null}
        </div>
        <div className="mx-4 border-b border-border/70" />
      </div>

      <nav className="flex flex-col gap-2 p-4">
        {visibleMenu.map((item) => {
          const Icon = item.icon;
          const isActive = pathname === item.path;
          const showPendingBadge =
            item.path === '/organizations' && pendingConnectionsCount > 0;
          const tabBadgeCount = badgeCountForPath(tabBadgeCounts, item.path);

          return (
            <Link
              key={item.path}
              href={item.path}
              prefetch
              onClick={onClose}
              className={`flex items-center gap-3 px-3 py-2.5 rounded-[var(--radius-sm)] border transition-colors ${
                isActive
                  ? 'bg-primary-soft border-primary/60 text-text-primary'
                  : 'border-border/50 text-text-secondary hover:bg-background-card/70 hover:text-text-primary hover:border-border'
              }`}
            >
              <Icon className="w-[18px] h-[18px] icon-flat" />
              <span className="text-sm flex-1">{item.name}</span>
              {showPendingBadge ? (
                <NavBadgePill
                  count={pendingConnectionsCount}
                  ariaLabel={`${pendingConnectionsCount} pending connection requests`}
                />
              ) : null}
              <NavBadgePill count={tabBadgeCount} ariaLabel={`${tabBadgeCount} unread updates`} />
            </Link>
          );
        })}
      </nav>
    </aside>
  );
}

export default memo(Sidebar);
