import {
  Flex,
  Box,
  FormControl,
  FormLabel,
  Input,
  Checkbox,
  Stack,
  Button,
  Text,
  useColorModeValue,
  FormErrorMessage,
  Alert,
  AlertIcon,
  AlertTitle,
} from '@chakra-ui/react';
import { Link as ReactRouterLink } from 'react-router-dom';
import { useState } from 'react';
import { Formik, Form, Field } from 'formik';
import * as Yup from 'yup';

import { useAuth } from '../../hooks';
import * as LocalStorage from '../../utilities/localStorage';

import { EVENT_NAMES } from '../../constants/define';
import { ROUTES } from '../../constants/paths';

const SigninSchema = Yup.object().shape({
  email: Yup.string().email('Invalid email').required('Required'),
  password: Yup.string().min(6, 'Too Short!').max(50, 'Too Long!').required('Required'),
});

export default function Login() {
  const [errorMessage, setErrorMessage] = useState(null);
  const [isLoading, setIsLoading] = useState();
  const [isRememberMe, setIsRememberMe] = useState(LocalStorage.get('isRememberMe'));
  const defaultEmail = LocalStorage.get('email');
  const defaulPassword = LocalStorage.get('password');

  const handleSubmit = async (values) => {
    try {
      const { email, password } = values;
   

      setIsLoading(true);
      const response = await window.grpcAPIs[EVENT_NAMES.AUTHENTICATION.LOGIN](email, password);
      setErrorMessage(null);
    } catch (error) {
      setErrorMessage(error?.message);
    } finally {
      setIsLoading(false);
    }
  };

  const handleIsCheckedRememberMe = () => {
    setIsRememberMe(!isRememberMe);
  };

  return (
    <Flex h="100%" align={'center'} justify={'center'} bg={useColorModeValue('gray.50', 'gray.800')}>
      <Stack spacing={8} mx={'auto'} width="lg" py={12} px={6}>
        <Box rounded={'lg'} bg={useColorModeValue('white', 'gray.700')} boxShadow={'lg'} p={8}>
          <Formik
            initialValues={{
              email: defaultEmail || '',
              password: defaulPassword || '',
            }}
            validationSchema={SigninSchema}
            onSubmit={handleSubmit}
          >
            {({ handleSubmit, errors, touched }) => (
              <Form onSubmit={handleSubmit}>
                <Stack spacing={4}>
                  <FormControl isInvalid={!!errors.email && touched.email}>
                    <FormLabel htmlFor="email">Email Address</FormLabel>
                    <Field as={Input} id="email" name="email" type="email" variant="filled" />
                    <FormErrorMessage>{errors.email}</FormErrorMessage>
                  </FormControl>
                  <FormControl isInvalid={!!errors.password && touched.password}>
                    <FormLabel htmlFor="password">Password</FormLabel>
                    <Field as={Input} id="password" name="password" type="password" variant="filled" />
                    <FormErrorMessage>{errors.password}</FormErrorMessage>
                  </FormControl>
                  <Alert display={errorMessage ? 'flex' : 'none'} status="error">
                    <AlertIcon />
                    <AlertTitle>{errorMessage}</AlertTitle>
                  </Alert>
                  <Stack spacing={10}>
                    <Stack direction={{ base: 'column', sm: 'row' }} align={'start'} justify={'space-between'}>
                      <Checkbox defaultChecked={isRememberMe} onChange={handleIsCheckedRememberMe}>
                        Remember me
                      </Checkbox>
                      <Text as={ReactRouterLink} to={ROUTES.FORGOT_PASSWORD.path} color="#81a540">
                        Forgot password?
                      </Text>
                    </Stack>
                    <Button
                      type="submit"
                      bg="#81a540"
                      color={'white'}
                      _hover={{
                        bg: 'green.500',
                      }}
                      isLoading={isLoading}
                    >
                      Sign In
                    </Button>
                  </Stack>
                </Stack>
              </Form>
            )}
          </Formik>
        </Box>
      </Stack>
    </Flex>
  );
}
