'use client';

import { AuthService } from '@/lib/auth-service';
import { useAuthStore } from '@/lib/auth-store';
import { useLanguage } from '@/lib/language-context';
import { cn } from '@/lib/utils';
import { BarChart3, Calendar, ClipboardList, FileText, LogOut, MessageSquareQuote, MessageSquareText, Newspaper, Pill, User, Users } from 'lucide-react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';

interface SidebarProps {
  open: boolean;
  onClose?: () => void;
}

export default function Sidebar({ open, onClose }: SidebarProps) {
  const { user } = useAuthStore();
  const { t } = useLanguage();
  const router = useRouter();
  const pathname = usePathname();

  const allMenuItems = [
    { iconKey: BarChart3, labelKey: 'navigation.dashboard', href: '/dashboard', roles: ['admin', 'doctor', 'staff', 'patient'] },
    { iconKey: Users, labelKey: 'patients.title', href: '/patients', roles: ['doctor', 'staff'] },
    { iconKey: Calendar, labelKey: 'appointments.title', href: '/appointments', roles: ['doctor', 'staff', 'patient'] },
    { iconKey: Users, labelKey: 'doctors.title', href: '/doctors', roles: ['admin'] },
    { iconKey: ClipboardList, labelKey: 'navigation.registrations', href: '/admin/registrations', roles: ['admin'] },
    { iconKey: Newspaper, labelKey: 'navigation.blogAdmin', href: '/admin/blog', roles: ['admin'] },
    { iconKey: FileText, labelKey: 'navigation.manualAdmin', href: '/admin/manual', roles: ['admin'] },
    { iconKey: MessageSquareQuote, labelKey: 'navigation.testimonialsAdmin', href: '/admin/testimonials', roles: ['admin'] },
    { iconKey: MessageSquareText, labelKey: 'navigation.supportFeedback', href: '/admin/support-feedback', roles: ['admin'] },
    { iconKey: Users, labelKey: 'navigation.team', href: '/admin/team', roles: ['doctor'] },
    { iconKey: MessageSquareQuote, labelKey: 'navigation.testimonials', href: '/dashboard/testimonials', roles: ['doctor', 'dentist'] },
    { iconKey: User, labelKey: 'profile.myProfile', href: '/profile', roles: ['admin', 'doctor', 'staff', 'patient'] },
    { iconKey: Pill, labelKey: 'subscription.title', href: '/subscription', roles: ['admin', 'doctor', 'staff', 'patient'] },
  ];

  const menuItems = allMenuItems.filter(item => {
    if (!user) return false;

    // Check role access
    const currentRole = user.userType || 'patient';
    if (!item.roles.includes(currentRole)) {
      return false;
    }

    // Special check for Subscription: Hide for secondary doctors (added by admin)
    if (item.href === '/subscription' && user.userType === 'doctor' && user.ownerId) {
      return false;
    }

    return true;
  });

  return (
    <aside
      className={cn(
        'bg-linear-to-b from-cyan-500 via-cyan-600 to-blue-600 text-white md:h-full h-[calc(100vh-6rem)] p-6 transition-all duration-300 shadow-lg fixed md:relative left-0 top-24 md:top-0 z-40 overflow-y-auto no-scrollbar',
        // Mobile: hide when closed, show when open
        'md:block',
        !open && 'hidden md:w-20',
        open && 'w-64 block md:w-64'
      )}
    >
      {/* <div className="flex items-center gap-3 mb-8">
        <div className="w-10 h-10 bg-white rounded-lg flex items-center justify-center shadow-md">
          <span className="font-bold text-cyan-600 text-lg">CP</span>
        </div>
        {open && <span className="font-bold text-xl">Medklinix</span>}
      </div> */}

      <nav className="space-y-3">
        {menuItems.map((item) => {
          const Icon = item.iconKey;
          const isActive = pathname === item.href || (item.href !== '/dashboard' && pathname?.startsWith(item.href));

          return (
            <Link
              key={item.href}
              href={item.href}
              onClick={() => {
                if (window.innerWidth < 768 && onClose) {
                  onClose();
                }
              }}
              className={cn(
                'flex min-w-0 items-center gap-3 px-4 py-3 rounded-xl transition-all duration-200 text-white hover:bg-white/20 hover:shadow-md group active:scale-95',
                isActive && 'bg-white/20 shadow-md',
                !open && 'justify-center px-3'
              )}
            >
              <Icon className={cn("h-5 w-5 shrink-0 text-white transition-transform duration-200", !isActive && "group-hover:scale-110")} />
              {open && <span className={cn("min-w-0 flex-1 truncate whitespace-nowrap text-sm font-semibold", isActive ? "font-bold" : "")}>{t(item.labelKey)}</span>}
            </Link>
          );
        })}
      </nav>

      <div className="mt-auto pt-6 border-t border-white/20">
        <button
          onClick={() => {
            AuthService.logout();
            router.push('/login');
          }}
          className={cn('flex min-w-0 items-center gap-3 px-4 py-3 w-full rounded-xl text-white hover:bg-white/20 hover:shadow-md transition-all duration-200 group active:scale-95', !open && 'justify-center px-3')}
        >
          <LogOut className="h-5 w-5 shrink-0 text-white group-hover:scale-110 transition-transform duration-200" />
          {open && <span className="min-w-0 flex-1 truncate whitespace-nowrap text-sm font-semibold">{t('navigation.logout')}</span>}
        </button>
      </div>
    </aside>
  );
}
