import { Nav, Navbar } from 'react-bootstrap';
import { Icon } from './Icon';
import { useNavigate, useLocation, Link } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import { routes } from '../../AppRoutes';
import { useAuth } from '../../auth/AuthProvider';
import { useState, useEffect } from 'react';
import { getNotifications, getReadNotifications } from '../../api/Notifications';

// Sidebar component
function Sidebar({
  toggleSidebar,
  isSidebarOpen,
  height,
}: {
  toggleSidebar: () => void;
  isSidebarOpen: boolean;
  height: string;
}) {
  const navigate = useNavigate();
  const location = useLocation();

  const handleSelect = (selectedKey: string | null) => {
    if (selectedKey) navigate(selectedKey);
  };

  const { user } = useAuth();

  const [unreadCount, setUnreadCount] = useState<number>(0);

  const getAndSetNotifications = async () => {
    let notifs;
    if (user?.team_id) {
      notifs = await getNotifications(user.team_id);
    } else {
      notifs = await getNotifications(undefined, true); // getting as instructor
    }

    const readResult = await getReadNotifications(user?.user_id as number);

    const unreadCount = notifs.filter(
      (notification) =>
        !readResult.some(
          (read) => read.notification_id === notification.notification_id
        )
    ).length;
    setUnreadCount(unreadCount);
  };

  useEffect(() => {
    if (user) {
      getAndSetNotifications();
    }
  }, [user]);

  return (
    <Navbar.Collapse
      id='navbar-nav'
      in={isSidebarOpen}
      className='bg-light border-end'
      dimension='width'
      style={{
        minHeight: height,
      }}
    >
      <Nav
        variant='pills'
        activeKey={location.pathname}
        className='d-block p-3'
        onSelect={handleSelect}
        // https://getbootstrap.com/docs/5.3/components/collapse/#horizontal
        style={{ width: '15rem' }}
      >
        {routes.map(
          (route) =>
            user &&
            route.sidebar &&
            route.allowedUserTypes.includes(user.type) && (
              <Nav.Item key={route.path} className='my-1'>
                <Nav.Link
                  as={Link}
                  to={route.path}
                  onClick={toggleSidebar}
                  active={location.pathname.startsWith(route.path)}
                >
                  <div className='d-flex justify-content-start align-items-center'>
                    <div className='me-3 px-1 d-flex align-items-top'>
                      <Icon
                        // @ts-ignore
                        iconName={route.icon}
                        size={24}
                        className='font-bold'
                      ></Icon>
                    </div>
                    {route.name}
                    {route.name == 'Notifications' && unreadCount > 0 && (
                      <span className='ms-2 badge rounded-pill bg-danger'>
                        {unreadCount}
                      </span>
                    )}
                  </div>
                </Nav.Link>
              </Nav.Item>
            )
        )}
      </Nav>
    </Navbar.Collapse>
  );
}

export default Sidebar;
