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

import { ROUTES } from '../../constants/paths';
import { useMutation } from 'react-query';

import { EVENT_NAMES } from '../../constants/define';
import { useMyToast } from '../../hooks';

const ChangePasswordScheme = Yup.object().shape({
  password: Yup.string().required('Required'),
  confirmPassword: Yup.string()
    .required('Required')
    .oneOf([Yup.ref('password'), null], 'Passwords must match'),
});

function ChangePassword() {
  const location = useLocation(),
    queryParams = new URLSearchParams(location.search),
    token = queryParams.get('token'),
    email = queryParams.get('email'),
    toast = useMyToast(),
    navigate = useNavigate();

  console.log({ token, email });

  const { mutate, isLoading } = useMutation({
    mutationFn: async (values) => {
      console.log({ token, email });
      return await window.grpcAPIs[EVENT_NAMES.AUTHENTICATION.CHANGE_PASSWORD]({
        token,
        email,
        newPassword: values.password,
      });
    },
    onSuccess: (data) => {
      toast({
        title: 'Success',
        description: data.message,
        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={ChangePasswordScheme}
            onSubmit={mutate}
          >
            {({ errors, touched }) => (
              <Form>
                <FormControl isRequired isInvalid={errors.password && touched.password} mb="4">
                  <FormLabel htmlFor="password">Password</FormLabel>
                  <Field as={Input} name="password" type="password" id="password" placeholder="Enter your password" />
                  <FormErrorMessage>{errors.pasword}</FormErrorMessage>
                </FormControl>
                <FormControl isRequired isInvalid={errors.confirmPassword && touched.confirmPassword} mb="4">
                  <FormLabel htmlFor="confirmPassword">Confirm Password</FormLabel>
                  <Field
                    as={Input}
                    name="confirmPassword"
                    type="password"
                    id="confirmPassword"
                    placeholder="Enter your confirm password"
                  />
                  <FormErrorMessage>{errors.confirmPassword}</FormErrorMessage>
                </FormControl>
                <Stack spacing={5}>
                  <Button
                    type="submit"
                    bg="#81a540"
                    color={'white'}
                    _hover={{
                      bg: 'green.500',
                    }}
                    isLoading={isLoading}
                  >
                    Change Password
                  </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>
  );
}

ChangePassword.propTypes = {};

export default ChangePassword;
