'use client';

import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { useTranslation } from '@/hooks/useTranslation';
import { useAuth as useAuthStore } from '@/lib/auth';
import { useAuth as useAuthContext } from '@/lib/auth';
import { Button } from '@/components/ui/button';
import { MEETING_ATTENDANCE_ROLES, MEETING_MANAGEMENT_ROLES } from '@/features/meeting-attendance/constants/roles';
import { BarChart3, Calendar, FileText, HelpCircle, Key, LogOut, Repeat, Settings2, Shield, Users } from 'lucide-react';

interface NavItem {
  label: string;
  href: string;
  icon: React.ComponentType<{ size?: number }>;
  roles?: string[];
  adminOnly?: boolean;
}

export function MeetingAttendanceNavbar() {
  const pathname = usePathname();
  const router = useRouter();
  const { t } = useTranslation();
  const { logout } = useAuthStore();
  const { user, hasAnyRole, isAdmin, roles } = useAuthContext();

  const navigation: NavItem[] = [
    { label: t.meetingAttendance.nav.dashboard, href: '/meetingattendance/dashboard', icon: BarChart3 },
    { label: t.meetingAttendance.nav.meetings, href: '/meetingattendance/meetings', icon: Calendar },
    { label: t.meetingAttendance.nav.series, href: '/meetingattendance/series', icon: Repeat, roles: MEETING_ATTENDANCE_ROLES },
    { label: t.meetingAttendance.nav.templates, href: '/meetingattendance/templates', icon: FileText, roles: MEETING_ATTENDANCE_ROLES },
    { label: t.meetingAttendance.nav.reports, href: '/meetingattendance/reports', icon: BarChart3, roles: MEETING_ATTENDANCE_ROLES },
    { label: t.meetingAttendance.nav.users, href: '/meetingattendance/users', icon: Users, roles: MEETING_MANAGEMENT_ROLES },
    { label: t.meetingAttendance.nav.auditLogs, href: '/meetingattendance/audit-logs', icon: Shield, roles: MEETING_MANAGEMENT_ROLES },
    { label: t.meetingAttendance.nav.outlookSync, href: '/meetingattendance/integrations/outlook', icon: Settings2, roles: MEETING_MANAGEMENT_ROLES },
    { label: t.meetingAttendance.nav.outlookBindings, href: '/meetingattendance/integrations/outlook/bindings-all', icon: Settings2, roles: MEETING_MANAGEMENT_ROLES, adminOnly: true },
    { label: t.meetingAttendance.nav.help, href: '/meetingattendance/help', icon: HelpCircle },
  ];

  const canAccess = (item: NavItem) => {
    if (item.adminOnly) {
      return isAdmin;
    }
    if (!item.roles || item.roles.length === 0) {
      return true;
    }
    if (isAdmin) {
      return true;
    }
    return hasAnyRole(item.roles);
  };

  const visibleNavigation = navigation.filter(canAccess);
  const activeHref = visibleNavigation
    .map((item) => item.href)
    .filter((href) => pathname === href || pathname.startsWith(`${href}/`))
    .sort((a, b) => b.length - a.length)[0];

  const handleLogout = () => {
    logout();
    router.push('/login');
  };

  const displayName = user?.displayName || user?.username || user?.email || '';
  const roleLabel = () => {
    if (isAdmin || roles.includes('Administrator') || roles.includes('ADMIN')) {
      return t.meetingAttendance.users.roles.admin;
    }
    if (roles.includes('MeetingManager') || roles.includes('MANAGER') || roles.includes('Manager')) {
      return t.meetingAttendance.users.roles.manager;
    }
    if (roles.includes('Leader') || roles.includes('LEADER')) {
      return t.meetingAttendance.users.roles.leader;
    }
    if (roles.includes('Employee') || roles.includes('EMPLOYEE')) {
      return t.meetingAttendance.users.roles.employee;
    }
    return t.meetingAttendance.nav.systemUser;
  };

  return (
    <nav className="bg-white shadow-sm border-b border-gray-100">
      <div className="w-full mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between items-center h-16">
          <div className="flex items-center min-w-0 flex-1">
            <div className="flex-shrink-0 flex items-center mr-6">
              <h1 className="text-lg lg:text-xl font-bold text-gray-900">{t.meetingAttendance.common.moduleName}</h1>
            </div>
            <div className="hidden md:flex md:space-x-4 lg:space-x-6 overflow-x-auto scrollbar-slim">
              {visibleNavigation.map((item) => {
                const Icon = item.icon;
                const isActive = activeHref === item.href;
                return (
                  <Link
                    key={item.href}
                    href={item.href}
                    className={`whitespace-nowrap py-2 px-2 border-b-2 font-medium text-sm inline-flex items-center gap-1.5 ${
                      isActive
                        ? 'border-blue-500 text-blue-600'
                        : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                    }`}
                  >
                    <Icon size={16} />
                    <span className="hidden lg:inline">{item.label}</span>
                  </Link>
                );
              })}
            </div>
          </div>
          <div className="flex items-center space-x-3 flex-shrink-0 ml-8">
            {displayName && (
              <div className="hidden md:flex flex-col items-end text-sm text-gray-700">
                <span className="font-medium">{displayName}</span>
                <span className="text-xs text-gray-500">{roleLabel()}</span>
              </div>
            )}
            <Link href="/meetingattendance/settings/change-password">
              <Button
                variant="ghost"
                size="sm"
                className="flex-shrink-0"
                title={t.meetingAttendance.nav.changePassword}
              >
                <Key size={16} className="mr-1.5" />
                <span className="hidden lg:inline">{t.meetingAttendance.nav.passwordShort}</span>
              </Button>
            </Link>
            <Button
              variant="outline"
              size="sm"
              onClick={handleLogout}
              className="flex-shrink-0"
            >
              <LogOut size={16} className="mr-1.5" />
              <span className="hidden sm:inline">{t.meetingAttendance.nav.signOut}</span>
            </Button>
          </div>
        </div>
      </div>
    </nav>
  );
}
