'use client';

import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import './header.css';
import { Avatar, Button, Card, Center, FileButton, Grid, Group, Menu, Text, UnstyledButton } from '@mantine/core';
import Cookies from 'js-cookie';
import { useEffect, useState } from 'react';
import { logout, refresh, refreshLoggedIn } from '@/api/auth';
import { useToggle } from '@mantine/hooks';
import { HeaderModal } from './HeaderModal';
import { HeaderItem, headerItems } from './headerItems';
import { userState } from '@/state/auth';
import { useRecoilState } from 'recoil';
import { getPicture, setPicture } from '@/api/users';
import { BsChevronDown } from 'react-icons/bs';

export default function Header() {
  const pathName = usePathname();
  const [modalType, toggle] = useToggle([undefined, 'login', 'register', 'reset']);
  const [headers] = useState<HeaderItem[]>(headerItems);
  const [user, setUser] = useRecoilState(userState);
  const [refreshId, setRefreshId] = useState<NodeJS.Timeout | undefined>(undefined);
  const [profilePicture, setProfilePicture] = useState<File | null>(null);
  const router = useRouter();

  useEffect(() => {
    if (!user || !Cookies.get('logged_in')) {
      refresh().then((response) => {
        if (response) {
          setRefreshId(refreshLoggedIn());
          setUser(response.user);
          if (response.user.profile_picture) {
            getPicture().then((response) => {
              if (response) {
                setProfilePicture(response as File);
              }
            });
          }
        }
      });
    }
  }, [user]);

  return (
    <>
      <nav className='navbar'>
        <div className='left'>
          <Link href={'/'} className='title'>
            Siren
          </Link>
          <div className='header-items'>
            {headers.map((item) => {
              const menuItems = item.links?.map((subItem) => (
                <Menu.Item
                  color={pathName == subItem.link ? 'blue' : undefined}
                  onClick={() => router.push(subItem.link ?? '#')}
                  key={subItem.label}
                >
                  {subItem.label}
                </Menu.Item>
              ));
              if (menuItems) {
                return (
                  <Menu trigger='hover' transitionProps={{ exitDuration: 0 }} withinPortal key={item.label}>
                    <Menu.Target>
                      <Link className={`header-item ${pathName == item.link && 'active'}`} href={item.link ?? '#'}>
                        <Center>
                          {item.label}
                          <BsChevronDown />
                        </Center>
                      </Link>
                    </Menu.Target>
                    <Menu.Dropdown>{menuItems}</Menu.Dropdown>
                  </Menu>
                );
              }
              return (
                <Link
                  className={`header-item ${pathName == item.link && 'active'}`}
                  href={item.link ?? '#'}
                  key={item.label}
                >
                  {item.label}
                </Link>
              );
            })}
          </div>
        </div>
        <div className='user-section'>
          {user ? (
            <Menu shadow='md' width={200} openDelay={100} closeDelay={400}>
              <Menu.Target>
                <UnstyledButton className='user user-button'>
                  <Group>
                    <Avatar src={profilePicture ? URL.createObjectURL(profilePicture) : undefined} />
                    <div style={{ flex: 1 }}>
                      <Text size='sm' fw={500}>
                        {user.first_name} {user.last_name}
                      </Text>
                      <Text c='dimmed' size='xs' style={{ textTransform: 'uppercase' }}>
                        {user.role}
                      </Text>
                    </div>
                  </Group>
                </UnstyledButton>
              </Menu.Target>
              <Menu.Dropdown p={0}>
                <Card>
                  <Card.Section h={140} style={{ backgroundColor: '#4481e3' }} />
                  <FileButton
                    onChange={(payload) => {
                      if (payload) {
                        setPicture(payload).then((response) => {
                          if (response) {
                            setProfilePicture(payload);
                          }
                        });
                      }
                    }}
                    accept='image/png,image/jpeg,image/jpg'
                    multiple={false}
                  >
                    {(props) => (
                      <Avatar
                        {...props}
                        component='button'
                        size={80}
                        radius={80}
                        mx={'auto'}
                        mt={-30}
                        style={{ cursor: 'pointer' }}
                        bg={profilePicture ? 'transparent' : 'white'}
                        src={profilePicture ? URL.createObjectURL(profilePicture) : undefined}
                      />
                    )}
                  </FileButton>
                  <Text ta='center' fz='lg' fw={500} mt='sm'>
                    {user.first_name} {user.last_name}
                  </Text>
                  <Text ta='center' fz='sm' c='dimmed' style={{ textTransform: 'uppercase' }}>
                    {user.role}
                  </Text>
                  <Grid mt='xl'>
                    <Grid.Col span={6}>
                      <Link href='/profile'>
                        <Button fullWidth radius='md' size='xs' variant='default'>
                          Profile
                        </Button>
                      </Link>
                    </Grid.Col>
                    <Grid.Col span={6}>
                      <Button
                        fullWidth
                        radius='md'
                        size='xs'
                        variant='default'
                        onClick={async () => {
                          await logout();
                          Cookies.remove('logged_in');
                          setUser(undefined);
                          setProfilePicture(null);
                          if (refreshId) {
                            clearInterval(refreshId);
                          }
                        }}
                      >
                        Logout
                      </Button>
                    </Grid.Col>
                    {user.role == 'admin' && (
                      <Grid.Col span={12}>
                        <Link href='/admin'>
                          <Button fullWidth radius='md' size='xs' variant='default'>
                            Administration
                          </Button>
                        </Link>
                      </Grid.Col>
                    )}
                  </Grid>
                </Card>
              </Menu.Dropdown>
            </Menu>
          ) : (
            <Group className='user'>
              <Button onClick={() => toggle('login')}>Login</Button>
              <Button variant='outline' onClick={() => toggle('register')}>
                Sign up
              </Button>
            </Group>
          )}
        </div>
      </nav>
      <HeaderModal
        type={modalType}
        toggle={toggle}
        setUser={(u) => {
          setUser(u);
          if (u.profile_picture) {
            getPicture().then((response) => {
              if (response) {
                setProfilePicture(response as File);
              }
            });
          }
        }}
        setRefreshId={setRefreshId}
      />
    </>
  );
}
