import { useLayoutEffect, useRef, useState } from 'react';
import { Link as RouterLink } from 'react-router-dom';

import { IconMessageCircle } from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import Link from '@material-hu/mui/Link';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuAvatar from '@material-hu/components/design-system/Avatar';
import HuCircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import { MAX_NAME_LENGTH } from 'src/constants/posts';
import { useAuth } from 'src/contexts/JWTContext';
import { type UsePostReactionsReturn } from 'src/hooks/usePostReactions';
import { eventsRoutes } from 'src/pages/dashboard/events/routes';
import { groupsRoutes } from 'src/pages/dashboard/groups/routes';
import { profileRoutes } from 'src/pages/dashboard/profile/routes';
import { DEFAULT_EMOJI } from 'src/types/feed';
import { type LiveStreamPost } from 'src/types/stream';
import { getCorrectLiveDescription } from 'src/utils/feed';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { truncateText } from 'src/utils/text';
import { getFullName, getInitials } from 'src/utils/userUtils';

import CommentCountPost from 'src/components/comments/CommentCountPost';
import CommentPostButton from 'src/components/comments/CommentPostButton';
import ShowMoreCommentsButton from 'src/components/comments/ShowMoreCommentsButton';
import { ReactionsList } from 'src/components/dashboard/reactions';
import PostText from 'src/components/post/PostText';
import ReadOnly from 'src/components/RichTextEditor/ReadOnly';
import TimeDistance from 'src/components/time/TimeDistance';

import AddComment from '../../components/AddComment';
import CommentUsers from '../../components/CommentUsers';
import {
  COMMENT_ADD_INPUT_ID,
  FULL_SCREEN_COMMENT_WIDTH,
} from '../../constants';
import useLiveStreamComments from '../hooks/useLiveStreamComments';

const SCROLL_THRESHOLD = 50;
const DESCRIPTION_MAX_CHARACTERS = 180;
const DESCRIPTION_MAX_NEW_LINES = 4;

export type ReactionsHandlers = UsePostReactionsReturn;

type LiveDetailsProps = {
  post: LiveStreamPost;
  reactionsHandlers: ReactionsHandlers;
  fullScreenContainer: HTMLDivElement | null | undefined;
};

