import { ImgElement } from '@axinom/mosaic-ui';
import React, { useEffect, useState } from 'react';
import MosaicBG from '../../resources/images/bg.svg';
import mosaicLogo from '../../resources/images/mosaic_logo.svg';
import { useIdentityService } from '../IdentityServiceProvider/IdentityServiceProvider';
import { BrandingOptions } from '../common/BrandingOptions';
import classes from './CompletePasswordReset.module.scss';

const DEFAULT_BG_IMAGE = MosaicBG;

export interface ForgotPasswordProps {
  brandingOptions?: BrandingOptions;
}
/**
 * Renders the CompletePasswordReset component
 */
export const CompletePasswordReset: React.FC<ForgotPasswordProps> = ({
  brandingOptions,
}) => {
  const { completePasswordReset, getWellKnownUrls } = useIdentityService();

  const [password, setPassword] = useState<string>('');
  const [confirmPassword, setConfirmPassword] = useState<string>('');
  const [axAuthManagementGraphQlEndpoint, setAxAuthManagementGraphQlEndpoint] =
    React.useState<string>();
  const [errorMessage, setErrorMessage] = useState<string>();
  const [isReset, setIsReset] = useState<boolean>(false);
  const [isSubmitted, setIsSubmitted] = useState<boolean>(false);

  const background = brandingOptions?.background ?? DEFAULT_BG_IMAGE;

  const backgroundStyles = {
    background: background?.includes('/') ? `url(${background})` : background,
    backgroundSize: `cover`,
    backgroundRepeat: `no-repeat`,
  };

  useEffect(() => {
    (async () => {
      const wellKnownUrls = await getWellKnownUrls();
      setAxAuthManagementGraphQlEndpoint(
        wellKnownUrls.axAuthManagementGraphQlEndpoint,
      );
    })();
  }, []);

  const callCompletePasswordReset = async (): Promise<void> => {
    setErrorMessage(undefined);
    const resetOtp = window.location.pathname.split('/').pop() ?? '';
    if (resetOtp === '' || resetOtp === undefined) {
      setErrorMessage('Invalid reset link');
      return;
    }

    if (password !== confirmPassword) {
      setErrorMessage('Passwords do not match.');
      return;
    }
    setIsSubmitted(true);
    if (axAuthManagementGraphQlEndpoint !== undefined) {
      const completePasswordResetResponse = await completePasswordReset(
        resetOtp,
        password,
        axAuthManagementGraphQlEndpoint,
      );
      setIsSubmitted(false);
      if (completePasswordResetResponse.isSuccess) {
        setIsReset(true);
      } else {
        setErrorMessage(
          completePasswordResetResponse.errorMessage ??
            'Unexpected Error occurred while attempting to complete password reset. Please try again later.',
        );
      }
    } else {
      setErrorMessage('AxAuthManagementGraphQlEndpoint is not available');
    }
  };

  return (
    <div
      className={classes.container}
      style={backgroundStyles}
      data-test-id="complete-password-reset-page"
    >
      <div className={classes.whiteBox}>
        <div className={classes.logo}>
          <ImgElement
            alt="Customer logo"
            src={brandingOptions?.companyLogo ?? mosaicLogo}
          />
        </div>
        <div className={classes.content}>
          {errorMessage && (
            <div
              className={classes.errorMessage}
              data-test-id="complete-password-reset-error-message"
            >
              {errorMessage}
            </div>
          )}
          {isReset && (
            <>
              <p data-test-id="complete-password-reset-success-message">
                Your password has been successfully reset.
              </p>
              <div
                className={classes.button}
                onClick={() => window.location.assign('/')}
                data-test-id="complete-password-back-to-signin-button"
              >
                Back to Sign In
              </div>
            </>
          )}
          {!isReset && (
            <>
              <p className={classes.hint}>Please enter the new password.</p>
              <div className={classes.inputGroup}>
                <input
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  autoComplete="new-password"
                  id="reset-password"
                  placeholder="new password"
                  data-test-id="complete-password-new-password"
                />
              </div>
              <div className={classes.inputGroup}>
                <input
                  type="password"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  autoComplete="new-password"
                  id="confirm-reset-password"
                  placeholder="confirm new password"
                  data-test-id="complete-password-confirm-password"
                />
              </div>
              <div
                className={
                  isSubmitted ? classes.buttonDisabled : classes.button
                }
                onClick={() => callCompletePasswordReset()}
                data-test-id="complete-password-change-password-button"
              >
                Change Password
              </div>
              <div
                className={classes.forgotPassword}
                data-test-id="complete-password-back-to-signin-link"
              >
                <a href="/">Back to Sign In</a>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};
