"use client"

import React, { useEffect, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useAppDispatch, useAppSelector } from '@/lib/redux/hooks';
import { getBodySetting } from '@/lib/redux/features/serviceAdmin';
import { makeStyles } from 'tss-react/mui';
import useResponsive from '@/hooks/useResponsive';
import { useMounted } from '@/hooks/useMounted';
import StorageHelper from '@/lib/storeHelper';
import { STORAGE_KEYS } from '@/types/common';
import { fetchNotificationsPublicPage, getNotificationsList } from '@/lib/redux/features/notifications';
import { getLanguage } from '@/lib/redux/features/locale';

type MakeStylesType = {
  below768: boolean;
  locale: string;
  style: any;
}
const useStyle = makeStyles<MakeStylesType>()((theme, { below768, locale, style }) => (
  {
    header: {
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      padding: '1rem 0',
      borderBottom: '2px solid #d0d0d0',
      fontSize: '18px'
    },
    titleNotifications: {
      // background: '#e2e2e2',
      color: '#707070',
      padding: '0.5rem 1rem',
      width: '100%',
      wordBreak: 'break-word',
      // whitePace: 'nowrap',
      overflow: 'hidden',
      textOverflow: 'ellipsis'
      // border: '1px solid #fff'
    },
    itemNotifications: {
      borderBottom: '2px solid #d0d0d0'
    },
    customCSS: {
      color: '#707070',
      fontWeight: 700,
      fontSize: below768 ? '12px' : '16px'
    },
    textInfo: {
      display: '-webkit-box',
      // WebkitLineClamp: 3,
      // WebkitBoxOrient: 'vertical',
      overflow: 'hidden',
      // maxHeight: 75,
      position: 'relative',
      padding: below768 ? locale === 'en' ? '0 3rem 0.5rem 1rem' : '0 6rem 0.5rem 1rem' : locale === 'en' ? '0 3.2rem 0.5rem 1rem' : '0 7.2rem 0.5rem 1rem',
      wordBreak: 'break-word',
      whitePace: 'wrap'
      // '&:after': {
      //   content: '\'... more\'',
      //   position: 'absolute',
      //   bottom: 0,
      //   right: 0,
      //   background: 'white'
      // }
    },
    btnMore: {
      paddingLeft: 5,
      paddingRight: below768 ? 10 : 0,
      color: 'black',
      cursor: 'pointer',
      position: 'absolute',
      bottom: 2,
      right: 0,
      backgroundColor: `${style.backgroundColor}!important`,
      // textDecoration: 'underline',
      fontWeight: 'bold',
      '&:hover': {
        color: '#d2d2d2'
      }
    },
    btnLess: {
      paddingLeft: 5,
      color: 'black',
      cursor: 'pointer',
      fontWeight: 'bold',
      '&:hover': {
        color: '#d2d2d2'
      }
    },
    btnLessMobile: {
      paddingLeft: 5,
      color: 'black',
      cursor: 'pointer',
      fontWeight: 'bold'
    },
    textInfoCreatedDate: {
      padding: '0 1rem 0.5rem 1rem',
      color: '#999999'
    },
    newInfo: {
      margin: '1.4rem 0',
      width: '100%'
    },
    less: {
      display: '-webkit-box',
      maxHeight: below768 ? 57 : 75,
      WebkitLineClamp: 3,
      // WebkitBoxOrient: 'vertical'
      '&:after': {
        textIndent: '20px'
      }
    },
    contentSpec: {
      width: '100%',
      whiteSpace: 'break-spaces',
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      paddingLeft: 20,
      paddingRight: below768 ? 0 : 20,
      height: 24
    },
    contentNormal: {
      width: '100%',
      whiteSpace: 'nowrap',
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      padding: '0px 20px'
    },
    contentNormal2: {
      width: 'fit-content',
      whiteSpace: 'nowrap',
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      padding: '0px 20px'
    },
    contentLess: {
      width: '95%',
      // whiteSpace: 'nowrap',
      // overflow: 'hidden',
      // textOverflow: 'ellipsis',
      padding: '0px 20px'
    }
  }
));

