"use client";

import { Button, Form, Image } from "react-bootstrap";
import { useFormik } from "formik";
import * as Yup from "yup";
import { useRouter } from "next/navigation";
import { useRequest } from "@/components/App/request";
import { toastrC } from "@/utils/helpers";
import { useApp } from "@/components/App";
import styles from "@/styles/Component/Login/Login.module.scss";
import { useRef } from "react";

const OtpPage = () => {
  const { request } = useRequest();
  const router = useRouter();
  const { state } = useApp();

  if (!state?.email) {
    router.push("/auth/forgot-password");
  }

  // Handling OTP input fields
  const inputRefs = useRef([]);

  const formik = useFormik({
    initialValues: {
      email: state?.email,
      code: ["", "", "", "", "", ""] // OTP array
    },
    validationSchema: Yup.object({
      code: Yup.array()
        .of(
          Yup.string()
            .length(1, "Each digit must be 1 character")
            .matches(/^[0-9]$/, "Must be a number")
        )
        .min(6, "OTP must be exactly 6 digits")
        .required("OTP is required")
    }),
    onSubmit: async (values, { setSubmitting }) => {
      try {
        setSubmitting(true);
        const res = await request("VERIFY_OTP", {
          email: values.email,
          code: values.code.join("") // Convert array to string
        });
        // dispatch({ ...state, code: values.code.join("") });

        if (res.status) {
          toastrC(res.message, "success", "Success");
          router.push("/auth/reset-password");
        } else {
          toastrC(res.message, "error", "Error");
        }
      } catch (error) {
        toastrC(error.message, "error", "Error");
        console.error("Error in OTP verification", error);
      } finally {
        setSubmitting(false);
      }
    }
  });

  // Handle OTP input change
  const handleChange = (index, value) => {
    if (!/^\d?$/.test(value)) return; // Allow only digits

    const newCode = [...formik.values.code];
    newCode[index] = value;
    formik.setFieldValue("code", newCode);

    if (value && index < 5) {
      inputRefs.current[index + 1]?.focus(); // Auto-focus next field
    }
  };

  // Handle backspace navigation
  const handleKeyDown = (index, e) => {
    if (e.key === "Backspace" && !formik.values.code[index] && index > 0) {
      inputRefs.current[index - 1]?.focus();
    }
  };

  const handlePaste = e => {
    e.preventDefault();
    const pasteData = e.clipboardData.getData("text").slice(0, 6); // Get first 6 characters
    if (!/^\d{6}$/.test(pasteData)) return; // Ensure only digits

    const newCode = pasteData.split(""); // Convert to array
    formik.setFieldValue("code", newCode);

    // Move focus to last filled input
    newCode.forEach((_, i) => {
      if (inputRefs.current[i]) {
        inputRefs.current[i].focus();
      }
    });
  };

  const handleResendCode = async () => {
    try {
      const res = await request("FORGOT_PASSWORD", {
        email: state?.email
      });

      if (res.status) {
        toastrC(res.message, "success", "Success");
        // router.push("/auth/reset-password");
      } else {
        toastrC(res.message, "error", "Error");
      }
      // toastrC("Password reset code sent to your email", "success", "Success");
    } catch (err) {
      toastrC(err.message, "error", "Error");
    }
  };

  return (
    <div className={`${styles.LoginCard} ${styles.OtpCardBlock}`}>
      <h1 className="mb-3">Confirm it`s you</h1>
      <p>We have just sent a OTP code to your email.</p>

      <Form onSubmit={formik.handleSubmit}>
        <div className={styles.OtpCard}>
          {formik.values.code.map((digit, index) => (
            <Form.Control
              key={index}
              type="text"
              maxLength={1}
              className={styles.ContactInput}
              value={digit}
              onChange={e => handleChange(index, e.target.value)}
              onKeyDown={e => handleKeyDown(index, e)}
              onPaste={index === 0 ? handlePaste : undefined}
              ref={el => {
                if (el) inputRefs.current[index] = el;
              }}
            />
          ))}
        </div>

        {formik.errors.code && formik.touched.code && (
          <div className="text-danger">{formik.errors.code}</div>
        )}

        <div className={styles.ResendCode}>
          <button
            type="button"
            className="btn btn-link"
            onClick={handleResendCode}
          >
            Resend the code
          </button>
        </div>

        <Button
          type="submit"
          className="btn-custom"
          disabled={formik.isSubmitting}
        >
          {formik.isSubmitting ? "Verifying..." : "Continue"}
          <Image src="../assets/cursor-icon.png" alt="cursor-icon" />
        </Button>
      </Form>
    </div>
  );
};

export default OtpPage;
