import React from 'react';
import classNames from 'classnames';
import {
  Avatar,
  Box,
  Header,
  Icon,
  IconButton,
  Icons,
  MenuItem,
  Scroll,
  Text,
  as,
  config,
} from 'folds';
import { Room } from 'matrix-js-sdk';
import { useRoomEventReaders } from '../../hooks/useRoomEventReaders';
import * as css from './EventReaders.css';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { UserAvatar } from '../user-avatar';
import { useMemberAvatar } from '../../hooks/useMemberAvatar';
import { useOpenUserRoomProfile } from '../../state/hooks/userRoomProfile';
import { useSpaceOptionally } from '../../hooks/useSpace';
import { getMouseEventCords } from '../../utils/dom';
import { useSetting } from '../../state/hooks/settings';
import { settingsAtom } from '../../state/settings';
import { today, yesterday, timeHourMinute, timeMon, timeDay, timeYear } from '../../utils/time';

function formatReadTs(ts: number, hour24Clock: boolean): string {
  const timeStr = timeHourMinute(ts, hour24Clock);
  if (today(ts)) return `Today at ${timeStr}`;
  if (yesterday(ts)) return `Yesterday at ${timeStr}`;
  const sameYear = timeYear(ts) === timeYear(Date.now());
  return sameYear
    ? `${timeMon(ts)} ${timeDay(ts)} at ${timeStr}`
    : `${timeMon(ts)} ${timeDay(ts)} ${timeYear(ts)} at ${timeStr}`;
}

type EventReaderItemProps = {
  room: Room;
  readerId: string;
  hour24Clock: boolean;
  lotusTerminal: boolean;
  onSelect: React.MouseEventHandler<HTMLButtonElement>;
};
function EventReaderItem({
  room,
  readerId,
  hour24Clock,
  lotusTerminal,
  onSelect,
}: EventReaderItemProps) {
  const { name, avatarUrl } = useMemberAvatar(room, readerId, 100, 100);
  const receiptTs = room.getReadReceiptForUserId(readerId)?.data.ts;

  return (
    <MenuItem
      style={{ padding: `0 ${config.space.S200}` }}
      radii="400"
      onClick={onSelect}
      before={
        <Avatar size="200">
          <UserAvatar
            userId={readerId}
            src={avatarUrl}
            alt={name}
            renderFallback={() => <Icon size="50" src={Icons.User} filled />}
          />
        </Avatar>
      }
    >
      <Box direction="Column" grow="Yes">
        <Text size="T400" truncate>
          {name}
        </Text>
        {receiptTs !== undefined && (
          <Text
            size="T200"
            priority="300"
            style={
              lotusTerminal
                ? {
                    color: 'var(--lt-accent-amber)',
                    textShadow: 'var(--lt-glow-amber)',
                  }
                : undefined
            }
          >
            {formatReadTs(receiptTs, hour24Clock)}
          </Text>
        )}
      </Box>
    </MenuItem>
  );
}

export type EventReadersProps = {
  room: Room;
  eventId: string;
  requestClose: () => void;
};
export const EventReaders = as<'div', EventReadersProps>(
  ({ className, room, eventId, requestClose, ...props }, ref) => {
    const mx = useMatrixClient();
    const myUserId = mx.getUserId();
    const latestEventReaders = useRoomEventReaders(room, eventId).filter((id) => id !== myUserId);
    const openProfile = useOpenUserRoomProfile();
    const space = useSpaceOptionally();
    const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock');
    const [lotusTerminal] = useSetting(settingsAtom, 'lotusTerminal');

    return (
      <Box
        className={classNames(css.EventReaders, className)}
        direction="Column"
        {...props}
        ref={ref}
      >
        <Header
          className={css.Header}
          variant="Surface"
          size="500"
          style={
            lotusTerminal
              ? {
                  borderBottomWidth: config.borderWidth.B300,
                  boxShadow: 'var(--lt-box-glow-cyan)',
                }
              : undefined
          }
        >
          <Box grow="Yes">
            <Text
              size="H3"
              style={
                lotusTerminal
                  ? {
                      color: 'var(--lt-accent-cyan)',
                      textShadow: 'var(--lt-glow-cyan)',
                      letterSpacing: '0.05em',
                    }
                  : undefined
              }
            >
              Seen by
            </Text>
          </Box>
          <IconButton size="300" radii="300" onClick={requestClose} aria-label="Close">
            <Icon src={Icons.Cross} />
          </IconButton>
        </Header>
        <Box grow="Yes">
          <Scroll visibility="Hover" hideTrack size="300">
            <Box className={css.Content} direction="Column">
              {latestEventReaders.map((readerId) => (
                <EventReaderItem
                  key={readerId}
                  room={room}
                  readerId={readerId}
                  hour24Clock={hour24Clock}
                  lotusTerminal={lotusTerminal}
                  onSelect={(event) => {
                    openProfile(
                      room.roomId,
                      space?.roomId,
                      readerId,
                      getMouseEventCords(event.nativeEvent),
                      'Bottom',
                    );
                  }}
                />
              ))}
            </Box>
          </Scroll>
        </Box>
      </Box>
    );
  },
);
