import React, { useEffect, useState } from 'react';

interface IProps {
    tagRef: React.MutableRefObject<HTMLElement>;
}

export default function MoreOrLess(props: IProps) {
    // setting state for showing more
    const [showMore, setShowMore] = useState(true);
    const [ref, setRef] = useState(null as React.MutableRefObject<HTMLElement>);

    useEffect(() => {
        setRef(props.tagRef);
        props.tagRef &&
        props.tagRef.current &&
        props.tagRef.current.scrollHeight > props.tagRef.current.clientHeight &&
        props.tagRef.current.classList.add('more-less-wrapper');
        return () => {
            props.tagRef && props.tagRef.current && props.tagRef.current.classList.remove('more-less-wrapper');
        };
    }, [props.tagRef]);

    const handleMoreOrLess = (e: React.MouseEvent<HTMLAnchorElement>) => {
        if (ref.current && showMore) {
            ref.current.classList.add('open');
            setShowMore(false);
        } else {
            ref.current.classList.remove('open');
            setShowMore(true);
        }
    };

    const renderMoreOrLess = () => {
        const element = ref.current;
        if (!showMore || (element && (element.scrollHeight > element.clientHeight))) {
            return (
                <a
                    role="button"
                    onClick={handleMoreOrLess}
                    className={`btn btn-app btn-link ${showMore ? 'more' : 'less'}`}
                >
                    {showMore ? 'More' : 'Less'}
                </a>
            );
        }
    };

    return (
        <>
            {ref && ref.current && renderMoreOrLess()}
        </>
    );
}
