import React from "react";
// PatternFly
import { Button } from "@patternfly/react-core";
// Modals
import ModalWithFormLayout from "src/components/layouts/ModalWithFormLayout";
// Components
import PasswordInput from "src/components/layouts/PasswordInput";
// RPC
import { ErrorResult } from "src/services/rpc";
import { useSetHostPasswordMutation } from "src/services/rpcHosts";
// Hooks
import { addAlert } from "src/store/Global/alerts-slice";
// Redux
import { useAppDispatch } from "src/store/hooks";

interface PropsToResetPassword {
  host: string;
  isOpen: boolean;
  onClose: () => void;
  onRefresh: () => void;
}

const HostSetPassword = (props: PropsToResetPassword) => {
  const dispatch = useAppDispatch();

  // RPC hooks
  const [setPassword] = useSetHostPasswordMutation();

  // Passwords
  const [newPassword, setNewPassword] = React.useState("");
  const [verifyPassword, setVerifyPassword] = React.useState("");
  const [passwordHidden, setPasswordHidden] = React.useState(true);
  const [verifyPasswordHidden, setVerifyPasswordHidden] = React.useState(true);

  // Fields
  const fields = [
    {
      id: "new-password",
      name: "New Password",
      pfComponent: (
        <PasswordInput
          dataCy="reset-password-new-password"
          id="reset-password-new-password"
          name="password"
          value={newPassword}
          aria-label="new password text input"
          onChange={setNewPassword}
          onRevealHandler={setPasswordHidden}
          passwordHidden={passwordHidden}
        />
      ),
    },
    {
      id: "reset-password",
      name: "Verify password",
      pfComponent: (
        <>
          <PasswordInput
            dataCy="set-password-verify-password"
            id="set-password-verify-password"
            name="password2"
            value={verifyPassword}
            aria-label="verify password text input"
            onChange={setVerifyPassword}
            onRevealHandler={setVerifyPasswordHidden}
            passwordHidden={verifyPasswordHidden}
            rules={[
              {
                id: "verify-match",
                message: "Passwords must match",
                validate: (v: string) => v === newPassword,
              },
            ]}
          />
        </>
      ),
    },
  ];

  // Reset fields and close modal
  const resetFieldsAndCloseModal = () => {
    // Reset fields
    setNewPassword("");
    setVerifyPassword("");
    setPasswordHidden(true);
    setVerifyPasswordHidden(true);
    // Close modal
    props.onClose();
  };

  // on Reset Password
  const onSetPassword = () => {
    setPassword([props.host, newPassword]).then((response) => {
      if ("data" in response) {
        if (response.data?.result) {
          // Close modal
          resetFieldsAndCloseModal();
          // Refresh data
          props.onRefresh();
          // Set alert: success
          dispatch(
            addAlert({
              name: "set-password-success",
              title: "Set one-time password for host '" + props.host + "'",
              variant: "success",
            })
          );
        } else if (response.data?.error) {
          // Set alert: error
          const errorMessage = response.data.error as ErrorResult;
          dispatch(
            addAlert({
              name: "set-password-error",
              title: errorMessage.message,
              variant: "danger",
            })
          );
        }
      }
    });
  };

  const actions = [
    <Button
      data-cy="modal-button-set-password"
      key={"set-password"}
      variant="primary"
      type="submit"
      form="reset-password-form"
      isDisabled={
        newPassword === "" ||
        verifyPassword === "" ||
        newPassword !== verifyPassword
      }
    >
      Reset password
    </Button>,
    <Button
      data-cy="modal-button-cancel"
      key={"cancel-set-password"}
      variant="link"
      onClick={resetFieldsAndCloseModal}
    >
      Cancel
    </Button>,
  ];
  return (
    <>
      <ModalWithFormLayout
        dataCy="host-set-password-modal"
        variantType="small"
        modalPosition="top"
        title="Set password"
        formId="reset-password-form"
        fields={fields}
        show={props.isOpen}
        onSubmit={onSetPassword}
        onClose={resetFieldsAndCloseModal}
        actions={actions}
      />
    </>
  );
};

export default HostSetPassword;
