"use client";

import {motion, AnimatePresence} from "framer-motion";
import React, {useEffect, useState} from "react";
import {FaEye, FaEyeSlash, FaTimes} from "react-icons/fa";
import {POST} from "@/services/axios/resources/resourcesAPI";
import toast from "react-hot-toast";

export default function LoginModal({setLoginModal, setUserName}) {

    const [mobile, setMobile] = useState("");
    const [firstName, setFirstName] = useState("");
    const [lastName, setLastName] = useState("");
    const [otp, setOtp] = useState("");
    const [mobileError, setMobileError] = useState(false);
    const [nameError, setNameError] = useState(false);
    const [otpError, setOtpError] = useState(false);


    const [confirmOtpModalOpen, setConfirmOtpModalOpen] = useState(false);
    const [loading, setLoading] = useState(false);

    const [isNewUser, setIsNewUser] = useState(false);

    const [timeLeft, setTimeLeft] = useState();

    useEffect(() => {
        const handleEsc = (e) => {
            if (e.key === "Escape") {
                setLoginModal(false);
            }
        };
        window.addEventListener("keydown", handleEsc);
        return () => window.removeEventListener("keydown", handleEsc);
    }, [setLoginModal]);

    function handleSendOTP() {
        if (!mobile || mobile.length !== 11 || !mobile.startsWith('09')) {
            toast.error("لطفا شماره موبایل را به درستی وارد کنید")
            return;
        }
        setLoading(true);

        const payload = {mobile: mobile};

        POST("/api/v1/otp/request", payload)
            .then(res => {
                toast.success("کد با موفقیت ارسال شد");
                setConfirmOtpModalOpen(true);
                setIsNewUser(res?.is_new_user);
                setTimeLeft(res?.retry_after);
            })
            .catch(err => {
                const retryAfter = err?.response?.data?.retry_after;

                toast.error(`خطایی در ارسال کد رخ داد. لطفا پس از ${formatTime(retryAfter)} دوباره سعی کنید`);
            })

            .finally(() => setLoading(false));
    }

    const formatTime = (seconds) => {
        const m = Math.floor(seconds / 60);
        const s = seconds % 60;
        return `${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
    };

    useEffect(() => {
        if (timeLeft <= 0) return;

        const interval = setInterval(() => {
            setTimeLeft((prev) => {
                if (prev <= 1) {
                    clearInterval(interval);
                    return 0;
                }
                return prev - 1;
            });
        }, 1000);

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

    function handleEnterPannel() {

        if (!name && isNewUser) {
            toast.error("لطفا نام خود را وارد کنید");
            setNameError(true);
            return;
        }
        if (!otp || otp.length !== 4) {
            toast.error("لطفا کد تایید را به درستی وارد کنید");
            setOtpError(true);
            return;
        }

        setLoading(true);
        const payload = {
            mobile: mobile,
            code: otp,
            full_name: firstName + lastName
        }


        POST("/api/v1/otp/verify", payload)
            .then((res) => {
                console.log(res);

                localStorage.setItem("accessToken", res.token);

                // چک کن فقط اگر name یا family وجود داشت ذخیره کن
                const name = res?.user?.name || "";
                const family = res?.user?.family || "";

                if (name || family) {
                    const fullName = `${name} ${family}`.trim(); // حذف فاصله اضافی اگر یکی از دو مورد خالی بود
                    setUserName(fullName);
                    localStorage.setItem("userName", fullName);
                }

                window.location.reload();
                setLoginModal(false);
            })
            .catch((err) => {
                console.log(err);
                toast.error("خطایی در احراز هویت بوجود آمده است");
            })
            .finally(() => setLoading(false));


    }

    useEffect(() => {
        setOtp('');
    }, [setLoginModal, confirmOtpModalOpen])


    //login and register values
    const [newName, setNewName] = useState("");
    const [newPassword, setNewPassword] = useState("");
    const [newEmail, setNewEmail] = useState("");
    const [isShowPassword, setIsShowPassword] = useState(true);

    const [loginEmail, setLoginEmail] = useState("");
    const [loginPassword, setLoginPassword] = useState("");


    //login and register
    function handleRegister() {
        setLoading(true);

        const payload = {
            name: newName,
            password: newPassword,
            email: newEmail
        }
        setConfirmOtpModalOpen(true);

        POST("/api/register", payload)
            .then(() => {
                toast.success("با موفقیت ثبت نام شد");
            })
            .finally(() => setLoading(false));
    }

    function handleLogin() {
        setLoading(true);
        const payload = {
            email: loginEmail,
            password: loginPassword,
        }

        POST("/api/v1/otp/login", payload)
            .then(() => {
                toast.success("با موفقیت وارد شدید");

                window.location.reload();
                setLoginModal(false);
            })
            .finally(() => setLoading(false));
    }

    return (
        <AnimatePresence>

            <motion.div
                className="w-screen h-screen fixed inset-0 bg-black/40 flex justify-center items-center z-50"
                initial={{opacity: 0}}
                animate={{opacity: 1}}
                exit={{opacity: 0}}
                onClick={() => setLoginModal(false)}
            >
                <motion.div
                    className="bg-white rounded-2xl shadow-lg w-[50%] p-6 relative flex flex-col gap-4"
                    initial={{y: -30, opacity: 0, scale: 0.95}}
                    animate={{y: 0, opacity: 1, scale: 1}}
                    exit={{y: -30, opacity: 0, scale: 0.95}}
                    transition={{type: "spring", stiffness: 300, damping: 25}}
                    onClick={(e) => e.stopPropagation()}
                >
                    {confirmOtpModalOpen ? (
                        <div className="flex flex-col gap-8">

                            <div className="flex flex-col gap-8">
                                <h1 className="md:text-2xl text-2xl font-bold leading-9">ورود</h1>
                                {/*<div className="flex items-center gap-4">*/}
                                {/*    <p className="text-sm text-muted leading-9">کد تایید به شماره {mobile} ارسال شد.*/}
                                {/*        شماره اشتباه است؟</p>*/}
                                {/*    <button*/}
                                {/*        onClick={() => setConfirmOtpModalOpen(false)}*/}
                                {/*        className="text-primary-main text-sm">*/}
                                {/*        ویرایش شماره*/}
                                {/*    </button>*/}
                                {/*</div>*/}
                                <div className="relative col-span-2">
                                    <input
                                        value={loginEmail}
                                        id={"phoneNumber"}
                                        type="text"
                                        placeholder="ایمیل خود را وارد کنید"
                                        className={`w-full text-right border rounded-lg outline-none p-4 transition duration-200 ${mobileError ? "border-danger-main" : ""}`}
                                        onChange={(e) => {
                                            setLoginEmail(e.target.value)
                                            setMobileError(false);
                                        }}
                                    />
                                    <label htmlFor={"phoneNumber"}
                                           className="bg-white absolute px-4 -top-3.5 right-4 text-sm">
                                        ایمیل
                                    </label>
                                </div>


                                <div className="relative">
                                    <input
                                        value={loginPassword}
                                        id={"phoneNumber"}
                                        type={isShowPassword ? `password` : `text`}
                                        placeholder="رمز عبور"
                                        className={`w-full text-right border rounded-lg outline-none p-4 transition duration-200 ${mobileError ? "border-danger-main" : ""}`}
                                        onChange={(e) => {
                                            setLoginPassword(e.target.value)
                                            setMobileError(false);
                                        }}
                                    />

                                    <label htmlFor={"phoneNumber"}
                                           className="bg-white absolute px-4 -top-3.5 right-4 text-sm">
                                        رمز عبور
                                    </label>
                                    {isShowPassword ? (
                                        <button className="absolute top-[18px] left-3"
                                                onClick={() => setIsShowPassword(!isShowPassword)}>
                                            <FaEyeSlash size={20}/>
                                        </button>
                                    ) : (
                                        <button className="absolute top-[18px] left-3"
                                                onClick={() => setIsShowPassword(!isShowPassword)}>
                                            <FaEye size={20}/>
                                        </button>
                                    )}
                                </div>
                            </div>


                            {isNewUser && (
                                <div>
                                    <div className="relative">
                                        <input
                                            value={firstName}
                                            id={"firstName"}
                                            type="text"
                                            placeholder="نام..."
                                            className={`w-full border rounded-lg outline-none p-4 transition duration-200 ${nameError ? "border-danger-main" : ""}`}
                                            onChange={(e) => {
                                                setFirstName(e.target.value)
                                                setNameError(false);
                                            }}
                                        />
                                        <label htmlFor={"firstName"}
                                               className="bg-white absolute px-4 -top-3.5 right-4 text-sm">
                                            نام
                                        </label>
                                    </div>
                                    <div className="relative">
                                        <input
                                            value={lastName}
                                            id={"lastName"}
                                            type="text"
                                            placeholder="نام خانوادگی..."
                                            className={`w-full border rounded-lg outline-none p-4 transition duration-200 ${nameError ? "border-danger-main" : ""}`}
                                            onChange={(e) => {
                                                setLastName(e.target.value)
                                                setNameError(false);
                                            }}
                                        />
                                        <label htmlFor={"lastName"}
                                               className="bg-white absolute px-4 -top-3.5 right-4 text-sm">
                                            نام خانوادگی شما
                                        </label>
                                    </div>
                                </div>
                            )}

                            <div className="grid grid-cols-1 gap-3 mt-3">
                                {/*<div className="relative col-span-2">*/}
                                {/*    <input*/}
                                {/*        value={otp}*/}
                                {/*        id={"otp"}*/}
                                {/*        type="text"*/}
                                {/*        placeholder="****"*/}
                                {/*        className={`w-full text-left border rounded-lg outline-none p-4 transition duration-200 ${otpError ? "border-danger-main" : ""}`}*/}
                                {/*        onChange={(e) => {*/}
                                {/*            setOtp(e.target.value)*/}
                                {/*            setOtpError(false);*/}
                                {/*        }}*/}
                                {/*    />*/}
                                {/*    <label htmlFor={"otp"} className="bg-white absolute px-4 -top-3.5 right-4 text-sm">کد*/}
                                {/*        تایید ۴ رقمی</label>*/}
                                {/*</div>*/}

                                <button
                                    onClick={() => {
                                        !loading ? handleLogin() : toast.error("لطفا صبر کنید")
                                    }}
                                    className="button col-span-1 py-3 bg-secondary-main text-white py-2 rounded-xl hover:bg-gray-500">
                                    {loading ? (
                                        <div className="mx-auto">
                                            <svg
                                                aria-hidden="true"
                                                className="inline w-5 h-5 text-white animate-spin dark:text-blues-shade6 fill-primary-main"
                                                viewBox="0 0 100 101"
                                                fill="none"
                                                xmlns="http://www.w3.org/2000/svg"
                                            >
                                                <path
                                                    d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
                                                    fill="currentColor"
                                                />
                                                <path
                                                    d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
                                                    fill="currentFill"
                                                />
                                            </svg>
                                        </div>
                                    ) : "ورود به پنل"}
                                </button>
                            </div>
                            {/*<button className="relative overflow-hidden px-6 py-3 rounded-lg bg-secondary-main border border-blue-500 text-blue-500 font-semibold transition-colors duration-300 before:content-[''] before:absolute before:top-0 before:left-1/2 before:-translate-x-1/2 before:w-0 before:h-full before:bg-secondary-main before:transition-all before:duration-300 hover:before:w-full hover:before:left-0 hover:before:translate-x-0 hover:text-white">*/}
                            {/*    هاور کن*/}
                            {/*</button>*/}


                            <p className="text-muted text-sm flex gap-4 item-center">
                                <span className="text-secondary-main font-bold">
                                    {formatTime(timeLeft)}
                                </span>
                                کد تایید را دریافت نکردید؟
                            </p>
                        </div>
                    ) : (
                        <div className="flex flex-col gap-4">
                            <div className="grid grid-cols-2">
                                <div className="flex flex-col gap-2">
                                    <h2 className="md:text-2xl text-2xl font-bold leading-9">ورود / ثبت نام</h2>
                                    <p className="text-sm text-muted leading-9">برای ورود لطفا شماره موبایل خود را وارد
                                        کنید.</p>
                                </div>

                                <div className="flex items-start justify-end">
                                    <button
                                        onClick={() => setLoginModal(false)}
                                        className="group"
                                    >
                                        <FaTimes size={20}
                                                 className="transition duration-200 group-hover:text-danger-main"/>
                                    </button>

                                </div>

                            </div>

                            <div className="grid grid-cols-3 gap-5 mt-3">
                                <div className="relative col-span-2">
                                    <input
                                        value={newName}
                                        id={"phoneNumber"}
                                        type="text"
                                        placeholder="نام"
                                        className={`w-full text-right border rounded-lg outline-none p-4 transition duration-200 ${mobileError ? "border-danger-main" : ""}`}
                                        onChange={(e) => {
                                            setNewName(e.target.value)
                                            setMobileError(false);
                                        }}
                                    />
                                    <label htmlFor={"phoneNumber"}
                                           className="bg-white absolute px-4 -top-3.5 right-4 text-sm">
                                        نام
                                    </label>
                                </div>

                                <div className="relative col-span-2">
                                    <input
                                        value={newEmail}
                                        id={"phoneNumber"}
                                        type="text"
                                        placeholder="ایمیل"
                                        className={`w-full text-right border rounded-lg outline-none p-4 transition duration-200 ${mobileError ? "border-danger-main" : ""}`}
                                        onChange={(e) => {
                                            setNewEmail(e.target.value)
                                            setMobileError(false);
                                        }}
                                    />
                                    <label htmlFor={"phoneNumber"}
                                           className="bg-white absolute px-4 -top-3.5 right-4 text-sm">
                                        ایمیل
                                    </label>
                                </div>

                                <div className="relative col-span-2">
                                    <div className="relative">
                                        <input
                                            value={newPassword}
                                            id={"phoneNumber"}
                                            type={isShowPassword ? `password` : `text`}
                                            placeholder="رمز عبور"
                                            className={`w-full text-right border rounded-lg outline-none p-4 transition duration-200 ${mobileError ? "border-danger-main" : ""}`}
                                            onChange={(e) => {
                                                setNewPassword(e.target.value)
                                                setMobileError(false);
                                            }}
                                        />

                                        {isShowPassword ? (
                                            <button className="absolute top-[18px] left-3"
                                                    onClick={() => setIsShowPassword(!isShowPassword)}>
                                                <FaEyeSlash size={20}/>
                                            </button>
                                        ) : (
                                            <button className="absolute top-[18px] left-3"
                                                    onClick={() => setIsShowPassword(!isShowPassword)}>
                                                <FaEye size={20}/>
                                            </button>
                                        )}
                                    </div>

                                    <label htmlFor={"phoneNumber"}
                                           className="bg-white absolute px-4 -top-3.5 right-4 text-sm">
                                        رمز عبور
                                    </label>
                                </div>

                                <button
                                    onClick={() => {
                                        !loading ? handleRegister() : toast.error("لطفا صبر کنید")
                                    }}
                                    className="button col-span-1 bg-secondary-main text-white py-2 rounded-xl hover:bg-gray-800">
                                    {loading ? (
                                        <div className="mx-auto">
                                            <svg
                                                aria-hidden="true"
                                                className="inline w-5 h-5 text-white animate-spin dark:text-blues-shade6 fill-primary-main"
                                                viewBox="0 0 100 101"
                                                fill="none"
                                                xmlns="http://www.w3.org/2000/svg"
                                            >
                                                <path
                                                    d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
                                                    fill="currentColor"
                                                />
                                                <path
                                                    d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
                                                    fill="currentFill"
                                                />
                                            </svg>
                                        </div>
                                    ) : "ثبت نام"}
                                </button>
                            </div>

                            <p className="text-muted text-sm">
                                کد تایید ورود به این شماره ارسال میشود
                            </p>
                        </div>
                    )}


                </motion.div>
            </motion.div>
        </AnimatePresence>
    );
}
