import { Controller, SubmitHandler, useForm } from "react-hook-form";
import OTPInput from "react-otp-input"
import { Link, useNavigate, useSearchParams } from "react-router-dom"
import { ResetPasswordCodeInterface } from "../../types";
import { yupResolver } from "@hookform/resolvers/yup";
import { ResetPasswordCodeSchema } from "../../schema";
import { ErrorComponent } from "../common/error";
import { useMutation } from "@tanstack/react-query";
import { checkOTP, sendOTPMutation } from "../../services/api/auth";
import toast from "react-hot-toast";
import { useEffect, useState } from "react";
import { ButtonComponent } from "../common/button";
import { handleError } from "../../utility/error-handle";

export const ResetpasswordCodeForm = () => {
    const navigate = useNavigate()
    const [seconds, setSeconds] = useState(30);
    const [isTimeUp, setIsTimeUp] = useState(false);
    const [searchParams] = useSearchParams()
    const { mutate, isPending } = useMutation({
        mutationFn: checkOTP,
        mutationKey: ["check-otp"]
    })

    const { mutate: sendOTPMutate, isPending: sendOTPPending } = useMutation({
        mutationFn: sendOTPMutation,
        mutationKey: ["send-otp"]
    })

    const { handleSubmit, formState: { errors }, control } = useForm<ResetPasswordCodeInterface>({
        resolver: yupResolver(ResetPasswordCodeSchema)
    })

    const submitCode: SubmitHandler<ResetPasswordCodeInterface> = async (data) => {
        await mutate({
            ...data,
            mobile_number: searchParams.get("phone_number"),
        },
            {
                onSuccess: () => {
                    toast.success(`کد وارد شده مطابقت دارد`)
                    navigate(`/auth/reset-password?mobile_number=${searchParams.get("phone_number")}&otp=${data?.otp}`)
                },
                onError: (err: any) => handleError(err)

            })
    }

    const handleSendOTPAgain = async () => {
        await sendOTPMutate({
            mobile_number: searchParams.get("phone_number")
        },
            {
                onSuccess: () => {
                    toast.success(`کد ورود برای شماره ${searchParams.get("phone_number")} ارسال شد`)
                    setSeconds(30)
                    setIsTimeUp(false)
                },
                onError: (err: any) => handleError(err)
            })
    }

    useEffect(() => {
        if (seconds > 0) {
            const timer = setInterval(() => {
                setSeconds(prevSeconds => prevSeconds - 1);
            }, 1000);
            return () => clearInterval(timer);
        } else {
            setIsTimeUp(true);
        }
    }, [seconds]);

    return (
        <form onSubmit={handleSubmit(submitCode)}
            className="w-fit xl:w-1/2 xl:p-0 p-10 flex flex-col bg-auth-form justify-center items-center gap-y-[42px] rounded-3xl">
            <img src="/svgs/logo/logo.svg" alt="logo" className="auth-logo-size" />
            <div className="flex flex-col xl:-mr-24">
                <div className="flex flex-col gap-y-5">
                    <span className="font-medium text-lg md:text-2xl xl:text-3xl text-primary-text-color">فراموشی رمز عبور</span>
                    <div className="flex flex-row gap-x-0.5 items-center">
                        <div className="flex flex-col sm:flex-row gap-0.5 items-center">
                            <p className="text-secondary-text-color font-normal text-xs md:text-sm">کد تایید ارسال شده به شماره {searchParams.get("phone_number")} را وارد کنید.</p>
                            <Link to="/auth/forgot-password">
                                <p className="text-primary-color font-bold text-xs md:text-sm cursor-pointer">ویرایش</p>
                            </Link>
                        </div>
                    </div>
                </div>
                <div className="mt-9 mb-[42px] flex w-full justify-center items-center" id="otp">
                    <Controller control={control} name="otp" render={({ field }) => (
                        <div>
                            <OTPInput
                                containerStyle="otp-container"
                                {...field}
                                numInputs={6}
                                renderInput={(props) => <input {...props} />}
                                inputStyle="otp-inputs"
                            />
                            <ErrorComponent show={errors.otp} message={errors.otp?.message} />
                        </div>
                    )} />

                </div>
                <div className="flex flex-col gap-y-[27px] items-center">
                    <p className="font-normal text-secondary-text-color text-base">{seconds} ثانیه دیگر تا دریافت کد</p>
                    <ButtonComponent title="تایید" pending={isPending} type="submit" />
                    <ButtonComponent title="ارسال مجدد" type="button" theme="glass" className={`w-fit h-fit p-0 ${!isTimeUp && "text-secondary-text-color"}`} disable={!isTimeUp} pending={sendOTPPending} onClick={handleSendOTPAgain} />
                </div>
            </div>
        </form>
    )
}