"use client";
import { useLang } from "@/lib/lang";
import { useAccess } from "@/lib/access";
import { BackBtn, Button, ButtonContainer, CourseToolsBtn } from "@/Theme/Midone/Forms";
import { Grid, Frame,useData} from "@/Theme/Midone/Utils";
import { FeatherIcon} from "@/Theme/Midone/Utils/FeatherIcon";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useRef, useState, useEffect } from "react";
// import { motion } from "framer-motion";

export function Page({laraPath, nextPath ,course}){

    const router = useRouter();
    const { componentPermission,checkPermission } = useAccess();
    // componentPermission(`contents.list`);
    const accessStroe = checkPermission("contents.store");
    const accessReport = checkPermission("contents.store");
    const back = ()=>router.back();
    const {Lang,local} = useLang();
    const {destroy} = useData();
    const [access, setAccess] = useState(false)
    const menuPath = usePathname().split('/').includes('myCourses') ? 'myCourses' : 'courses';
    let formUrl = "/"+menuPath+"/"+course+"/tools/learnpath";

    let info = {
        ...(menuPath == "courses" || menuPath == "myCourses") && accessStroe ? { insertLink: nextPath+formUrl + "/new" } : {},
        perPage:20,
        url: laraPath+"/content-list/"+course,
        columns: [
            {label: "title", minWidth:"250px", jsx: (item)=><span>{<Link href={nextPath+formUrl + "/" + item.id}>{item.title}</Link> }</span>},
            {
                label: "description",
                minWidth:"300px",
                jsx: (item) => {
                    const html = item?.description || '';
                    // حذف تگ‌های HTML و &nbsp;
                    const text = html
                        .replace(/<[^>]+>/g, '')       // حذف تگ‌های HTML
                        .replace(/&nbsp;/g, ' ')       // حذف فاصله‌های غیرقابل‌شکستن
                        .trim();                       // حذف فاصله‌های اضافی ابتدا و انتها

                    const limited = (text.split(' ').slice(0, 20).join(' ') + '...').replace(/\r?\n/g, "<br>");
                    return <Description text={limited} expandedHeight="60px" />
                }
            },

            {label: "duration", field: "duration"},
            {label: "order", field: "order"},
            accessReport?{label: "view", width:"70px",  field: "view_count"}:"",
            accessReport?{label: "status", width:"60px",  jsx: (item)=><span className={item.active_status?.color}>{item.active_status?.["title_"+local]}</span>}:'',
            {label: "",
                sort:false, 
                width:"110px", 
                jsx:(item)=><>
                    <div className='flex justify-center '>
                        <FeatherIcon permission="contents.visited" name="Users"  url={nextPath+formUrl+"/"+item.id+"/visitors"} tooltip={Lang('public.visitors')} />
                        <FeatherIcon permission="contents.update" name="Edit"  url={nextPath+formUrl+"/"+item.id+"/edit"} tooltip={Lang('public.edit')} />
                        <FeatherIcon name="Eye" url={nextPath+formUrl+"/"+item.id} tooltip={Lang('public.view')} />
                        <FeatherIcon permission="contents.destroy" name="XOctagon"  tooltip={Lang('public.delete')} color="darkred" onClick={()=>destroy(laraPath+"/contents/"+item.id)} />
                    </div>
                </>
            },
        ],
        callback: (data)=>{ setAccess(data?.userAccess) }
    }

    return(
        <Frame title={Lang(["public.contents"])}>
            <div className="intro-y col-span-12">
                <Grid {...info} key={"table key"} />
                <ButtonContainer>
                    <CourseToolsBtn href={`${nextPath}/${menuPath}/${course}/tools`} />
                    <BackBtn onClick={back} />
                </ButtonContainer>
            </div>
        </Frame>
        
    );
}

const Description = ({text, expandedHeight="80px"}) => {
    const contentRef = useRef(null);
    const [expanded, setExpanded] = useState(false);
    const [showButton, setShowButton] = useState(false);

    useEffect(() => {
        if (contentRef.current) {
            const fullHeight = contentRef.current.scrollHeight;
            setShowButton(fullHeight > expandedHeight.replace("px", "") );
        }
    }, [text]);

    return (
        <div>
            <div
                ref={contentRef}
                style={{
                    maxHeight: expanded ? "none" : expandedHeight,
                    overflow: "hidden",
                    transition: "max-height 0.3s ease",
                    position: "relative",
                    fontSize: "0.75rem",
                }}
            >
                <div dangerouslySetInnerHTML={{__html: text}} />
            </div>

            {showButton && (
                <button
                    onClick={() => setExpanded(!expanded)}
                    style={{
                        marginTop: "8px",
                        background: "none",
                        border: "none",
                        color: "#2563eb",
                        cursor: "pointer",
                        padding: 0,
                    }}
                >
                    {expanded ? "نمایش کمتر" : "نمایش بیشتر"}
                </button>
            )}
        </div>
    );
}