"use client";

import { useLang } from "@/lib/lang";
import { useUtility } from "@/lib/utility";
import { useAccess } from "@/lib/access";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useRef, useState, useCallback, useMemo } from "react";
import Link from "next/link";
import { BackBtn, Box, Button, ButtonContainer, CourseToolsBtn, useFormRefs } from "@/Theme/Midone/Forms";
import { Select } from "@/Theme/Midone/Forms/Select";
import { Grid, Frame, useData, FeatherIcon } from "@/Theme/Midone/Utils";
import { YearGroupFilter } from "@/Components/Public/YearGroupFilter";

export function Page({ laraPath,nextPath,course,baseGroup="",baseYear="" }) {
    const { Lang, local } = useLang();
    const { checkPermission } = useAccess();
    // componentPermission("forum.list");
    const toolsFilters = checkPermission("toolsFilters.index");
    const { destroy,getNeedles } = useData();
    const router = useRouter();
    const back = ()=>router.back();
    const nextUrl = nextPath+"/courses/"+course+"/tools";
    const formUrl = "/forum";
    const { getYearSemester, getGroupCode } = useUtility();
    const [getAccess, setGetAccess] = useState();
    const menuPath = usePathname().split('/').includes('myCourses') ? 'myCourses' : 'courses';
    const component = useFormRefs();
    const [params, setParams] = useState({ semester: baseYear,group: baseGroup,correcting:"",type:"",menuPath:menuPath });
    let [url, setUrl] = useState(laraPath+"/forum-list?course="+course);
    const [needles, setNeedles] = useState();
    const effectRan = useRef(false);

    if(baseGroup != "" && baseYear != "") params['flagReport'] = true;   

    useEffect(() => {
        if (!effectRan.current) {
            getNeedles(`${laraPath}/forum/get-needles?course=${course}`, setNeedles);
            effectRan.current = true;
        }
    }, [getNeedles, laraPath]);

    const urlItems = useMemo(() => {
        return Object.keys(params)
            .filter(key => params[key])
            .map(key => `${key}=${params[key]}`)
            .join("&");
    }, [params]);

    useEffect(() => {
        // setUrl(`${laraPath}/forum-list/?course=${course}&${urlItems}`);
        setUrl(`${laraPath}/forum-list?course=${course}&${urlItems}`);
    }, [urlItems, laraPath]);
   
    const filterList = useCallback((e, filter) => {
        setParams((prevParams) => ({ ...prevParams, [filter]: e.target.value }));
    }, []);

    const clearFilter = useCallback(() => {
        setParams({ semester: "", group: "",correcting:"",type:"",menuPath });
    }, []);

    let info = useMemo(() => ({
        // ...(menuPath == "courses" || checkPermission("forum.store") ? { insertLink: nextUrl+formUrl + "/new" } : {}),
        ...((menuPath == "courses" || menuPath == "myCourses") && checkPermission("forum.store") ? { insertLink: nextUrl+formUrl + "/new" } : {}),
        url: url,
        headerJSX:<>
            {checkPermission("forum.reportForum") &&
                <Link className="absolute top-14 left-2 sm:relative sm:float-left sm:mt-2 sm:top-0 btn btn-primary mr-5 mb-2" href={nextUrl+formUrl+"/report"}>{Lang(["public.report"])}</Link> }     
            {(checkPermission("forum.needCheckForum") && baseGroup == "" && baseYear == "")&&
                <Link className="absolute top-14 left-20 sm:relative sm:float-left sm:left-0 sm:mt-2 sm:top-0 btn btn-primary ml-0 mb-2" href={nextUrl+formUrl+"/needCheck"}>{Lang(["public.btn_not_check"])}</Link> }
        </>,
        columns: [
            {label: "title", jsx: (item)=><span>{<Link href={nextUrl+formUrl + "/" + item?.id + "/posts"}>{item?.title}</Link>}</span>},
            {label: "year_semester", jsx: (item) => getYearSemester(item?.group, Lang)},
            {label: "group", jsx: (item)=>getGroupCode(item?.group, Lang)},
            (getAccess)? {label: "last_post", field: "last_post"}
            : {label: "last_post",  field: "last_post_general"},
            getAccess? {label: "subjects", field: "count_post_parent"}:'',
            getAccess? {label: "posts", field: "count_post"}:'',
            getAccess? {label: "not_check", field: "count_post_not_check"}:'',
            getAccess? {label: "status", jsx: (item)=><span className={"text-"+item?.active_status?.color}>{item?.active_status?.["title_"+local]}</span>}:'',
            // getAccess? {label: "need_confirmation", jsx:(item)=> (item?.need_to_apply)? <FeatherIcon spanWrapperclassName="btn-cursor-default" name="Check" /> : "" }:'',
            // {label: "lock", jsx:(item)=> (item?.lock)? <FeatherIcon spanWrapperclassName="btn-cursor-default" name="Lock" color="darkred" />
            //     : <FeatherIcon spanWrapperclassName="btn-cursor-default" name="Unlock" /> },
            // getAccess? {label: "status", jsx: (item)=><span className={"text-"+item?.active_status?.color}>{item?.active_status?.["title_"+local]}</span>}:'',
            {label: "", sort:false, width:"160px", jsx:(item)=><>
                    <div className='flex justify-center'>
                        <FeatherIcon name="MessageCircle" url={nextUrl+formUrl + "/" + item?.id + "/posts"} tooltip={Lang('public.posts')} />
                        <FeatherIcon name="Edit" permission="forum.update" url={nextUrl+formUrl + "/" + item?.id + "/edit"} tooltip={Lang('public.edit')} />
                        <FeatherIcon name="Eye" permission="forum.showInfo" url={nextUrl+formUrl + "/" + item?.id} tooltip={Lang('public.view')} />
                        <FeatherIcon name="XOctagon" permission="forum.destroy" tooltip={Lang('public.delete')} color="darkred" onClick={() => destroy(laraPath+formUrl+"/" + item?.id)} />
                    </div>
                </>
            },
        ],
        callback: (data)=>{ setGetAccess(data?.accessOperation) }

    }), [url, Lang, formUrl, destroy, laraPath]);

    return(
        <Frame title={Lang(["public.forums"])}>
            <Box shadow={false} minIcon={true} min={true} display={(toolsFilters && baseGroup == "" && baseYear == "")} >
                <YearGroupFilter needles={needles} Lang={Lang} filterList={filterList} params={params} />
                <ButtonContainer>
                    <Button label="clear_filter" className="btn btn-secondary w-20 mr-1 ml-1" onClick={clearFilter} />
                </ButtonContainer>
            </Box>
            <div className="intro-y col-span-12 relative">
                <Grid {...info} key={url} className="mt-14 sm:mt-0" />
                <ButtonContainer>
                    <CourseToolsBtn href={`${nextPath}/${menuPath}/${course}/tools`} />
                    <BackBtn onClick={back} display={(baseGroup == "" && baseYear == "")} />
                </ButtonContainer>
            </div>
        </Frame>
    );
}