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

import classNames from 'classnames';
import { PropsWithChildren, useEffect, useState, useCallback } from 'react';
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 { PageUrl } from '@/constants/app';

import './index.less';

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

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

const PREFIX = 'base-message';

function BaseMessage(props: IUserMessageProps) {
  const { id, message, isRead: isReadProps, children } = 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(
    () => navigateTo(PageUrl.MaterialView, { resumeId: message.jobId, source: MaterialViewSource.Chat }),
    [message.jobId]
  );
  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`}
        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;
