import React from 'react';
import { Badge, Box, Chip, Icon, Icons, Text, config } from 'folds';
import { MatrixEvent, Room } from 'matrix-js-sdk';
import { MobileTouchTarget } from '../../../styles/mobile.css';
import { useThreadSummary } from '../../../hooks/useThreadSummary';
import { useSetting } from '../../../state/hooks/settings';
import { settingsAtom } from '../../../state/settings';
import { timeDayMonthYear, timeHourMinute, today } from '../../../utils/time';
import { ThreadNotificationMode } from '../../../utils/threadNotifications';

type ThreadSummaryProps = {
  rootEvent: MatrixEvent;
  room: Room;
  onOpen: (threadId: string) => void;
};
export function ThreadSummary({ rootEvent, room, onOpen }: ThreadSummaryProps) {
  const { summary, unread, mode } = useThreadSummary(rootEvent, room);
  const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock');

  if (!summary || summary.count === 0) return null;

  const { count, latestTs } = summary;
  const latestStr =
    latestTs !== undefined
      ? today(latestTs)
        ? timeHourMinute(latestTs, hour24Clock)
        : timeDayMonthYear(latestTs)
      : undefined;

  return (
    <Box style={{ marginTop: config.space.S200 }}>
      <Chip
        variant="SurfaceVariant"
        radii="300"
        className={MobileTouchTarget}
        before={<Icon size="50" src={Icons.Thread} />}
        after={
          unread > 0 ? <Badge variant="Success" fill="Solid" radii="Pill" size="200" /> : undefined
        }
        onClick={() => {
          const threadId = rootEvent.getId();
          if (threadId) onOpen(threadId);
        }}
      >
        <Text size="T200">
          {count === 1 ? '1 reply' : `${count} replies`}
          {latestStr ? ` · ${latestStr}` : ''}
        </Text>
        {mode === ThreadNotificationMode.Mute && <Icon size="50" src={Icons.BellMute} />}
      </Chip>
    </Box>
  );
}
