import React, {useMemo} from 'react';
import {View} from 'react-native';
import {
  DatePill,
  DefaultMessage as DefaultMessageRenderer,
} from '@modules/chats/components';
import {DatePillMessage, ExtendedMessageType} from '@modules/chats/interfaces';
import type {DefaultMessage} from '@modules/chats/interfaces';
import {getLocalizedDateLabelByTs} from '@modules/chats/utils';

import {styles} from './styles';

interface Props {
  message: DefaultMessage;
}

export function Message({message}: Props) {
  const datePillItem = useMemo((): Nullable<DatePillMessage> => {
    const currentDate = message.data.ts
      ? getLocalizedDateLabelByTs(message.data.ts)
      : null;

    if (!currentDate) {
      return null;
    }

    return {
      extendedType: ExtendedMessageType.DatePill,
      useExtraMarginTop: true,
      data: {date: currentDate, version: 0},
      id: `date-pill-${message.data.ts}`,
      ts: message.ts,
      isChannel: true,
      isFirst: true,
    };
  }, [message.data.ts, message.ts]);

  return (
    <View style={styles.container}>
      {datePillItem && (
        <View style={styles.datePill}>
          <DatePill item={datePillItem} />
        </View>
      )}
      <DefaultMessageRenderer item={message} />
    </View>
  );
}