const LiveDetails = (props: LiveDetailsProps) => {
  const { post, reactionsHandlers, fullScreenContainer } = props;
  const [isAtBottom, setIsAtBottom] = useState(true);
  const { t } = useLokaliseTranslation('livestream');
  const { user: currentUser } = useAuth();
  const commentsContainerRef = useRef<HTMLDivElement | null>(null);
  const commentsEndRef = useRef<HTMLDivElement | null>(null);

  const {
    user,
    group,
    event,
    createdAt,
    id,
    reactions,
    commentCount,
    commentsEnabled,
    body: description,
    bodyAttributes,
    bodyHtml,
  } = post;
  const { handleAddReaction, handleRemoveReaction, getReactionUsers } =
    reactionsHandlers;

  const isEventPostType = !!event;
  const isGroupPostType = !!group;

  const {
    commentsSorted,
    showLoadMoreComments,
    hasNoComments,
    isLoadingComments,
    isFetchingNextPage,
    fetchNextPage,
    postMutation,
  } = useLiveStreamComments({
    post,
    commentsEnabled,
    commentsEndRef,
    currentUser,
  });

  useLayoutEffect(() => {
    if (commentsEndRef.current && isAtBottom) {
      commentsEndRef.current.scrollIntoView();
    }
  }, [commentsSorted[commentsSorted.length - 1]?.id]);

  const handleClickComment = () => {
    const textarea = document.getElementById(COMMENT_ADD_INPUT_ID);
    textarea?.focus();
  };

  const handleScroll = () => {
    if (!commentsContainerRef.current) return;

    const { scrollTop, scrollHeight, clientHeight } =
      commentsContainerRef.current;

    setIsAtBottom(scrollHeight - scrollTop - clientHeight <= SCROLL_THRESHOLD);
  };

  return (
    <Stack
      sx={{
        width: FULL_SCREEN_COMMENT_WIDTH,
        position: 'absolute',
        bottom: 0,
        right: 0,
        top: 0,
        backgroundColor: 'new.background.layout.tertiary',
        px: 2,
        py: 3,
      }}
      onMouseMove={e => {
        // stop propagation to prevent the parent from triggering
        // the mouse move event and show live controls
        e.stopPropagation();
      }}
    >
      <Stack sx={{ flexDirection: 'row', gap: 1, mb: 2 }}>
        <HuAvatar
          src={user.profilePicture || ''}
          text={getInitials(getFullName(user))}
        />
        <Stack>
          <Stack
            sx={{
              display: '-webkit-box',
              WebkitLineClamp: 2,
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
            }}
          >
            <HuTooltip
              description={getFullName(user)}
              disableTooltip={getFullName(user).length < MAX_NAME_LENGTH}
              slotProps={{
                popper: {
                  container: fullScreenContainer,
                },
              }}
            >
              <Link
                component={RouterLink}
                to={profileRoutes.profile(user.id)}
                variant="globalS"
                sx={th => ({
                  display: 'inline',
                  verticalAlign: 'middle',
                  color: th.palette.new.text.neutral.default,
                  textDecoration: 'none',
                  fontWeight: 'semiBold',
                  transition: 'color 0.2s',
                  '&:hover': {
                    color: th.palette.primary.main,
                    textDecoration: 'underline',
                  },
                })}
              >
                {truncateText(getFullName(user), MAX_NAME_LENGTH)}
              </Link>
            </HuTooltip>
            <Typography
              variant="globalS"
              color="new.text.neutral.lighter"
              sx={{ mx: 0.5, display: 'inline', verticalAlign: 'middle' }}
            >
              {getCorrectLiveDescription(
                t,
                !group?.title && !event?.title,
                true,
              )}
            </Typography>
            {isGroupPostType && group?.title && (
              <Link
                color="textPrimary"
                component={RouterLink}
                to={groupsRoutes.detail(group.id)}
                variant="globalS"
                sx={th => ({
                  display: 'inline',
                  verticalAlign: 'middle',
                  color: th.palette.new.text.neutral.default,
                  textDecoration: 'none',
                  fontWeight: 'semiBold',
                  transition: 'color 0.2s',
                  '&:hover': {
                    color: th.palette.newBase?.brand[500],
                    textDecoration: 'underline',
                  },
                })}
              >
                {group.title}
              </Link>
            )}
            {isEventPostType && event?.title && (
              <Link
                color="textPrimary"
                component={RouterLink}
                to={eventsRoutes.event(event.id)}
                variant="globalS"
                sx={th => ({
                  display: 'inline',
                  verticalAlign: 'middle',
                  color: th.palette.new.text.neutral.default,
                  textDecoration: 'none',
                  fontWeight: 'semiBold',
                  transition: 'color 0.2s',
                  '&:hover': {
                    color: th.palette.newBase?.brand[500],
                    textDecoration: 'underline',
                  },
                })}
              >
                {event.title}
              </Link>
            )}
          </Stack>
          <TimeDistance
            date={new Date(createdAt)}
            showIcon={false}
            typographySx={{
              fontSize: '14px',
              fontWeight: 'regular',
            }}
          />
        </Stack>
      </Stack>
      {!!bodyHtml && (
        <ReadOnly
          content={bodyHtml}
          maxCharacters={DESCRIPTION_MAX_CHARACTERS}
          maxNewLines={DESCRIPTION_MAX_NEW_LINES}
        />
      )}
      {!bodyHtml && (
        <PostText
          body={description}
          bodyAttributes={bodyAttributes}
          maxCharacters={DESCRIPTION_MAX_CHARACTERS}
          maxNewLines={DESCRIPTION_MAX_NEW_LINES}
        />
      )}
      <ReactionsList
        id={id}
        reactions={reactions}
        getReactionUsers={getReactionUsers}
        onAdd={handleAddReaction}
        onRemove={handleRemoveReaction}
        withUserList
        containerElement={fullScreenContainer}
        defaultEmoji={DEFAULT_EMOJI}
      />
      <Divider sx={{ my: 1 }} />
      {!commentsEnabled && (
        <Stack sx={{ mt: 4, textAlign: 'center' }}>
          <Typography
            variant="globalXS"
            color="new.text.neutral.lighter"
          >
            {t('VIEWER_COMMENTS_DISABLED')}
          </Typography>
        </Stack>
      )}
      {commentsEnabled && (
        <>
          <Stack
            sx={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              px: 2,
              py: 1.5,
            }}
          >
            <CommentPostButton handleClickComment={handleClickComment} />
            <CommentCountPost commentCount={commentCount} />
          </Stack>
          <Divider sx={{ my: 1 }} />
          <Stack
            ref={commentsContainerRef}
            onScroll={handleScroll}
            sx={{
              mb: 1,
              flex: 1,
              justifyContent: hasNoComments ? 'center' : 'flex-start',
              overflow: 'auto',
            }}
          >
            {isLoadingComments && (
              <Stack sx={{ textAlign: 'center' }}>
                <HuCircularProgress />
              </Stack>
            )}
            {hasNoComments && !isLoadingComments && (
              <Stack sx={{ alignItems: 'center', gap: 1 }}>
                <HuAvatar
                  Icon={IconMessageCircle}
                  size="large"
                  variant="rounded"
                  color="primary"
                />

                <Stack sx={{ alignItems: 'center' }}>
                  <Typography
                    variant="globalM"
                    color="new.text.neutral.default"
                    fontWeight="fontWeightSemiBold"
                  >
                    {t('VIEWER_NO_COMMENTS')}
                  </Typography>
                  <Typography
                    variant="globalXS"
                    color="new.text.neutral.lighter"
                  >
                    {t('VIEWER_NO_COMMENTS_DESCRIPTION')}
                  </Typography>
                </Stack>
              </Stack>
            )}
            {!hasNoComments && !isLoadingComments && (
              <Stack sx={{ gap: 2 }}>
                {showLoadMoreComments && (
                  <ShowMoreCommentsButton
                    handleLoadMoreComments={fetchNextPage}
                  />
                )}
                {!!commentsSorted?.length &&
                  commentsSorted.map(elem => (
                    <CommentUsers
                      key={elem.id}
                      comment={elem}
                    />
                  ))}
                <Stack ref={commentsEndRef} />
                {isFetchingNextPage && (
                  <Stack sx={{ textAlign: 'center' }}>
                    <HuCircularProgress />
                  </Stack>
                )}
              </Stack>
            )}
          </Stack>
          <AddComment
            postMutation={postMutation}
            canAddImages={false}
            containerElement={fullScreenContainer}
          />
        </>
      )}
    </Stack>
  );
};

export default LiveDetails;
