"use client";
import React, { use, useEffect, useState } from "react";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
} from "@/components/ui/input-group";
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
import { ArrowRight, Eye, EyeOffIcon } from "lucide-react";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/redux/store";
import { toggleState } from "@/redux/feature/toggleSlice";
import Link from "next/link";
import { Button } from "@/components/ui/button";
import { useForm, SubmitHandler } from "react-hook-form";
import { AuthFormValues, registrationType, sentOtpType } from "@/type/authType";
import CustomForm from "@/components/common/CustomForm";
import { useRouter, useSearchParams } from "next/navigation";
import { useMutation } from "@tanstack/react-query";
import { APIResponseType } from "@/type/comonType";
import { RegistrationResponse } from "@/type/responseType";
import Error from "next/error";
import { reSandOtp, verifySandOtp } from "@/lib/services/auth.services";
import { useApiToast } from "@/hooks/use-apiToast";
import showCustomToast from "@/components/common/toaster/CustomToast";
import { AxiosError } from "axios";
import { otpType } from "../type/otpType";
import { useTimer } from "@/hooks/use-timer";

const RegistrationOtpCodePage = () => {
  const router = useRouter();
  const [registrationPhone, setRegistrationPhone] = useState("");
  const [registrationEmail, setRegistrationEmail] = useState("");
  useEffect(() => {
    const phone = localStorage.getItem("registrationPhone") || "";
    const email = localStorage.getItem("registrationEmail") || "";
    setRegistrationPhone(phone);
    setRegistrationEmail(email);
  }, []);

  const { getToastData } = useApiToast();

  const searchParams = useSearchParams();
  const id = searchParams.get("id");

  const { seconds, isActive, startTimer, formatTime } = useTimer(120);

  useEffect(() => {
    startTimer(); // Start timer on mount
  }, [startTimer]);

  const { mutate: resendOtp, isPending: isResending } = useMutation<
    APIResponseType<null>,
    AxiosError<{ message: string }>,
    sentOtpType
  >({
    mutationFn: reSandOtp,
    onSuccess: (data) => {
      showCustomToast({
        type: "success",
        message: data.message || "OTP resent successfully",
      });
      startTimer(); // Restart timer on success
    },
    onError: (error) => {
      showCustomToast({
        type: "error",
        message: error.response?.data.message || "Failed to resend OTP",
      });
    },
  });

  const {
    mutate: verifyOTP,
    data: registerResponse,
    error,
    isPending,
    isSuccess,
  } = useMutation<
    APIResponseType<otpType>,
    AxiosError<{ message: string }>,
    { otp: string; phone: string; email: string } // Change to object type
  >({
    mutationFn: verifySandOtp,
    onSuccess: (data) => {
      if (typeof window !== "undefined") {
        localStorage.removeItem("registrationPhone");
        localStorage.removeItem("registrationEmail");
      }
      showCustomToast({
        type: "success",
        message: data.message,
      });
      router.push("/finish");

      console.log("I AM HERE-----------");
    },
    onError: (error) => {
      console.log(
        "Registration error----------------:",
        error.response?.data.message,
      );
      const { message, description } = getToastData(error.response);

      showCustomToast({
        type: "error",
        message: message ?? "Something went wrong",
        description,
      });
    },
  });
  const dispatch = useDispatch();
  const isTrue = useSelector((state: RootState) => state.toggle.value);
  const {
    handleSubmit,
    register,
    watch,
    control,
    formState: { errors },
  } = useForm<AuthFormValues>();
  const onSubmit: SubmitHandler<AuthFormValues> = (data) => {
    try {
      verifyOTP({
        otp: data.code,
        phone: registrationPhone,
        email: registrationEmail,
      });
    } catch (error) {
      throw error;
    }
  };

  return (
    <div className="mx-6 flex min-h-screen flex-col items-center justify-center">
      {/* login text */}
      <div className="j border-border mt-15 flex w-full flex-col items-center gap-5 rounded-2xl border py-20 md:py-20 lg:py-55">
        <div className="mx-5">
          <div className="text-background font-bricolage text-5xl font-bold md:text-6xl">
            Enter OTP code{" "}
          </div>
          <div className="text-secondary-text font-bricolage text-sm font-normal">
            Enter the confirmation code we just send you in your Email. <br />{" "}
            Don&apos;t receive a code?
            <Button
              onClick={() =>
                resendOtp({
                  email: registrationEmail,
                  number: registrationPhone,
                })
              }
              disabled={isActive || isResending}
              className="bg-transparent hover:bg-transparent"
            >
              <span
                className={`text-background font-bold underline ${isActive ? "cursor-not-allowed opacity-50" : "cursor-pointer hover:scale-105"}`}
              >
                {isActive ? `Resend in ${formatTime()}` : "Resend"}
              </span>
            </Button>
          </div>
        </div>
        {/* text form */}
        <div className="mx-5 my-10 flex w-full flex-col items-center justify-center">
          <form action="" onSubmit={handleSubmit(onSubmit)}>
            <Field className="font-manrope max-w-sm">
              <CustomForm
                type="code"
                register={register}
                errors={errors}
                control={control!}
                isLoading={isPending}
              />
            </Field>
          </form>
          {/* rules and regulation       */}
        </div>
      </div>
    </div>
  );
};

export default RegistrationOtpCodePage;
