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

export const SendCodeForm = () => {
    const navigate = useNavigate()
    const { mutate, isPending } = useMutation({
        mutationFn: sendOTPMutation,
        mutationKey: ["send-otp"]
    })
    const { mutate: loginOtpMutate, isPending: loginOtpPending } = useMutation({
        mutationFn: loginWithOTP,
        mutationKey: ["login-otp"]
    })
    const [seconds, setSeconds] = useState(30);
    const [isTimeUp, setIsTimeUp] = useState(false);
    const [searchParams] = useSearchParams();
    const { handleSubmit, formState: { errors }, control } = useForm<LoginWithOTP>({
        resolver: yupResolver(LoginCodeSchema)
    })
    const handleSendOTPAgain = async () => {
        await mutate({
            mobile_number: searchParams.get("phone_number")
        },
            {
                onSuccess: () => {
                    toast.success(`کد ورود برای شماره ${searchParams.get("phone_number")} ارسال شد`)
                    setSeconds(30)
                    setIsTimeUp(false)
                },
                onError: (err: any) => handleError(err)

            })
    }
    const submitCode: SubmitHandler<LoginWithOTP> = async (data) => {
        loginOtpMutate({
            ...data,
            mobile_number: searchParams.get("phone_number"),
        },
            {
                onSuccess: (res: any) => {
                    toast.success("با موفقیت وارد شدید")
                    window.localStorage.setItem("token", res?.data?.token)
                    navigate("/")
                    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/login-with-code">
                                <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">
                    {!isTimeUp && <p className="font-normal text-secondary-text-color text-base">{seconds} ثانیه دیگر تا دریافت کد</p>}
                    <ButtonComponent title="تایید" pending={loginOtpPending} type="submit" />
                    <ButtonComponent title="ارسال مجدد" type="button" theme="glass" className={`w-fit h-fit p-0 ${!isTimeUp && "text-secondary-text-color"}`} disable={!isTimeUp} pending={isPending} onClick={handleSendOTPAgain} />
                </div>
            </div>
        </form>
    )
}