"use client"
import { usePathname, useRouter } from 'next/navigation';
import React, { useEffect } from 'react'
import { getTranslation } from '../../../../../i18n';
import { useSession } from 'next-auth/react';
import { useSelector } from 'react-redux';
import { IRootState } from '@/store';
import ReactTimeAgo from 'react-time-ago';
import { useLazyTheoryTrainAttemptsGetDataByUserTheoryTrainAndUserIdQuery } from '@/services/theoryTrainAttempts';
import { ArrowIcons } from '@/components/icon/menu/ArrowIcons';

export const List = ({ id }: { id: string }) => {
    const router = useRouter()
    const pathname = usePathname()
    const { t } = getTranslation();
    const { data: sessionData } = useSession();
    const userId = sessionData?.user?.userInfo?.id;

    const [TheoryTrainAttemptsGetDataByUserTheoryTrainAndUserId, { currentData: dataTheoryTrainAttemptsGetDataByUserTheoryTrainAndUserId, isFetching: isFetchingTheoryTrainAttemptsGetDataByUserTheoryTrainAndUserId }] = useLazyTheoryTrainAttemptsGetDataByUserTheoryTrainAndUserIdQuery()
    useEffect(() => {
        if (userId && id) {
            TheoryTrainAttemptsGetDataByUserTheoryTrainAndUserId({
                userId: String(userId),
                userTheoryTrainId: String(id),
            })
        }
    }, [userId, id])
    const isRtl = useSelector((state: IRootState) => state.themeConfig.rtlClass) === 'rtl' ? true : false;


    if (isFetchingTheoryTrainAttemptsGetDataByUserTheoryTrainAndUserId) {
        return <div className='flex justify-center items-center h-[50vh]'>
            <div className="loader !bg-primary"></div>
        </div>
    }
    return (
        <div className='flex flex-col justify-center items-center md:my-16 max-md:my-2  w-full'>
            {(dataTheoryTrainAttemptsGetDataByUserTheoryTrainAndUserId?.details?.length ?? 0) > 0 && <div className=" text-black text-opacity-90 text-[32px] font-bold font-['Alexandria'] leading-[35px]">{t("previous-attempts")}</div>}

            <div className='CardDetails internalMenu  w-full   max-md:max-w-[100%] md:max-w-[50%] my-6'>
                {dataTheoryTrainAttemptsGetDataByUserTheoryTrainAndUserId?.details?.map((item, index) => {
                    return (
                        <ItemList
                            props={{
                                onClick: () => {
                                    if (item.score != null) {
                                        router.push(`/theoreticalTraining/${id}?start=true&result=true&theoryTrainAttemptId=${item.id}`)
                                    } else {
                                        router.push(`/theoreticalTraining/${id}?start=true`)
                                    }
                                }
                            }}
                            // children={<div className="text-black text-opacity-60 text-xs font-normal font-['Alexandria'] leading-[18px]">{item.score == null ? t('not-finished') : ""}</div>} 
                            key={index}
                            title={
                                item.score == null ?
                                    <>
                                        الاختبار غير منتهي
                                    </> :
                                    t('degree') + " : " +
                                    (item.score != null ? item.score ?? "" : "")
                            }
                            value={
                                item.score == null ? <ArrowIcons className='rtl:rotate-180 text-[#000]/50' /> :
                                    < ReactTimeAgo date={item.score ? new Date(item.endAt) : new Date()} locale={isRtl ? 'ar' : 'en-US'} />} />

                    )
                })
                } </div>
        </div> 
    )
}

export const ItemList = ({ title, value, props, children }: { children?: React.ReactNode, title: React.ReactNode, value: string | React.ReactNode, props?: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement> }) => {
    return <div
        {...props}
        className='available-item'>
        <div className=" flex justify-between cursor-pointer ">
            <div className='font-semibold  px-1 min-w-fit'>
                {title}
            </div>
            <div className='font-light'>
                {value}
            </div>
        </div>
        {children}

    </div>
}
