import React from 'react';
import * as Yup from 'yup';
import { Form, Formik } from 'formik';
import { InputCompOne } from '..';
import { useNavigate } from 'react-router-dom';
import { RouteHandler } from '../../router/routes';

import { useDispatch } from 'react-redux';
import { updateUserDetails } from '../../store/UserDetails';

import { validateBVN, verifyOTP } from '../../core/apiRequest';
import { RequestStatus } from '../../core/models';

// To get the validation schema
const validationSchema = Yup.object().shape({
  bvn: Yup.string()
    .required('BVN is required')
    .test('no-e', 'Invalid number', (value: any) => {
      if (value && /^[0-9]*$/.test(value) == false) {
        return false;
      }
      return true;
    })
    .min(11, 'must be 11 digits')
    .max(11, 'must be 11 digits'),
  otp: Yup.string()
    // .when('require_otp', {
    //   is: true,
    //   then: Yup.string().required("OTP is required")
    // })
    // .required("OTP is required")
    .test('no-e', 'Invalid number', (value: any) => {
      if (value && /^[0-9]*$/.test(value) == false) {
        return false;
      }
      return true;
    })
    .min(5, 'must be 5 digits')
    .max(5, 'must be 5 digits'),
  // .test("no-e", "must be 11 characters", (value:any) => {
  //   if (value.length < 11) {
  //     return false;
  //   }
  //   return true;
  // })
});

// initial values for formik
let initialValues = {
  bvn: '',
  otp: '',
};

type ValidBVN = {
  verification_id: string;
  valid: undefined | boolean;
};

