import { Image } from '@tarojs/components';

import classNames from 'classnames';
import { PropsWithChildren, useEffect, useState, useCallback } from 'react';

import { PageUrl } from '@/constants/app';
import { MaterialViewSource } from '@/constants/material';
import useUserInfo from '@/hooks/use-user-info';
import { IChatMessage } from '@/types/message';
import { getScrollItemId } from '@/utils/common';
import { navigateTo } from '@/utils/route';

import './index.less';

export interface IBaseMessageProps {
  id: string;
  message: IChatMessage;
}

export interface IUserMessageProps extends PropsWithChildren, IBaseMessageProps {
  isRead?: boolean;
  resumeId?: string;
}

const PREFIX = 'base-message';

function BaseMessage(props: IUserMessageProps) {
  const { id, message, isRead: isReadProps, children, resumeId } = props;
  const { userId } = useUserInfo();
  const [isRead, setIsRead] = useState(message.isRead);
  const isSender = message.senderUserId === userId;

  // useEffect(() => {
  //   if (isSender) {
  //     return;
  //   }
  //   // 对方发的消息，拉取到消息后，后端会主动已读，这里延迟模拟下
  //   const timer = setTimeout(() => setIsRead(true), 1200);
  //   return () => clearTimeout(timer);
  // }, [isSender]);
  const handleClick = useCallback(() => {
    if (!resumeId || isSender) {
      return;
    }
    navigateTo(PageUrl.MaterialView, { resumeId: resumeId, source: MaterialViewSource.Chat });
  }, [resumeId, isSender]);
  useEffect(() => {
    if (isRead) {
      return;
    }
    isReadProps && setIsRead(true);
  }, [isRead, isReadProps]);

  return (
    <div className={classNames(PREFIX, { 'is-sender': isSender })} id={getScrollItemId(id)}>
      <Image
        mode="aspectFit"
        className={`${PREFIX}__avatar`}
        onClick={handleClick}
        src={message.senderAvatarUrl || require('@/statics/png/default_avatar.png')}
      />
      <div className={`${PREFIX}__content-container`}>
        {children}
        <div className={classNames(`${PREFIX}__status`, { done: isRead })}>{isRead ? '已读' : '未读'}</div>
      </div>
    </div>
  );
}

export default BaseMessage;
