import React, { useContext } from 'react';
import { Text, View } from 'react-native';

import styles from './styles';
import MessageContext from './Context';
import ThreadDetails from '../ThreadDetails';
import I18n from '../../i18n';
import { type IMessageThread } from './interfaces';
import { useTheme } from '../../theme';
import Touchable from './Touchable';

const Thread = React.memo(
	({ msg, tcount, tlm, isThreadRoom, id }: IMessageThread) => {
		'use memo';

		const { theme, colors } = useTheme();
		const { threadBadgeColor, toggleFollowThread, user, replies, onThreadPress } = useContext(MessageContext);

		const backgroundColor = threadBadgeColor ? colors.badgeBackgroundLevel2 : colors.buttonBackgroundSecondaryDefault;
		const textColor = threadBadgeColor || theme !== 'light' ? colors.fontWhite : colors.fontPureBlack;

		if (!tlm || isThreadRoom || tcount === null) {
			return null;
		}

		return (
			<View style={styles.buttonContainer}>
				<Touchable
					onPress={onThreadPress}
					accessibilityRole='button'
					accessibilityLabel={I18n.t('View_Thread')}
					style={[styles.button, { backgroundColor }]}
					testID={`message-thread-button-${msg}`}>
					<Text style={[styles.buttonText, { color: textColor }]}>{I18n.t('View_Thread')}</Text>
				</Touchable>
				<ThreadDetails
					item={{
						tcount,
						replies,
						id
					}}
					user={user}
					badgeColor={threadBadgeColor}
					toggleFollowThread={toggleFollowThread}
					style={styles.threadDetails}
				/>
			</View>
		);
	},
	(prevProps, nextProps) => {
		if (prevProps.tcount !== nextProps.tcount) {
			return false;
		}
		return true;
	}
);

Thread.displayName = 'MessageThread';

export default Thread;
