"use client";
import LoadingButton from '@/components/ui/loading/Loader';
import { SECRET_KEY } from '@/config/env';
import { useRouterNavigation } from '@/hooks/useRouterNavigation';
import useTabFocus from '@/hooks/useTabFocus';
import { useTranslation } from '@/hooks/useTranslation';
import { resendVerificationCode, verificationCode } from '@/libs/axios/modules/auth';
import { getProfile } from '@/libs/axios/modules/user';
import { login } from '@/libs/cookies/isLoggedIn';
import { saveToken } from '@/libs/cookies/token';
import { saveUser } from '@/libs/cookies/user';
import { firstWordCapital, toCapitalize } from '@/utils/text';
import CryptoJS from 'crypto-js';
import Image from 'next/image';
import { useSearchParams } from 'next/navigation';
import { JSX, SyntheticEvent, useCallback, useEffect, useRef, useState } from "react";
import { Bounce, toast } from 'react-toastify';

export default function OTPPage(): JSX.Element {
    const length: number = 6;
    const [otp, setOtp] = useState<string[]>(Array(length).fill(""));
    const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
    const { navigate } = useRouterNavigation();
    const { t } = useTranslation();
    const searchParams = useSearchParams();
    const type = searchParams.get('type') || '';
    const email = searchParams.get('email') || '';
    const [errors, setErrors] = useState({
        code: "",
    });
    const [num, setNum] = useState(90);
    const [disabled, setDisabled] = useState(true);
    const isFocused = useTabFocus();
    const interValRef = useRef<NodeJS.Timeout | null>(null);
    const decreaseNum = useCallback(() => setNum((prev) => prev - 1), []);
    const [loading, setLoading] = useState(false);

    const handleChange = (index: number, value: string) => {
        if (!/^[0-9]?$/.test(value)) return;
        const newOtp = [...otp];
        newOtp[index] = value;
        setOtp(newOtp);

        if (value && index < length - 1) {
            inputRefs.current[index + 1]?.focus();
        }
    };

    const handleKeyDown = (
        index: number,
        e: React.KeyboardEvent<HTMLInputElement>
    ) => {
        if (e.key === "Backspace" && !otp[index] && index > 0) {
            inputRefs.current[index - 1]?.focus();
        }
    };

    const isOtpComplete = otp.every((digit) => digit !== "");

    function generateRandomString(length = 64) {
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#$%^&*()-_=+|]}[{;:,<.>/?';
        let result = '';
        const charactersLength = characters.length;

        for (let i = 0; i < length; i++) {
            result += characters.charAt(Math.floor(Math.random() * charactersLength));
        }

        return result;
    }

    const resendVerification = async (e: SyntheticEvent) => {
        e.preventDefault();
        try {
            setLoading(true);
            const secretKey = SECRET_KEY ?? '';

            const encryptedEmail = decodeURIComponent(email);

            const plainEmail = CryptoJS.AES.decrypt(encryptedEmail, secretKey).toString(CryptoJS.enc.Utf8);
            const { data: response } = await resendVerificationCode({ email: plainEmail });
            setLoading(false);
            if (interValRef.current) {
                setNum(90);
                setDisabled(true);
                interValRef.current = setInterval(decreaseNum, 1000);
            }
            if (response && response.data) {
                toast.success(t('success.request'), {
                    position: "top-center",
                    autoClose: 2000,
                    hideProgressBar: false,
                    closeOnClick: true,
                    pauseOnHover: true,
                    draggable: true,
                    progress: undefined,
                    theme: "colored",
                    transition: Bounce,
                });
            }
        } catch (error: any) {
            setLoading(false);
            let message: string = error.message;
            if (error && error.data && error.data) {
                message = error.data.message;
            };
            toast.error(message, {
                position: "top-center",
                autoClose: 2000,
                hideProgressBar: false,
                closeOnClick: true,
                pauseOnHover: true,
                draggable: true,
                progress: undefined,
                theme: "colored",
                transition: Bounce,
            });
        }
    }

    const onSubmit = async (e: SyntheticEvent) => {
        e.preventDefault();
        try {
            setLoading(true);
            const secretKey = SECRET_KEY ?? '';

            const encryptedType = decodeURIComponent(type);
            const encryptedEmail = decodeURIComponent(email);

            const plainType = CryptoJS.AES.decrypt(encryptedType, secretKey).toString(CryptoJS.enc.Utf8);
            const plainEmail = CryptoJS.AES.decrypt(encryptedEmail, secretKey).toString(CryptoJS.enc.Utf8);

            if (plainType === 'login' || plainType === 'forgot_password') {
                const code = otp.join("");
                const deviceToken = generateRandomString();
                const body = {
                    code,
                    device_token: deviceToken,
                    email: plainEmail
                };
                const { data: response } = await verificationCode(body);
                if (response && response.data && response.data.token) {
                    const token = response.data.token;
                    const { data: responseProfile } = await getProfile(token);
                    toast.success(t('success.verification'), {
                        position: "top-center",
                        autoClose: 2000,
                        hideProgressBar: false,
                        closeOnClick: true,
                        pauseOnHover: true,
                        draggable: true,
                        progress: undefined,
                        theme: "colored",
                        transition: Bounce,
                    });
                    if (plainType === 'login') {
                        saveUser(responseProfile.data);
                        login();
                        saveToken(response.data.token);
                        navigate('/');
                    } else {
                        saveToken(response.data.token);
                        navigate('/auth/reset-password');
                    }
                }
            }
        } catch (error: any) {
            let message: string = error.message;
            if (error && error.data && error.data) {
                message = error.data.message;
                if (error.data.errors) {
                    setErrors(error.data.errors);
                    return;
                }
            }
            toast.error(message, {
                position: "top-center",
                autoClose: 2000,
                hideProgressBar: false,
                closeOnClick: true,
                pauseOnHover: true,
                draggable: true,
                progress: undefined,
                theme: "colored",
                transition: Bounce,
            });
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (isFocused) {
            interValRef.current = setInterval(decreaseNum, 1000);
        }

        return () => {
            clearInterval(interValRef.current ?? undefined);
        };
    }, [isFocused])

    useEffect(() => {
        if (num <= 0) {
            setDisabled(false);
            clearInterval(interValRef.current ?? undefined);
        }
    }, [num])

    return (
        <form onSubmit={onSubmit} className="min-h-screen w-full flex flex-col justify-center items-center gap-5">
            <Image
                src="/assets/Main/Logo/logo kutubuku.png"
                alt="Logo KutuBuku"
                width={200}
                height={100}
                priority
            />
            <div className='max-w-md gap-5 p-6 rounded-lg shadow-lg bg-white flex flex-col w-full'>
                <h2 className="text-3xl font-bold mb-2 text-center">{toCapitalize(t('OTP verification'))}</h2>
                <p className="text-sm text-dark-300">
                    {firstWordCapital(t('enter the OTP code that we have sent to your email, to verify your account'))}.
                </p>
                <div className="flex items-center justify-center gap-2 p-8">
                    {otp.map((digit, index) => (
                        <input
                            key={index}
                            ref={(el) => {
                                inputRefs.current[index] = el;
                            }}
                            type="text"
                            value={digit}
                            onChange={(e) => handleChange(index, e.target.value)}
                            onKeyDown={(e) => handleKeyDown(index, e)}
                            maxLength={1}
                            className="w-12 h-12 border-b border-gray-600 text-center text-2xl font-bold bg-light-500 focus:outline-primary-500 transition duration-200"
                        />
                    ))}
                </div>
                <LoadingButton
                    type="submit"
                    loading={loading}
                    disabled={!isOtpComplete}
                    className={`w-full p-2 mt-4 rounded-lg text-white font-semibold transition-all capitalize
                    ${isOtpComplete
                            ? "bg-primary-500 hover:bg-green-600 cursor-pointer"
                            : "bg-gray-400 cursor-not-allowed"
                        }`}
                >
                    {firstWordCapital(t("verifikasi"))}
                </LoadingButton>
                <p className="text-sm text-dark-300 mt-10 text-center">
                    {firstWordCapital(t("didn't get the code"))}?
                    <span className='font-inter-600 text-sm text-dark-500'>{num > 0 && `${num} ${t('seconds')}`}</span>
                    {
                        !disabled &&
                        <button disabled={disabled} onClick={resendVerification} className="font-inter-500 text-sm text-primary-500 capitalize">{t('resend')}</button>
                    }
                </p>
            </div>
        </form>
    );
}