'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import './topbar.css';
import {
  Anchor,
  Avatar,
  Button,
  Checkbox,
  Container,
  Group,
  Menu,
  Modal,
  Paper,
  PasswordInput,
  Text,
  TextInput,
  Title
} from '@mantine/core';
import Cookies from 'js-cookie';
import { useEffect, useState } from 'react';
import { useForm } from '@mantine/form';
import { login, logout, ping } from '@/api/users';

const headerItems = [
  {
    name: 'Races',
    link: '/races'
  },
  {
    name: 'Classes',
    link: '/classes'
  },
  {
    name: 'Feats',
    link: '/feats'
  },
  {
    name: 'Options & Features',
    link: '/options'
  },
  {
    name: 'Backgrounds',
    link: '/backgrounds'
  },
  {
    name: 'Items',
    link: '/items'
  },
  {
    name: 'Spells',
    link: '/spells'
  },
  {
    name: 'Management',
    link: '/management'
  }
];

export default function Topbar() {
  const pathName = usePathname();
  const [showLogin, setShowLogin] = useState(false);
  const [authenticated, setAuthenticated] = useState(false);
  // Check if the auth cookie is set
  // If it is, show the user avatar
  // If not, show the login button
  useEffect(() => {
    console.log('cookies', Cookies.get());
    if (Cookies.get('auth')) {
      setAuthenticated(true);
    }
  }, []);

  return (
    <>
      <nav className='navbar'>
        <div className='left'>
          <Link href={'/'} className='title'>
            Siren
          </Link>
          <div className='header-items'>
            {headerItems.map((item) => (
              <Link className={`header-item ${pathName == item.link && 'active'}`} href={item.link} key={item.name}>
                {item.name}
              </Link>
            ))}
          </div>
        </div>
        <div className='user'>
          <Menu shadow='md' width={200} trigger='hover' openDelay={100} closeDelay={400}>
            <Menu.Target>
              <Avatar style={{ cursor: 'pointer' }} />
            </Menu.Target>
            <Menu.Dropdown>
              {!authenticated && <Menu.Item onClick={() => setShowLogin(true)}>Login</Menu.Item>}
              {authenticated && (
                <Menu.Item
                  onClick={async () => {
                    const response = await logout();
                    if (response?.status == 200) {
                      Cookies.remove('auth');
                      setAuthenticated(false);
                    }
                  }}
                >
                  Logout
                </Menu.Item>
              )}
              <Menu.Item onClick={() => ping()}>Ping</Menu.Item>
            </Menu.Dropdown>
          </Menu>
        </div>
      </nav>
      <LoginModal showLogin={showLogin} setShowLogin={setShowLogin} setAuthenticated={setAuthenticated} />
    </>
  );
}

function LoginModal({
  showLogin,
  setShowLogin,
  setAuthenticated
}: {
  showLogin: boolean;
  setShowLogin: (show: boolean) => void;
  setAuthenticated: (authenticated: boolean) => void;
}) {
  const form = useForm({
    initialValues: {
      email: '',
      password: ''
    }
  });
  return (
    <Modal opened={showLogin} onClose={() => setShowLogin(false)} withCloseButton={false}>
      <Container>
        <Title ta='center'>Welcome back!</Title>
        <Text c='dimmed' size='sm' ta='center' mt={5}>
          Do not have an account yet?{' '}
          <Anchor size='sm' component='button'>
            Create account
          </Anchor>
        </Text>

        <Paper withBorder shadow='md' p={30} mt={30} radius='md'>
          <form
            onSubmit={form.onSubmit(async (values) => {
              const response = await login(values.email, values.password);
              if (response?.status == 200) {
                setShowLogin(false);
                setAuthenticated(true);
              }
            })}
          >
            <TextInput label='Email' placeholder='you@example.com' required {...form.getInputProps('email')} />
            <PasswordInput
              label='Password'
              placeholder='Your password'
              required
              mt='md'
              {...form.getInputProps('password')}
            />
            <Group justify='space-between' mt='lg'>
              <Checkbox label='Remember me' />
              <Anchor component='button' size='sm'>
                Forgot password?
              </Anchor>
            </Group>
            <Button type='submit' fullWidth mt='xl'>
              Sign in
            </Button>
          </form>
        </Paper>
      </Container>
    </Modal>
  );
}
