"use client"

import { useLazyExamGetDataByUserIdAndTheoryTrainIdQuery } from '@/services/exam';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { toast } from 'react-toastify';
import { getTranslation } from '../../../../../i18n';

export const ComponentTestProgress = ({ id }: { id: string }) => {
    const [number, setNumber] = useState(3)
    const { t } = getTranslation();
    const session = useSession()
    const userId = session.data?.user?.userInfo?.id
    const router = useRouter()
    const [ExamGetDataByUserIdAndTheoryTrainId, { currentData: dataExamGetDataByUserIdAndTheoryTrainId, isFetching: isFetchingExamGetDataByUserIdAndTheoryTrainId }] = useLazyExamGetDataByUserIdAndTheoryTrainIdQuery()
    const [isLoading, setIsLoading] = useState(false)
    const [shouldStartInterval, setShouldStartInterval] = useState(false);

    useEffect(() => {
        let intervalId: any = undefined

        if (shouldStartInterval) {
            intervalId = setInterval(() => {
                setNumber((currentNumber) => {
                    if (currentNumber !== 0) {
                        return currentNumber - 1;
                    } else {
                        router.push(`/theoreticalTraining/${id}?start=true`)
                        setIsLoading(false)
                        return 0; // Reset to 0 if 100 is reached
                    }
                });
            }, 500);
        }

        return () => clearInterval(intervalId);
    }, [shouldStartInterval]);

    const handleButtonClick = async () => {
        try {
            setIsLoading(true)
            const dataByTheoryTrainIdAndUserId = await ExamGetDataByUserIdAndTheoryTrainId({
                userId: String(userId),
                theoryTrainId: String(id)
            })
            console.log(dataByTheoryTrainIdAndUserId);
            
            if (dataByTheoryTrainIdAndUserId.data && dataByTheoryTrainIdAndUserId.data?.success == false && dataByTheoryTrainIdAndUserId.data?.message == "you are not subscribed") {
                toast.error(t("you-are-not-subscribed"), { autoClose: 3000 });
                setIsLoading(false)
            } else if (dataByTheoryTrainIdAndUserId.data && dataByTheoryTrainIdAndUserId.data.lastAttempt==null) { 
                toast.error(t("you-have-used-all-your-attempts-for-this-day"), { autoClose: 3000 });
                setIsLoading(false)
            }
            else {
                setShouldStartInterval(true);
            }
        } catch (error) {
            // Handle error
            setIsLoading(false)
        }
    }

    return (
        <div className='flex flex-col gap-16 my-4'>
            <div className="text-black text-opacity-90 text-[28px] font-bold font-['Alexandria'] leading-[42px]">استعد لبدء الاختبار</div>
            <CircularProgress size={200} progress={number} strokeWidth={25} end={3} />
            <StartButton isLoading={isFetchingExamGetDataByUserIdAndTheoryTrainId || isLoading} onClick={handleButtonClick} />
        </div>
    )
}

const StartButton = ({ isLoading, onClick }: { isLoading: boolean, onClick: () => void }) => (
    <button
        type='button'
        onClick={onClick}
        className="w-full  px-4 py-[10px] bg-indigo-600 rounded-[96px] justify-center items-center gap-1.5 inline-flex">
        <div className="text-center text-white text-lg font-semibold font-['Alexandria'] leading-[27px]">ابدء</div>
        {isLoading
            ? <div className="loaderDotsWhite" /> :
            <div className="w-[18px] h-[18px] relative" >
                <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path fillRule="evenodd" clipRule="evenodd" d="M11.6161 3.32293C11.8519 3.5251 11.8793 3.88021 11.6771 4.11608L7.49086 9.00001L11.6771 13.8839C11.8793 14.1198 11.8519 14.4749 11.6161 14.6771C11.3802 14.8793 11.0251 14.852 10.8229 14.6161L6.32292 9.36608C6.14236 9.15543 6.14236 8.84459 6.32292 8.63394L10.8229 3.38394C11.0251 3.14807 11.3802 3.12075 11.6161 3.32293Z" fill="white" />
                </svg>
            </div>
        }
    </button>
)


interface CircularProgressProps {
    size: number; // Diameter of the circle
    progress: number; // Current progress out of 100
    strokeWidth: number; // Width of the stroke
    end: number; //  progress out of end
}

const CircularProgress: React.FC<CircularProgressProps> = ({
    size,
    progress,
    strokeWidth,
    end
}) => {
    const radius = (size - strokeWidth) / 2;
    const circumference = radius * 2 * Math.PI;
    const offset = circumference - (progress / end) * circumference;
    // Adding a style object for the animated circle
    const animatedCircleStyle = {
        transition: 'stroke-dashoffset 0.5s ease-out', // Smooth transition for the dash offset
    };
    return (
        <div className="circular-progress">
            <svg
                className='text-primary'
                width={size}
                height={size}
                viewBox={`0 0 ${size} ${size}`}
                xmlns="http://www.w3.org/2000/svg"
            >
                <circle
                    className="circular-bg"
                    stroke="#eee"
                    fill="none"
                    cx={size / 2}
                    cy={size / 2}
                    r={radius}
                    strokeWidth={`${strokeWidth}px`}
                />
                <circle
                    style={animatedCircleStyle} // Apply the style here

                    className="circle"
                    stroke="currentColor"
                    fill="none"
                    cx={size / 2}
                    cy={size / 2}
                    r={radius}
                    strokeWidth={`${strokeWidth}px`}
                    strokeDasharray={`${circumference} ${circumference}`}
                    strokeDashoffset={offset}
                    transform={`rotate(-90 ${size / 2} ${size / 2})`}
                />
                <text
                    className="text-center text-primary text-[64px] font-semibold font-['Alexandria'] leading-[56px]"
                    x="50%"
                    y="50%"
                    textAnchor="middle"
                    dy=".3em"
                    fill="currentColor"
                >
                    {`${progress}`}
                </text>
            </svg>
        </div>
    );
};

export default CircularProgress;


