import { useState } from 'react';
import { Auth } from '@aws-amplify/auth';

import { Button, Spinner, Text } from 'components/common';
import { FormRow } from 'components/FormRow';
import { Input } from 'components/inputs';
import { useUserContext } from 'context/user';
import { useNotifications } from 'context/notifications';
import {
  useRequestReducer,
  REQUEST,
  SUCCESS,
  FAILURE,
} from 'hooks/useRequestReducer';

export const EmailForm = () => {
  const { push: notify } = useNotifications();

  const { user } = useUserContext();
  const attributes = user?.attributes;

  const [form, setForm] = useState({
    email: attributes?.email,
    code: '',
  });
  const [codeSent, setCodeSent] = useState(false);
  const [verified, setVerified] = useState(attributes?.email_verified);

  const [state, dispatch] = useRequestReducer();

  const notChanged = form.email === attributes?.email;

  const handleChange: React.ChangeEventHandler<HTMLInputElement> = (ev) => {
    const { name, value } = ev.target;
    setForm((form) => ({ ...form, [name]: value }));
  };

  const updateEmail = async () => {
    dispatch(REQUEST());
    try {
      const currentUser = await Auth.currentAuthenticatedUser({
        bypassCache: true,
      });
      await Auth.updateUserAttributes(currentUser, {
        email: form.email,
      });

      setCodeSent(true);
      dispatch(SUCCESS());
      notify('Verification code was sent to your email');
    } catch (error) {
      dispatch(FAILURE(error));
    }
  };

  const verifyEmail: React.MouseEventHandler<HTMLButtonElement> = async (
    ev
  ) => {
    dispatch(REQUEST());
    try {
      await Auth.verifyCurrentUserAttributeSubmit('email', form.code);

      setVerified(true);
      setCodeSent(false);
      dispatch(SUCCESS());
      notify("Congratulations! You've just verified your email");
    } catch (error) {
      dispatch(FAILURE(error));
    }
  };

  const resendCode = async () => {
    dispatch(REQUEST());
    try {
      await Auth.verifyCurrentUserAttribute('email');
      dispatch(SUCCESS());
      notify('Verification code was sent to your email');
    } catch (error) {
      dispatch(FAILURE(error));
    }
  };

  const renderUpdateForm = () => {
    return (
      <>
        <Input
          className="mb2"
          name="email"
          value={form.email}
          onChange={handleChange}
          placeholder="user@email.com"
        />
        <Button
          size="l"
          className="tac me2"
          // color="gray"
          onClick={updateEmail}
          disabled={form.email === '' || notChanged || state.loading}
          block
        >
          Update email
        </Button>
      </>
    );
  };

  const renderConfirmationForm = () => {
    return (
      <>
        <Input
          className="mb2"
          name="code"
          value={form.code}
          onChange={handleChange}
          placeholder="Confirmation code"
        />
        <Button
          size="l"
          color="gray"
          onClick={verifyEmail}
          disabled={state.loading}
          block
        >
          Verify email
        </Button>
      </>
    );
  };

  const renderVerificationForm = () => {
    return (
      <>
        <Input
          className="mb2"
          name="email"
          value={form.email}
          onChange={handleChange}
          placeholder="user@email.com"
          disabled
        />
        <Input
          className="mb2"
          name="code"
          value={form.code}
          onChange={handleChange}
          placeholder="Confirmation code"
        />
        <div className="flex">
          <Button
            size="l"
            className="me2"
            // color={form.code ? 'blue' : 'gray'}
            onClick={verifyEmail}
            disabled={form.code === '' || state.loading}
            block
          >
            Verify
          </Button>
          <Button
            size="l"
            color="gray"
            onClick={resendCode}
            disabled={state.loading}
            block
          >
            Resend
          </Button>
        </div>
      </>
    );
  };

  return (
    <FormRow
      as="div"
      label={verified ? 'Email address' : 'Email address is not\xa0verified'}
    >
      {verified
        ? !codeSent
          ? renderUpdateForm()
          : renderConfirmationForm()
        : renderVerificationForm()}

      {/* {state.success && <Text className="mt4">{state.payload}</Text>} */}
      {state.failure && (
        <Text className="mt4" style={{ color: '#d81b60' }}>
          {state.payload}
        </Text>
      )}

      <Spinner show={state.loading} />
    </FormRow>
  );
};
