import { Link } from '@tanstack/react-router';
import React from 'react';
import { FormattedMessage } from 'react-intl';

import GroupAvatar from '@/components/groups/group-avatar';
import HStack from '@/components/ui/hstack';
import Icon from '@/components/ui/icon';
import Stack from '@/components/ui/stack';
import Text from '@/components/ui/text';
import Emojify from '@/features/emoji/emojify';
import GroupActionButton from '@/features/group/components/group-action-button';
import { useGroupQuery } from '@/queries/groups/use-group';
import { shortNumberFormat } from '@/utils/numbers';

interface IGroupListItem {
  groupId: string;
  withJoinAction?: boolean;
}

const GroupListItem: React.FC<IGroupListItem> = ({ groupId, withJoinAction = true }) => {
  const { data: group } = useGroupQuery(groupId, true);

  if (!group) return null;

  return (
    <HStack alignItems='center' justifyContent='between' data-testid='group-list-item'>
      <Link
        key={group.id}
        to='/groups/$groupId'
        params={{ groupId: group.id }}
        className='overflow-hidden'
      >
        <HStack alignItems='center' space={2}>
          <GroupAvatar group={group} size={44} />

          <Stack className='overflow-hidden'>
            <Text weight='bold' truncate>
              <Emojify text={group.display_name} emojis={group.emojis} />
            </Text>

            <HStack className='text-gray-700 dark:text-gray-600' space={1} alignItems='center'>
              <Icon
                className='size-4.5'
                src={
                  group.locked
                    ? require('@phosphor-icons/core/regular/lock.svg')
                    : require('@phosphor-icons/core/regular/globe.svg')
                }
              />

              <Text theme='inherit' tag='span' size='sm' weight='medium'>
                {group.locked ? (
                  <FormattedMessage id='group.privacy.locked' defaultMessage='Private' />
                ) : (
                  <FormattedMessage id='group.privacy.public' defaultMessage='Public' />
                )}
              </Text>

              {typeof group.members_count !== 'undefined' && (
                <>
                  <span>&bull;</span>
                  <Text theme='inherit' tag='span' size='sm' weight='medium'>
                    {shortNumberFormat(group.members_count)}{' '}
                    <FormattedMessage
                      id='groups.discover.search.results.member_count'
                      defaultMessage='{members, plural, one {member} other {members}}'
                      values={{
                        members: group.members_count,
                      }}
                    />
                  </Text>
                </>
              )}
            </HStack>
          </Stack>
        </HStack>
      </Link>

      {withJoinAction && <GroupActionButton group={group} />}
    </HStack>
  );
};

export { GroupListItem as default };
