import { CaretDownOutlined, CaretUpOutlined } from '@ant-design/icons';
import { Avatar, Comment, Divider, Popconfirm, Space, Timeline } from 'antd';
import Link from 'antd/lib/typography/Link';
import type { CSSProperties } from 'react';
import { useIntl, useModel, useRequest } from 'umi';
import MentionText from '../MentionText';
import { getFeishuUserDetail } from '../server';
import TimeFromNow from '../TimeFromNow';
import UserLink from '../UserInfo/link';
import lessStyle from './index.less';

const styles: Record<'divider' | 'span' | 'userWrap' | 'avatar' | 'title', CSSProperties> = {
  divider: {
    margin: 0,
    backgroundColor: 'rgba(0,0,0,0.1)',
  },
  span: {
    whiteSpace: 'nowrap',
  },
  userWrap: {
    display: 'contents',
  },
  avatar: {
    color: '#f56a00',
    backgroundColor: '#fde3cf',
  },
  title: {
    whiteSpace: 'nowrap',
    color: 'rgba(0,0,0,0.3)',
  },
};

export interface ReasonDataType {
  user: any;
  content: string;
  isDeleted: boolean;
  deletedAt: number;
  createdAt: number;
  id: number;
}

export interface ReasonItemProps extends ReasonDataType {
  initiator?: any;
  index: number;
  length: number;
  fold?: boolean;
  canFold?: boolean;
  restLength?: number;
  readOnly?: boolean;
  onDelete: (id: number) => void;
  onFold?: () => void;
  onExpand?: () => void;
}

const ReasonItem = (props: ReasonItemProps) => {
  const {
    user,
    content,
    isDeleted,
    deletedAt,
    createdAt,
    id: msgId,
    initiator,
    index,
    length,
    fold,
    canFold,
    restLength,
    readOnly,
    onDelete,
    onFold,
    onExpand,
  } = props;
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const { formatMessage } = useIntl();

  const { data: userData } = useRequest(
    () => {
      return getFeishuUserDetail({ userId: user.id });
    },
    {
      ready: Boolean(user.id),
      cacheKey: `getFeishuUserDetail-${user.id}`,
      refreshDeps: [user.id],
      cacheTime: 3 * 60 * 1000,
      staleTime: 2 * 60 * 1000,
    },
  );

  const discard = isDeleted
    ? formatMessage({ id: 'component.AuditList.reason.deleted' })
    : undefined;
  const lastItem = index === length - 1;

  return (
    <Timeline.Item
      className={lastItem ? lessStyle.timelineEndItem : ''}
      dot={
        <Avatar size={'small'} src={userData?.avatar?.avatar_72} style={styles.avatar}>
          {String(user.nameZh || user.account)
            .slice(0, 1)
            .toLocaleUpperCase()}
        </Avatar>
      }
    >
      <Comment
        className={lessStyle.reasonItem}
        author={<UserLink user={user} bracket={'en'} />}
        content={<MentionText text={content} discard={discard} />}
        datetime={
          <Space split={<Divider type={'vertical'} style={styles.divider} />}>
            {Boolean(index === 0 && initiator?.id) && (
              <span style={styles.title}>
                (<UserLink user={initiator} bracket={'en'} userWrapStyle={styles.userWrap} />
                &nbsp;
                {formatMessage({ id: 'base.proxy.apply' })})
              </span>
            )}

            <TimeFromNow style={styles.title} time={(isDeleted ? deletedAt : createdAt) * 1000} />

            {!isDeleted && currentUser?.id === user?.id && msgId !== 0 && !readOnly && (
              <Popconfirm
                title={formatMessage({ id: 'component.AuditList.reason.del.tips' })}
                onConfirm={() => onDelete(msgId)}
              >
                <Link style={styles.span}>{formatMessage({ id: 'base.common.del' })}</Link>
              </Popconfirm>
            )}

            {lastItem && canFold && (
              <Link style={styles.span} onClick={fold ? onExpand : onFold}>
                {formatMessage({ id: `base.common.${fold ? 'expand.more' : 'collapse'}` })}
                {fold && `(${restLength ?? 0})`}
                {fold ? <CaretDownOutlined /> : <CaretUpOutlined />}
              </Link>
            )}
          </Space>
        }
      />
    </Timeline.Item>
  );
};

export default ReasonItem;
