import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import axios from 'axios';
import Logo from '../common/Logo';
import HeaderLink from './HeaderLink';
import Committee from '../icons/Committee';
import Help from '../icons/Help';
import Ranking from '../icons/Ranking';
import Team from '../icons/Team';
import Menu from '../icons/Menu';
import CloseMenu from '../icons/CloseMenu';
import { CustomResponse } from '../../model/common';

interface HeaderProps {
  splash?: boolean;
  onDark?: boolean;
  auth?: boolean;
}

const Header: React.FC<HeaderProps> = ({ splash, onDark, auth }) => {
  const [isOpen, setOpen] = useState<boolean>(false);
  const [notifications, setNotifications] = useState<number>(0);

  useEffect(() => {
    if (!auth) {
      try {
        axios
          .post<CustomResponse<number>>('/api/getNotificationsCount')
          .then(({ data: { ok, data: notificationsCount } }) => {
            if (ok) {
              setNotifications(notificationsCount);
            }
          });
      } catch (err) {
        console.log('Error loading notifications ', err);
      }
    }
  });

  return (
    <header className={`${onDark ? 'onDark' : ''}${isOpen ? ' open' : ''}`}>
      {!splash ? (
        <Link href="/">
          <a title="Home" href="/">
            <Logo white={onDark} />
          </a>
        </Link>
      ) : null}
      <button
        className="menuClick"
        type="button"
        onClick={(): void => setOpen(!isOpen)}
      >
        {isOpen ? <CloseMenu /> : <Menu />}
      </button>
      <div className={`linksHolder ${isOpen ? 'open' : ''}`}>
        {!auth ? (
          <>
            <HeaderLink
              title="Ranking"
              route="/ranking"
              icon={<Ranking size="medium" />}
              onDark={onDark}
            />
            <HeaderLink
              title="Perfil"
              route="/profile"
              icon={<Team size="medium" />}
              onDark={onDark}
              notification={notifications}
            />
          </>
        ) : null}
        <HeaderLink
          className=" committeeLink"
          title="Comité Dialípico"
          route="/committee"
          icon={<Committee size="medium" />}
          onDark={onDark}
        />
        <HeaderLink
          title="Ayuda"
          route="/help"
          icon={<Help size="medium" />}
          onDark={onDark}
        />
      </div>
      <span className="veil" />
    </header>
  );
};

export default Header;
