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

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

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

  const [state, dispatch] = useRequestReducer();
  const [form, setForm] = useState({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
  });

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

  const submitPassword = async () => {
    const { oldPassword, newPassword, confirmPassword } = form;
    if (oldPassword && newPassword === confirmPassword) {
      dispatch(REQUEST());
      try {
        const currentUser = await Auth.currentAuthenticatedUser({
          bypassCache: true,
        });
        await Auth.changePassword(
          currentUser,
          oldPassword.trim(),
          newPassword.trim()
        );

        dispatch(SUCCESS());
        notify('Your password has been changed successfully');
        setForm({ oldPassword: '', newPassword: '', confirmPassword: '' });
      } catch (error) {
        dispatch(FAILURE(error));
      }
    } else {
      dispatch(FAILURE(new Error("Passwords don't match")));
    }
  };

  const [show, showPassword] = useState(false);

  const renderForm = () => {
    return (
      <>
        <PasswordInput
          className="mb2"
          placeholder="Current password"
          type="password"
          value={form.oldPassword}
          name="oldPassword"
          onChange={handleChange}
        />
        <PasswordInput
          className="mb2"
          placeholder="New password"
          type="password"
          value={form.newPassword}
          name="newPassword"
          onChange={handleChange}
          show={show}
          onShow={() => showPassword((s) => !s)}
        />
        <PasswordInput
          className="mb2"
          placeholder="Confirm password"
          type="password"
          value={form.confirmPassword}
          name="confirmPassword"
          onChange={handleChange}
          show={show}
          onShow={() => showPassword((s) => !s)}
        />

        <Button
          size="l"
          // color="gray"
          className="tac me2"
          onClick={submitPassword}
          disabled={
            !form.oldPassword ||
            !form.newPassword ||
            !form.confirmPassword ||
            state.loading
          }
          block
        >
          Change password
        </Button>
      </>
    );
  };

  return (
    <FormRow as="div" label="Password">
      {renderForm()}
      {state.failure && (
        <Text className="mt4" style={{ color: '#d81b60' }}>
          {state.payload}
        </Text>
      )}
      <Spinner show={state.loading} />
    </FormRow>
  );
};
