import {
  Box,
  Button,
  FormControl,
  FormErrorMessage,
  FormLabel,
  Heading,
  Input,
  Stack,
  Text,
  useToast
} from '@chakra-ui/react';
import { useSupabaseClient } from '@supabase/auth-helpers-react';
import { nanoid } from 'nanoid';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';

import {
  checkPassword,
  checkPasswordAreEqual,
  checkPasswordLength
} from '../utils/checks';

export const ResetPassword = ({
  redirectAfterAction
}: {
  redirectAfterAction?: boolean;
}) => {
  const router = useRouter();
  const toast = useToast();
  const supabaseClient = useSupabaseClient();

  const [password, setPassword] = useState<string>();
  const [confirmPassword, setConfirmPassword] = useState<string>();

  const [autoGeneratedPassword, setAutoGeneratedPassword] = useState<string>();

  useEffect(() => {
    setAutoGeneratedPassword(nanoid(40));
  }, []);

  const handleResetPassword = async () => {
    supabaseClient.auth
      .updateUser({ password })
      .catch(error =>
        toast({
          title: 'Reset password failure',
          description: JSON.stringify(error),
          status: 'error',
          duration: 3000,
          isClosable: true
        })
      )
      .then(res => {
        if (typeof res == 'object' && res.error) {
          toast({
            title: 'Reset password failure',
            description: res.error.message,
            status: 'error',
            duration: 3000,
            isClosable: true
          });
        } else if (typeof res == 'object' && res.data?.user) {
          toast({
            title: 'Password successfully reset',
            status: 'success',
            duration: 3000,
            isClosable: true
          });
          if (redirectAfterAction) {
            router.push('/');
          }
        }
      });
  };

  return (
    <Stack spacing={8}>
      <Heading size="md">Reset your password</Heading>

      <FormControl isInvalid={!checkPasswordLength(password)}>
        <FormLabel>Password</FormLabel>
        <Input
          type="password"
          autoComplete="new-password"
          data-test-id="reset-password-input"
          onChange={e => setPassword(e.target.value)}
        />
        {!checkPasswordLength(password) ? (
          <FormErrorMessage>
            Password must be between 6 and 99 characters long.
          </FormErrorMessage>
        ) : null}
      </FormControl>

      <FormControl
        isInvalid={!checkPasswordAreEqual(password, confirmPassword)}
      >
        <FormLabel>Confirm password</FormLabel>
        <Input
          type="password"
          autoComplete="new-password"
          data-test-id="confirm-reset-password-input"
          onChange={e => setConfirmPassword(e.target.value)}
        />
        {!checkPasswordAreEqual(password, confirmPassword) ? (
          <FormErrorMessage>Password are different.</FormErrorMessage>
        ) : null}
      </FormControl>

      <Box fontSize={15}>
        <Text fontWeight={450}>
          {'Here is an auto-generated password that we can suggest:'}
        </Text>
        <Text>{autoGeneratedPassword}</Text>
      </Box>

      <Box>
        <Button
          data-test-id="reset-password-button"
          onClick={handleResetPassword}
          isDisabled={!checkPassword(password, confirmPassword)}
        >
          Reset password
        </Button>
      </Box>
    </Stack>
  );
};
