import React, { useEffect, useState } from 'react';
import {
  Box,
  FormStatusMessage,
  MainButton,
  Modal,
  ModalHeader,
  Input,
  AttentionBanner,
} from '@nova-hf/ui';
import {
  useSendNumberVerificationChallengeMutation,
  useVerifyNumberVerificationChallengeMutation,
} from 'typings/graphql';
import { useRouter } from 'next/router';
import { ModalProps } from '@nova-hf/ui/umd/ts/src/modal/Modal';
import { useTranslation } from 'utils/i18n';

type ConfirmationModalProps = {
  phoneNumber?: string;
  challengeId?: string;
  onClose?: () => void;
} & Pick<ModalProps, 'isVisible' | 'onVisibilityChange'>;

export const ConfirmationModal = ({
  isVisible,
  phoneNumber,
  challengeId,
  onClose,
  onVisibilityChange,
}: ConfirmationModalProps) => {
  const { t } = useTranslation('containers');
  const [codeValue, setCodeValue] = useState('');
  const [errorMessage, setErrorMessage] = useState('');
  const [isCodeValid, setIsCodeValid] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [sendNumberVerificationChallenge, { loading: newChallengeLoading }] =
    useSendNumberVerificationChallengeMutation();
  const [verifyCode, { loading: verifyNumberLoading }] =
    useVerifyNumberVerificationChallengeMutation();

  const { query } = useRouter();
  const customerId: string = (query.customerId as string) ?? '';

  useEffect(() => {
    if (newChallengeLoading || verifyNumberLoading) {
      setIsLoading(true);
    } else setIsLoading(false);
  }, [newChallengeLoading, verifyNumberLoading]);

  useEffect(() => {
    setIsCodeValid(codeValue.length === 6);
  }, [codeValue]);

  const handleSendNewVerification = async () => {
    if (phoneNumber) {
      try {
        const { data } = await sendNumberVerificationChallenge({
          variables: {
            input: {
              customerId: customerId,
              primaryNumber: phoneNumber,
            },
          },
        });
        if (data?.sendNumberVerificationChallenge.NumberVerificationChallenge?.id) {
          setErrorMessage('');
          setCodeValue('');
        }
      } catch (error) {
        if (error instanceof Error) {
          setErrorMessage(error.message);
        }
      }
    }
  };

  const handleVerifyCode = async () => {
    if (challengeId) {
      try {
        const { data } = await verifyCode({
          variables: {
            input: {
              challengeId: challengeId,
              confirmationCode: codeValue,
            },
          },
        });
        if (data?.verifyNumberVerificationChallenge) {
          setErrorMessage('');
          setCodeValue('');
          onClose && onClose();
        }
      } catch (error) {
        if (error instanceof Error) {
          setErrorMessage(error.message);
        }
      }
    }
  };

  return (
    <Modal
      ariaLabel="Confirm phone number modal"
      isVisible={isVisible}
      onVisibilityChange={onVisibilityChange}
    >
      <Box width="100%" {...(isLoading && { style: { opacity: 0.5 } })}>
        <ModalHeader
          title={t('confirmationModal.modalTitle')}
          eyebrow={t('confirmationModal.modalEyebrow')}
          color="pink"
        />
        <Box marginTop={15} marginBottom={9}>
          <Input
            autoComplete="one-time-code"
            id="codeInput"
            name="codeInputField"
            label={t('confirmationModal.inputLabel')}
            value={codeValue}
            onChange={(e) => setCodeValue(e.target.value)}
            disabled={isLoading}
            {...(codeValue && { icon: 'checkBox' })}
          />
          {errorMessage && <FormStatusMessage status="error" message={errorMessage} />}
        </Box>
        <Box display="flex" flexDirection="row" gap={4} marginBottom={errorMessage ? 5 : 0}>
          <MainButton
            text={t('confirmationModal.resendCodeButton')}
            onClick={handleSendNewVerification}
            colorScheme="white"
            dottedShadow="none"
            isDisabled={isLoading}
            isLoading={newChallengeLoading}
          />
          <MainButton
            text={t('confirmationModal.confirmButton')}
            onClick={handleVerifyCode}
            colorScheme="pink"
            dottedShadow="none"
            isDisabled={isLoading || !isCodeValid}
            isLoading={verifyNumberLoading}
          />
        </Box>
      </Box>
      {errorMessage && (
        <Box position="absolute" left={0} right={0} bottom={0}>
          <AttentionBanner
            color="warning"
            icon="warning"
            strongText={t('confirmationModal.wrongCodeValue')}
            regularText={t('confirmationModal.tryAgain')}
          />
        </Box>
      )}
    </Modal>
  );
};
