import * as Yup from "yup";
import Modal from "components/containers/modal/Modal";
import { Formik } from "formik";
import { useTranslation } from "react-i18next";
import InputField from "components/controls/InputField";
import Button from "components/controls/Button";

type Props = {
  isShown: boolean;
  onClose: VoidFunction;
  onSubmit: (password?: string) => void;
};

type FormValues = {
  password: string;
};

type FormValuesValidation = {
  [Property in keyof FormValues]: any;
};

export default function PasswordConfirmation({
  isShown,
  onClose,
  onSubmit,
}: Props) {
  const { t } = useTranslation();

  return (
    <Modal isOpen={isShown} onClose={onClose} className="max-w-lg">
      <Modal.CloseButton onClose={onClose} />
      <Modal.Header>{t("dialogues.confirmAction.title")}</Modal.Header>
      <Formik
        initialValues={{
          password: "",
        }}
        validationSchema={Yup.object().shape<FormValuesValidation>({
          password: Yup.string().min(2, "min 2 characters").required(),
        })}
        onSubmit={async (values, actions) => {
          onSubmit(values.password);
          onClose();
        }}
      >
        {(formik) => (
          <form onSubmit={formik.handleSubmit}>
            <InputField
              name="password"
              placeholder="Password"
              type="password"
              value={formik.values.password}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              autoComplete="off"
              error={formik.errors.password}
              touched={formik.touched.password}
            />
            <div className="text-sm text-center">
              {t("dialogues.confirmAction.description")}
            </div>
            <Modal.Footer className="text-center">
              <Button type="outline" htmlType="submit" variant="red">{t('dialogues.confirmAction.confirm')}</Button>
            </Modal.Footer>
          </form>
        )}
      </Formik>
    </Modal>
  );
}
