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

import { ROUTES } from '../../constants/paths';
import { EVENT_NAMES, STATUS_MESSAGES } from '../../constants/define';
import { useMyToast } from '../../hooks';

const ForgotPasswordSchema = Yup.object().shape({
  email: Yup.string().email('Invalid email').required('Required'),
});

function ForgotPassword() {
  const toast = useMyToast(),
    navigate = useNavigate();

  const { mutate, isLoading, isError, error } = useMutation({
    mutationFn: (values) => {
      return window.grpcAPIs[EVENT_NAMES.AUTHENTICATION.INITIATE_RESET_PASSWORD](values);
    },
    onSuccess: (data) => {
      toast({
        title: 'Success',
        description: STATUS_MESSAGES.SEND_MAIL_SUCCESS,
        status: 'success',
        duration: 5000,
        isClosable: true,
      });
      navigate(ROUTES.LOGIN.path);
    },
  });

  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: '',
            }}
            validationSchema={ForgotPasswordSchema}
            onSubmit={mutate}
          >
            {({ errors, touched }) => (
              <Form>
                <FormControl isInvalid={errors.email && touched.email} mb="4">
                  <FormLabel htmlFor="email">Email Address</FormLabel>
                  <Field as={Input} name="email" id="email" placeholder="Enter your email" />
                  <FormErrorMessage>{errors.email}</FormErrorMessage>
                </FormControl>
                {isError && (
                  <Alert status="error">
                    <AlertIcon />
                    <AlertTitle>{error?.message}</AlertTitle>
                  </Alert>
                )}
                <Stack spacing={5}>
                  <Button
                    type="submit"
                    bg="#81a540"
                    color={'white'}
                    _hover={{
                      bg: 'green.500',
                    }}
                    isLoading={isLoading}
                  >
                    Reset Reset Link to Email
                  </Button>
                  <Stack direction={{ base: 'column', sm: 'row' }} align={'start'} justify={'space-between'}>
                    <Text as={ReactRouterLink} to={ROUTES.LOGIN.path} color="#81a540">
                      Sign In?
                    </Text>
                  </Stack>
                </Stack>
              </Form>
            )}
          </Formik>
        </Box>
      </Stack>
    </Flex>
  );
}

export default ForgotPassword;
