import { Box, Text, useColorModeValue } from '@chakra-ui/react';
import _debounce from 'lodash/debounce';
import React, { useRef, useEffect, useState, useCallback } from 'react';

const CUT_HEIGHT = 144;

const AccountPageDescription = ({ children }: {children: React.ReactNode}) => {
  const ref = useRef<HTMLParagraphElement>(null);

  const [ needCut, setNeedCut ] = useState(false);
  const [ expanded, setExpanded ] = useState(false);

  const calculateCut = useCallback(() => {
    const textHeight = ref.current?.offsetHeight;
    if (!needCut && textHeight && textHeight > CUT_HEIGHT) {
      setNeedCut(true);
    } else if (needCut && textHeight && textHeight < CUT_HEIGHT) {
      setNeedCut(false);
    }
  }, [ needCut ]);

  useEffect(() => {
    calculateCut();
    const resizeHandler = _debounce(calculateCut, 300);
    window.addEventListener('resize', resizeHandler);
    return function cleanup() {
      window.removeEventListener('resize', resizeHandler);
    };
  }, [ calculateCut ]);

  const expand = useCallback(() => {
    setExpanded(true);
  }, []);

  const gradient = useColorModeValue(
    'linear-gradient(360deg, rgba(255, 255, 255, 0.8) 38.1%, rgba(255, 255, 255, 0) 166.67%)',
    'linear-gradient(360deg, rgba(16, 17, 18, 0.8) 38.1%, rgba(16, 17, 18, 0) 166.67%)',
  );

  return (
    <Box position="relative" marginBottom={{ base: 6, lg: 12 }}>
      <Text
        ref={ ref }
        maxHeight={ needCut && !expanded ? `${ CUT_HEIGHT }px` : 'auto' }
        overflow="hidden"

        style={ needCut && !expanded ? { WebkitLineClamp: '6', WebkitBoxOrient: 'vertical', display: '-webkit-box' } : {} }
      >
        { children }
      </Text>
      { needCut && !expanded && (
        <Box
          position="absolute"
          bottom="-16px"
          left={ 0 }
          width="100%"
          height="63px"
          style={{ background: gradient }}
          onClick={ expand }
        >
        </Box>
      ) }
    </Box>
  );
};

export default AccountPageDescription;
