import React, { useEffect, useState } from "react";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "./ui/input-otp";
import { REGEXP_ONLY_DIGITS } from "input-otp";
import { Button } from "./ui/button";
import { useSendOTP } from "@/hooks/use-auth";
// import { useForgotPasswordMutation } from "@/redux/services/auth.api";

const VerifyOTP = ({
  valueChanger,
  verifyOTP,
  value,
  email,
  userId,
}: {
  valueChanger: (data: string) => void;
  verifyOTP: () => void;
  value: string;
  email: string;
  userId: string;
}) => {
  const [timeLeft, setTimeLeft] = useState(60);
  const { mutateAsync: sendOTP } = useSendOTP();
  useEffect(() => {
    if (timeLeft === 0) return;

    const timer = setInterval(() => {
      setTimeLeft((prev) => prev - 1);
    }, 1000);

    return () => clearInterval(timer);
  }, [timeLeft]);

  // Format time as MM:SS
  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, "0")}:${secs
      .toString()
      .padStart(2, "0")}`;
  };

  // Calculate timer progress percentage
  const timerProgress = (timeLeft / 60) * 100;

  //    const verifyOTP = () => {
  //      // console.log("Verifying:", value);
  //      setStep(2);
  //    };
  const resendOTP = () => {
    sendOTP({ email, userId });
    // forgotPasswordApi({ email })
    //   .unwrap()
    //   .then((res) => {
    //     // console.log("res", res);
    //     if (res.success) {
    //       // toast.success(res.message);
    //     } else {
    //       // toast.error(res.message);
    //     }
    //     // setStep(1); // maybe move this here after success
    //   })
    //   .catch((err) => {
    //     console.log("API Error:", err);
    //   });
    setTimeLeft(60);
  };

  return (
    <>
      <div className="text-center mb-8">
        <h1 className="text-2xl font-bold mb-2">Verification</h1>
        <p className="text-muted-foreground">
          Please enter OTP sent to your email
        </p>
      </div>

      {/* OTP Input Fields */}
      <div className="flex gap-2 mb-6 justify-center">
        <InputOTP
          value={value}
          onChange={(value) => valueChanger(value)}
          pattern={REGEXP_ONLY_DIGITS}
          maxLength={6}
          disabled={timeLeft <= 0}
        >
          <InputOTPGroup>
            <InputOTPSlot index={0} />
            <InputOTPSlot index={1} />
            <InputOTPSlot index={2} />
            {/* </InputOTPGroup> */}
            {/* <InputOTPSeparator /> */}
            {/* <InputOTPGroup> */}
            <InputOTPSlot index={3} />
            <InputOTPSlot index={4} />
            <InputOTPSlot index={5} />
          </InputOTPGroup>
        </InputOTP>
      </div>

      {/* Verify Button */}
      <Button
        className="w-[40%] py-2 rounded-md mb-8"
        onClick={verifyOTP}
        disabled={timeLeft <= 0 || value.length < 6}
      >
        Verify
      </Button>

      {/* Timer */}
      <div className="flex flex-col items-center">
        <div className="relative w-20 h-20 mb-4">
          <svg className="w-full h-full transform -rotate-90">
            <circle
              cx="40"
              cy="40"
              r="36"
              stroke="#e5e7eb"
              strokeWidth="2"
              fill="none"
            />
            <circle
              cx="40"
              cy="40"
              r="36"
              stroke="#07361d"
              strokeWidth="4"
              fill="none"
              strokeDasharray={`${2 * Math.PI * 36}`}
              strokeDashoffset={`${
                2 * Math.PI * 36 * (1 - timerProgress / 100)
              }`}
              className="transition-all duration-1000 ease-linear"
            />
          </svg>
          <div className="absolute inset-0 flex items-center justify-center font-semibold">
            {formatTime(timeLeft)}
          </div>
        </div>

        {/* Resend Link */}
        <div className="text-sm">
          <span className="text-muted-foreground">
            Code didn{"'"}t receive?{" "}
          </span>
          <button
            onClick={resendOTP}
            className="hover:text-primary font-semibold cursor-pointer underline"
            disabled={timeLeft > 0}
          >
            Resend
          </button>
        </div>
      </div>
    </>
  );
};

export default VerifyOTP;
