import React, { FormEvent, useState } from "react";
import OTPInput from "./OTPInput";

interface Props {
  email: string;
  code: string;
  timer: number;
  setCode: (value: string) => void;
  onSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
  resendCode: () => void;
}

const OTPVerification: React.FC<Props> = ({
  email,
  timer,
  setCode,
  onSubmit,
  resendCode,
  code,
}) => {
  const [otp, setOtp] = useState("");

  const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (otp.length === 4) {
      onSubmit(e);
    } else {
      alert("Please enter the 4-digit code");
    }
  };

  return (
    <div className="request-container">
      <h1 className="header">Verification</h1>
      <p className="sub-header">
        Enter the 4-digit code sent to <strong>{email}</strong>.
      </p>
      <form className="auth-form" onSubmit={handleSubmit}>
        <OTPInput
          length={4}
          onComplete={(codes) => {
            setOtp(code);
            setCode(codes);
          }}
          code={code}
        />
        <div className="timing">
          {timer > 0
            ? `${String(Math.floor(timer / 60)).padStart(2, "0")}:${String(
                timer % 60
              ).padStart(2, "0")}`
            : ""}
        </div>
        <button
          type="submit"
          className="continue-button"
          //   disabled={otp.length < 4} // prevent clicking if not complete
        >
          Verify
        </button>
      </form>
      <div
        className={`resend ${timer > 0 ? "disabled" : ""}`}
        onClick={timer === 0 ? resendCode : undefined}
        style={{
          cursor: timer === 0 ? "pointer" : "not-allowed",
          opacity: timer === 0 ? 1 : 0.5,
        }}
      >
        If you didn’t receive a code, <span>Resend</span>
      </div>
    </div>
  );
};

export default OTPVerification;
