import { Button, Form, Input, Modal, notification, Spin } from "antd";
import React, { FC, useEffect, useState } from "react";
import FormInput from "../../sellerLanding/common/FormInput";
import cx from "classnames";
import styles from "./resetPassword.module.scss";
import { useMediaQuery } from "react-responsive";
import * as commonAPI from "../../../pages/api/common";
import { baseUrl } from "../../../constants/urls";
import OTPModal from "../otpModal/OTPModal";
import { passwordMsg } from "../../../constants/errorMessages";
const ResetPassword: FC<any> = ({
  isResetPassword,
  handleCloseResetPassword,
  email,
  stateArray
}) => {
  const isMobile = useMediaQuery({ maxWidth: 767.68 });
  const [form] = Form.useForm();
  const [isOtpVerified, setIsOtpVerified] = useState(false);
  const [isOTPModalVisible, setIsOTPModalVisible] = useState(false);
  const [isLoading, setIsLoading] =  useState(false);

  const ResetPassword = (formData: any) => {
    setIsLoading(true);
    commonAPI
      .getRequest(
        `${baseUrl}/api/forget-password/verify-otp?email=${email}&otp=${formData.code}`
      )
      .then((res) => {
        setIsLoading(false);
        setIsOtpVerified(true);
        
        form.resetFields();
      });
  };
  const ResetConfirmPassword = (formData: any) => {
    setIsLoading(true);
    const params = {
      email: email,
      password: formData.new_password,
      confirmPassword: formData.confirm_new_password,
    };
    commonAPI
      .postRequest(`${baseUrl}/api/forget-password/change-password`, params)
      .then((res) => {
        notification.success({ message: res?.data?.message });
        handleCloseResetPassword();
        setTimeout(() => {
          setIsOTPModalVisible(true);
          setIsLoading(false);
        }, 10);
      });
  };


  return (
    <>
      <Modal
        maskClosable={false}
        visible={isResetPassword}
        onOk={handleCloseResetPassword}
        onCancel={handleCloseResetPassword}
        footer={null}
        width={isMobile ? "98%" : 400}
        destroyOnClose={true}
      >
        <Spin size="large" spinning={isLoading}>
        {!isOtpVerified ? (
          <div>
            <h2 className={styles.title}>Reset Password</h2>
            <div className={styles.contentText}>
              An email with a verification code was just sent to {email}
            </div>
            <Form
              className="p-6"
              onFinish={ResetPassword}
              name="email_login"
              initialValues={{ remember: true }}
              autoComplete="on"
              form={form}
            >
              <Form.Item
                className={cx(styles.inputContainer)}
                name="code"
                rules={[
                  {
                    required: true,
                  },
                ]}
              >
                <FormInput
                  label="Enter Code"
                  placeholder="Enter Code"
                  name="Enter Code"
                  type="text"
                  required="true"
                  inputType="Text"
                />
              </Form.Item>
              <Form.Item>
                <Button type="primary" block htmlType="submit">
                  Next
                </Button>
              </Form.Item>
            </Form>
          </div>
        ) : (
          <div>
            <h2 className={styles.title}>Set New Password</h2>
            <div className={styles.contentText}>
              Please enter below your new password to Login your account.
            </div>
            <Form
              className="p-6"
              onFinish={ResetConfirmPassword}
              name="reset_password"
              initialValues={{ remember: true }}
              autoComplete="on"
              layout="vertical"
              form={form}
            >
              <Form.Item
                className={cx(styles.inputContainer)}
                name="new_password"
                label="Set New Password"
                rules={[
                  {
                    required: true,
                    pattern:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/,
                    message: passwordMsg+    " &nbsp;Ex : Johney@1",
                  }
                ]}
              >
                {/* <FormInput
                label="Set New Password"
                placeholder="Set New Password"
                name="Set New Password"
                type="text"
                required="true"
                inputType="Text"
              /> */}
                <Input.Password
                  placeholder="Set New Password"
                  name="Set New Password"
                  onCopy={(e)=>{
                    e.preventDefault()
                    return false;
                  }}
                />
              </Form.Item>
              <Form.Item
                className={cx(styles.inputContainer)}
                name="confirm_new_password"
                dependencies={["new_password"]}
                label="Confirm New Password"
                hasFeedback
                rules={[
                  {
                    required: true,
                    message: "Please confirm your password!",
                  },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue("new_password") === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(
                        new Error(
                          "The two passwords that you entered do not match!"
                        )
                      );
                    },
                  }),
                ]}
              >
                {/* <FormInput
                label="Confirm New Password"
                placeholder="Confirm New Password"
                name="Confirm New Password"
                type="text"
                required="true"
                inputType="Text"
              /> */}
                <Input.Password
                  placeholder="Set New Password"
                  name="Set New Password"
                  onPaste={(e)=>{
                    e.preventDefault()
                    return false;
                  }}
                />
              </Form.Item>
              <Form.Item>
                <Button type="primary" block htmlType="submit">
                  Submit
                </Button>
              </Form.Item>
            </Form>
          </div>
        )}
        </Spin>
      </Modal>
      {isOTPModalVisible && (
        <OTPModal
          handleOTPClose={() => {
            setIsOTPModalVisible(false);
          }}
          isOTPModalVisible={isOTPModalVisible}
          stateArray={stateArray}
        />
      )}
    </>
  );
};

export default ResetPassword;
