"use client";

import { useLang } from "@/lib/lang";
import Link from "next/link";
import { useRouter } from 'next/navigation';
import { useEffect, useState } from "react";
import { Button, ButtonContainer, CheckBox, Frame, useData, useFormRefs } from "@/Theme/Midone/Forms";
import { useConfig } from "@/lib/config";
import { Loading } from "@/Theme/Midone";

export function Tools({ courseId , path}) {
    const { laraAdmin, mediaPath, nextAdmin } = useConfig();
    const { Lang ,local} = useLang();
    const router = useRouter();
    const component = useFormRefs();
    const { get} = useData();
    const [isLoading, setIsLoading] = useState(false);
    
    const toolsUrl = (courseId != undefined) && `${laraAdmin}/courses/tools/${courseId}`;

    const ROLES = {
        Teacher: 1,
        Student: 2,
        // Assistant: 3,
        // Admin: [4,5,6,7,8,9],
    };

    useEffect(() => {
        if(courseId != undefined && toolsUrl != undefined) get(toolsUrl, component, "info");
    }, [courseId]);

    const updateToolStatus = async (tool) => {
        setIsLoading(true); // شروع لودینگ
        get(`${laraAdmin}/courses/change-tools/${courseId}/${tool}`, component, "course",()=>{
            get(toolsUrl, component, "info"); // Reload data after change
            setIsLoading(false);
        });
    };

    // if(component?.state?.info != undefined){

        const toolsData = component?.state?.info?.tools;
        const course = component?.state?.info?.course;
        const role = component?.state?.info?.register?.role_id;
        const groupCode = component?.state?.info?.register?.group;
        const group = (component?.state?.info?.register?.group)?.slice(-2);
        // const self_study = (component?.state?.info?.register?.self_study);
        const hasAccess = ![1,2,3].includes(parseInt(role));
        // const hasAccess = role == ROLES.Admin;
        const isStudent = role == ROLES.Student;
    // }
    const inactiveImgClass = "filter grayscale pointer-events-none";
    const back = () => router.back();
// console.log(component?.state?.info?.register);
    return (
        <>
            {toolsData?.length > 0 ?
            <>
            <Frame
            style={{ filter: isLoading ? 'blur(4px)' : 'none', opacity: isLoading ? 0.8 : 1,transition: 'all 0.3s ease'}}
             title={Lang("public.tools") +" "+ Lang("public.group") +" "+(group ? group :  "")} cols={10}>
            {toolsData?.map((tool, index) => {
                let hrefTools = course?.[tool.title_en] == 0 && isStudent ? "#" : `${nextAdmin}/${path}/${courseId}/tools/${tool.href}`;

                return (
                    <div key={index} className="col-span-5 md:col-span-4 lg:col-span-3 xl:col-span-2 file box rounded-md px-5 pt-8 pb-5 sm:px-5 relative zoom-in btn-cursor-default"
                    style={{ filter: isLoading ? 'blur(4px)' : 'none', opacity: isLoading ? 0.8 : 1,transition: 'all 0.3s ease'}}
                    >
                        <Link href={hrefTools} className="w-3/5 file__icon file__icon--image mx-auto">
                            <div className={`file__icon--image__preview image-fit ${course?.[tool.title_en] == 0 ? inactiveImgClass : ''}`}>
                                <img alt={tool.title_en} src={`${mediaPath}/baseTools/${tool.img}`} />
                            </div>
                        </Link>
                        <Link href={hrefTools} className="block font-medium mt-4 text-center truncate">
                            {tool['title_'+local]}
                        </Link>
                        {hasAccess && (
                            <CheckBox
                                onChange={() => updateToolStatus(tool.title_en)}
                                defaultValue={course?.[tool.title_en]}
                                label=" "
                                name={Lang('public.active')}
                                refItem={[component, "status_id"]}
                                value={0}
                            />
                        )}
                    </div>
                );
            })}

            </Frame>
            <ButtonContainer>
                <Button label="back" onClick={back} />
            </ButtonContainer>
            </>
            :<Loading />
            }
        </>
    );
}
