'use client';

import Link from 'next/link';
import { memo, useMemo } from 'react';
import { usePathname } from 'next/navigation';
import {
  LayoutDashboard,
  Users,
  Calendar,
  UserCog,
  FlaskConical,
  FileText,
  CreditCard,
} from 'lucide-react';
import { useAuth } from '@/lib/hooks/useAuth';
import { canViewTab } from '@/access';

const menu = [
  { name: 'Today', path: '/today', icon: LayoutDashboard, read: 'TAB_TODAY_READ' as const },
  { name: 'Patients', path: '/patients', icon: Users, read: 'TAB_PATIENTS_READ' as const },
  { name: 'Appointments', path: '/appointments', icon: Calendar, read: 'TAB_APPOINTMENTS_READ' as const },
  { name: 'Staff Management', path: '/staff', icon: UserCog, read: 'TAB_STAFF_READ' as const },
  { name: 'Lab Management', path: '/lab', icon: FlaskConical, read: 'TAB_LAB_READ' as const },
  { name: 'Billing', path: '/billing', icon: CreditCard, read: 'TAB_BILLING_READ' as const },
  { name: 'Reports', path: '/reports', icon: FileText, read: 'TAB_REPORTS_READ' as const },
];

function Sidebar() {
  const pathname = usePathname();
  const { currentOrganization } = useAuth();

  const visibleMenu = useMemo(
    () => menu.filter((item) => canViewTab(currentOrganization, item.read)),
    [currentOrganization],
  );

  return (
    <aside className="w-64 bg-background-secondary/90 border-r border-border text-text-primary flex flex-col">
      <div className="h-[71px] px-4 flex items-center">
        <h1 className="text-lg font-medium tracking-tight">DyoLink</h1>
      </div>
      <div className="mx-4 border-b border-border/70" />

      <nav className="flex flex-col gap-2 p-4">
        {visibleMenu.map((item) => {
          const Icon = item.icon;
          const isActive = pathname === item.path;

          return (
            <Link
              key={item.name}
              href={item.path}
              prefetch
              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">{item.name}</span>
            </Link>
          );
        })}
      </nav>
    </aside>
  );
}

export default memo(Sidebar);