const LetsGetStarted: React.FC = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  // const [pinValues, setPinValues] = React.useState({
  //   bvn: "",
  //   otp: "",
  // });
  // const otpInputRef = React.useRef<HTMLInputElement>(null);

  const [requestStatusBVN, setRequestStatusBVN] = React.useState<RequestStatus>(
    { loading: false, status: undefined, message: '' }
  );

  const [requestStatusOTP, setRequestStatusOTP] = React.useState<RequestStatus>(
    { loading: false, status: undefined, message: '' }
  );

  const [bvnIsValid, setBvnIsValid] = React.useState<ValidBVN>({
    verification_id: '',
    valid: undefined,
  });

  // e: React.FormEvent<HTMLInputElement>
  // let { value } = e.target as HTMLInputElement;
  const bvnValidation = (values: any) => {
    // Function to Validate BVN
    let bvn = values.bvn;
    setRequestStatusBVN({ loading: true, status: false, message: '' });
    validateBVN({ bvn })
      .then((res) => {
        if (!res || !res.data.call_return) {
          setBvnIsValid({ verification_id: '', valid: false });
          setRequestStatusBVN({
            loading: false,
            status: false,
            message: 'unable to verify BVN',
          });
          return setTimeout(() => {
            setRequestStatusBVN({ loading: false, status: false, message: '' });
          }, 4000);
        }
        setBvnIsValid({
          verification_id: res.data.verification_id,
          valid: true,
        });
        setRequestStatusBVN({
          loading: false,
          status: true,
          message: 'verified',
        });
      })
      .catch((err) => {
        setBvnIsValid({ verification_id: '', valid: false });
        console.log(err);
      });
  };

  const handleSubmit = (values: any) => {
    // Function to VERIFY OTP AND LOGIN USER
    setRequestStatusOTP({ loading: true, status: false, message: '' });
    // console.log('values', values)
    verifyOTP({ ...values, verification_id: bvnIsValid.verification_id })
      .then((res) => {
        if (!res || !res.data.call_return) {
          setRequestStatusOTP({
            loading: false,
            status: false,
            message: 'wrong otp',
          });
          return setTimeout(() => {
            setRequestStatusOTP({ loading: false, status: false, message: '' });
          }, 4000);
        }
        // console.log(res.data)
        localStorage.setItem('token', res.data?.token);
        localStorage.setItem('uid', res?.data?.customer[0]?.uid);
        dispatch(updateUserDetails({ ...res?.data?.customer[0] }));
        navigate(RouteHandler.dashboardHome, { replace: true });
      })
      .catch((err) => {
        setRequestStatusOTP({
          loading: false,
          status: false,
          message: 'something went wrong, try again',
        });
        console.log(err);
        return setTimeout(() => {
          setRequestStatusOTP({ loading: false, status: false, message: '' });
        }, 4000);
      });
  };

  return (
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={bvnIsValid.valid ? handleSubmit : bvnValidation}
    >
      {(props: any) => (
        <Form className="">
          <div className="w-full">
            <div className="containerMode flex justify-between gap-1 xl:gap-8 flex-col">
              <div className="my-[4rem] flex items-center justify-center w-full">
                <h1 className="font-bold text-[2.375rem] text-[#5C2684] my-[.5rem] text-center">
                  Let’s Get You Started
                </h1>
              </div>
              <div className="mx-auto flex flex-col gap-8 max-w-[31.625rem] ">
                <div className="w-full">
                  <InputCompOne
                    parentClass="flex flex-col gap-2"
                    label="Enter Your BVN "
                    name="bvn"
                    parentInputClass="w-full"
                    labelSpan="( To get your BVN, dial *565*0# )"
                    labelSpanClass="text-[13px] text-[#5a5a5a] font-semibold"
                    placeholder="Enter your BVN"
                    labelClass="font-bold text-[18px] leading-[21.78px] tracking-[2%] text-[#282828] mb-[2px] flex item-center gap-[4px]"
                    input
                    inputClass="w-full h-[3.625rem] rounded bg-[#EFEFEF] px-4"
                    value={props.values.bvn}
                    onChange={props.handleChange}
                    error={
                      props.errors.bvn && props.touched.bvn && props.errors.bvn
                    }
                    maxLength={11}
                  />
                  <p
                    className={`p-2 ${
                      !requestStatusBVN.status
                        ? 'text-red-500'
                        : 'text-emerald-500'
                    }`}
                  >
                    {requestStatusBVN.loading
                      ? 'verifying...'
                      : requestStatusBVN.message}
                  </p>
                </div>
                {bvnIsValid.valid && (
                  <InputCompOne
                    parentClass="flex flex-col gap-2"
                    label="Enter OTP "
                    name="otp"
                    parentInputClass="w-full"
                    labelSpan="( Please check your BVN phone number for verification pin )"
                    labelSpanClass="text-[13px] text-[#5a5a5a] font-semibold"
                    placeholder="Enter your OTP"
                    labelClass="font-bold text-[18px] leading-[21.78px] tracking-[2%] text-[#282828] mb-[2px] flex item-center gap-[4px]"
                    input
                    inputClass="w-full h-[3.625rem] rounded bg-[#EFEFEF] px-4"
                    value={props.values.otp}
                    onChange={props.handleChange}
                    error={
                      props.errors.otp && props.touched.otp && props.errors.otp
                    }
                    maxLength={5}
                  />
                )}
                <button
                  type="submit"
                  className="w-full h-[3.625rem] rounded bg-[#FBB700] rounded-2 px-4 text-[18px] text-[#282828] font-semibold disabled:text-[#282828] disabled:text-opacity-50"
                  disabled={
                    requestStatusBVN.loading ||
                    (!props.values.otp && bvnIsValid.valid)
                  }
                >
                  Enter
                </button>

                <p
                  className={`p-2 ${
                    !requestStatusOTP.status
                      ? 'text-red-500'
                      : 'text-emerald-500'
                  }`}
                >
                  {requestStatusOTP.message}
                </p>

                {bvnIsValid.valid || bvnIsValid.valid == undefined ? (
                  <p className="text-[#5C2684] mt-[1.5625rem] w-fit">
                    ***Every personal information attached to your BVN is safe
                    and secure. It is only important for us to verify your
                    information and also give you access to your application
                    profile/account.
                  </p>
                ) : (
                  <p className="text-[#5C2684] mt-[1.5625rem] w-fit">
                    ***Did not receive OTP? Click to resend
                  </p>
                )}
              </div>
            </div>
          </div>
        </Form>
      )}
    </Formik>
  );
};

export default LetsGetStarted;