const HomeNotifications = (props: any) => {
  const t = useTranslations("");
  const mounted = useMounted();
  const dispatch = useAppDispatch();
  const { below768, getBelow768 } = useResponsive();

  const notificationsList: any[] = useAppSelector(getNotificationsList);
  const style = useAppSelector(getBodySetting) || {} as any;
  const locale = useAppSelector(getLanguage);

  const [showMoreList, setShowMoreList] = useState(new Map());
  const [idContent, setIdContent] = useState<any[]>([]);

  // const locale = StorageHelper.getCookie(STORAGE_KEYS.locale);

  const { classes } = useStyle({ below768, locale, style });

  const handleClickBtnMore = (id: any, isSpec: any) => {
    if (!mounted) {
      return null;
    }
    const newMap = new Map(showMoreList);
    newMap.set(id, true);
    setShowMoreList(newMap);
    if (idContent.length > 0) {
      if (idContent.filter(item => item.id === id)) {
        const newList = idContent.map(item => {
          if (item.id === id) {
            return {
              id: id,
              readMore: true
            };
          } else {
            return item;
          }
        });
        setIdContent(newList);
      } else {
        setIdContent([
          ...idContent,
          {
            id: id,
            readMore: true
          }
        ]);
      }
    } else {
      setIdContent([
        ...idContent,
        {
          id: id,
          readMore: true
        }
      ]);
    }
    const textBody = document.getElementById(`textBody-${id}`);
    if (textBody) {
      textBody.style.textOverflow = '';
      textBody.style.whiteSpace = isSpec ? 'break-spaces' : 'normal';
      textBody.style.overflow = 'none';
      textBody.style.height = 'auto';
      textBody.style.wordBreak = 'break-word';
    }
  };

  const handleClickBtnLess = (id: any, isSpec: any) => {
    const newMap = new Map(showMoreList);
    newMap.set(id, false);
    setShowMoreList(newMap);
    if (idContent.length > 0) {
      if (idContent.filter(item => item.id === id)) {
        const newList = idContent.map(item => {
          if (item.id === id) {
            return {
              id: id,
              readMore: false
            };
          } else {
            return item;
          }
        });
        setIdContent(newList);
      } else {
        setIdContent([
          ...idContent,
          {
            id: id,
            readMore: false
          }
        ]);
      }
    } else {
      setIdContent([
        ...idContent,
        {
          id: id,
          readMore: false
        }
      ]);
    }

    if (below768) {
      if (idContent.length > 0) {
        idContent.map(item => {
          const content = document.getElementById(`content-${item.id}`);
          const textBody = document.getElementById(`textBody-${item.id}`);
          const button = document.getElementById(`button-${item.id}`);
          if (content && button && textBody) {
            if (content.offsetWidth > textBody.offsetWidth) {
              button.style.display = 'none';
              content.style.marginBottom = '10px';
            }
            if (content.offsetWidth < textBody.offsetWidth) {
              button.style.display = 'block';
              textBody.style.width = '100%';
            }
          }
        });
      }
    } else {
      if (idContent.length > 0) {
        idContent.map(item => {
          const content = document.getElementById(`content-${item.id}`);
          const textBody = document.getElementById(`textBody-${item.id}`);
          const button = document.getElementById(`button-${item.id}`);
          if (content && button && textBody) {
            if (content.offsetWidth > textBody.offsetWidth) {
              button.style.display = 'none';
              content.style.marginBottom = '10px';
            }
            if (content.offsetWidth < textBody.offsetWidth) {
              textBody.style.width = '100%';
            }
          }
        });
      }
    }
    const textBody = document.getElementById(`textBody-${id}`);
    if (textBody) {
      textBody.style.textOverflow = 'ellipsis';
      textBody.style.whiteSpace = isSpec ? 'break-space' : 'nowrap';
      textBody.style.overflow = 'hidden';
      textBody.style.height = '24px';
      textBody.style.wordBreak = 'normal';
    }
  };

  const renderNotifications = (item: any, index?: number) => {
    const { id, title, body } = item;
    return (
      <div key={`${index}-${id}-${title}`} className={classes.itemNotifications}>
        <div className={`${classes.titleNotifications} ${classes.customCSS}`}>
          {title}
        </div>
        {
          body.includes('\n')
            ? <div id={`textBody-${id}`} className={`${classes.contentSpec}`}>
              {formatContent(id, body)}
            </div>
            : <div id={`content-${id}`}>
              <div id={`textBody-${id}`} className={`${classes.contentNormal2}`}>
                {body}
              </div>
            </div>
        }
        <div id={`button-${id}`} style={{ fontWeight: 'bold', textAlign: 'end', paddingRight: 10 }}>
          <span
            className={below768 ? classes.btnLessMobile : classes.btnLess}
            onClick={() => { handleButonClick(id, body.includes('\n')) }}>
            {formatButtonShow(id)}
          </span>
        </div>
      </div>
    );
  };

  const handleButonClick = (id: any, isSpec: any) => {
    if (idContent.length > 0) {
      idContent.map(item => {
        if (item.id === id) {
          if (item.readMore) {
            return handleClickBtnLess(id, isSpec);
          } else {
            return handleClickBtnMore(id, isSpec);
          }
        }
      });
    }
  };

  useEffect(() => {
    if (idContent.length > 0) {
      idContent.map(item => {
        const content = document.getElementById(`content-${item.id}`);
        const textBody = document.getElementById(`textBody-${item.id}`);
        const button = document.getElementById(`button-${item.id}`);
        if (content && textBody && button) {
          if (content.offsetWidth > textBody.offsetWidth) {
            button.style.display = 'none';
            content.style.marginBottom = '10px';
          }
          if (content.offsetWidth < textBody.offsetWidth) {
            button.style.display = 'block';
            textBody.style.width = '100%';
          }
          textBody.style.width = 'fit-content';
        }
      });
    }
    if (below768) {
      if (idContent.length > 0) {
        idContent.map(item => {
          const content = document.getElementById(`content-${item.id}`);
          const textBody = document.getElementById(`textBody-${item.id}`);
          const button = document.getElementById(`button-${item.id}`);
          if (content && textBody && button) {
            if (content.offsetWidth > textBody.offsetWidth) {
              button.style.display = 'none';
              content.style.marginBottom = '10px';
            }
            if (content.offsetWidth < textBody.offsetWidth) {
              button.style.display = 'block';
              textBody.style.width = '100%';
            }
          }
        });
      }
    } else {
      if (idContent.length > 0) {
        idContent.map(item => {
          const content = document.getElementById(`content-${item.id}`);
          const textBody = document.getElementById(`textBody-${item.id}`);
          const button = document.getElementById(`button-${item.id}`);
          if (content && textBody && button) {
            if (content.offsetWidth > textBody.offsetWidth) {
              button.style.display = 'none';
              content.style.marginBottom = '10px';
            }
            if (content.offsetWidth < textBody.offsetWidth) {
              textBody.style.width = '100%';
            }
          }
        });
      }
    }
  }, [below768, idContent]);

  const formatContent = (id: any, content: any) => {
    if (idContent.length > 0) {
      return (
        <>
          {idContent.map(item => {
            if (item.id === id) {
              if (item.readMore) {
                return content;
              } else {
                return `${content.split('\n')[0]}...`;
              }
            }
          })}
        </>
      );
    }
  };

  const formatButtonShow = (id: any) => {
    if (idContent.length > 0) {
      return (
        <>
          {idContent.map(item => {
            if (item.id === id) {
              if (item.readMore) {
                return t('button.less');
              } else {
                return t('button.more');
              }
            }
          })}
        </>
      );
    }
  };

  useEffect(() => {
    dispatch(fetchNotificationsPublicPage({ size: 3 }));
  }, []);

  useEffect(() => {
    const newList = notificationsList.map(item => {
      return {
        id: item.id,
        readMore: false
      };
    });
    setIdContent(newList);
  }, [notificationsList]);

  return (
    <div className={classes.newInfo} id='notifications-container'>
      {
        notificationsList && notificationsList.length > 0 &&
        <>
          <div className={`${classes.header} ${classes.customCSS}`} >
            <div className='text-left' style={{ marginLeft: below768 ? '10px' : '0px' }}>{t('title.notifications')}</div>
          </div>
          {notificationsList.map((item, index) => renderNotifications(item, index))}
        </>
      }
    </div>
  );
};

export default  HomeNotifications

