import {
  Anchor,
  Card,
  Group,
  Menu,
  MenuDropdown,
  MenuTarget,
  ScrollArea,
  Spoiler,
  Stack,
  Text,
} from '@mantine/core';
import { ActivityType, Collection, CollectionAccessType } from '@/api-client';
import { User } from '@semble/types';
import { Fragment, ReactNode } from 'react';
import styles from './FeedActivityStatus.module.css';
import { getRelativeTime } from '@/lib/utils/time';
import { getRecordKey } from '@/lib/utils/atproto';
import { sanitizeText } from '@/lib/utils/text';
import {
  LinkAvatar,
  LinkMenuItem,
  LinkText,
} from '@/components/link/MantineLink';
import { isBotAccount } from '@/features/platforms/bluesky/lib/utils/account';
import BotLabel from '@/features/profile/components/botLabel/BotLabel';

interface Props {
  user: User;
  activityType: ActivityType;
  collections?: Collection[];
  createdAt: Date;
  note?: string;
  actions?: ReactNode;
}

export default function FeedActivityStatus(props: Props) {
  const MAX_DISPLAYED = 2;
  const time = getRelativeTime(props.createdAt.toString());
  const relativeCreatedDate = time === 'now' ? `Now` : time;

  const renderActivityText = () => {
    if (props.activityType === ActivityType.CONNECTION_CREATED) {
      return (
        <Text fw={500}>
          <Group
            component="span"
            gap={'xs'}
            wrap="nowrap"
            display={'inline-flex'}
          >
            <LinkText
              href={`/profile/${props.user.handle}`}
              fw={600}
              c={'bright'}
            >
              {sanitizeText(props.user.name)}
            </LinkText>
            {isBotAccount(props.user) && <BotLabel />}
          </Group>{' '}
          <Text span>made a connection</Text>
          <Text fz={'sm'} fw={600} c={'gray'} span display={'block'}>
            {relativeCreatedDate}
          </Text>
        </Text>
      );
    }

    const collections = props.collections ?? [];
    const displayedCollections = collections.slice(0, MAX_DISPLAYED);
    const remainingCollections = collections.slice(
      MAX_DISPLAYED,
      collections.length,
    );
    const remainingCount = collections.length - MAX_DISPLAYED;

    return (
      <Text fw={500}>
        <Group
          component="span"
          gap={'xs'}
          wrap="nowrap"
          display={'inline-flex'}
        >
          <LinkText
            href={`/profile/${props.user.handle}`}
            fw={600}
            c={'bright'}
          >
            {sanitizeText(props.user.name)}
          </LinkText>
          {isBotAccount(props.user) && <BotLabel />}
        </Group>{' '}
        {collections.length === 0 ? (
          <Text span>added to library</Text>
        ) : (
          <Fragment>
            <Text span>added to </Text>
            {displayedCollections.map(
              (collection: Collection, index: number) => (
                <span key={collection.id}>
                  <Anchor
                    href={`/profile/${collection.author.handle}/collections/${getRecordKey(collection.uri!)}`}
                    c={
                      collection.accessType === CollectionAccessType.OPEN
                        ? 'green'
                        : 'grape'
                    }
                    fw={500}
                  >
                    {collection.name}
                  </Anchor>
                  {index < displayedCollections.length - 1 ? ', ' : ''}
                </span>
              ),
            )}
            {remainingCount > 0 && <Text span>{' and '}</Text>}
            {remainingCount > 0 && (
              <Menu shadow="sm" position="bottom-start">
                <MenuTarget>
                  <Text
                    fw={600}
                    c={'gray'}
                    style={{ cursor: 'pointer', userSelect: 'none' }}
                    span
                  >
                    {remainingCount} other collection
                    {remainingCount > 1 ? 's' : ''}
                  </Text>
                </MenuTarget>
                <MenuDropdown maw={380}>
                  <ScrollArea.Autosize mah={150} type="auto">
                    {remainingCollections.map((c) => (
                      <LinkMenuItem
                        key={c.id}
                        href={`/profile/${c.author.handle}/collections/${getRecordKey(c.uri!)}`}
                        target="_blank"
                        c={
                          c.accessType === CollectionAccessType.OPEN
                            ? 'green'
                            : 'grape'
                        }
                        fw={600}
                      >
                        {c.name}
                      </LinkMenuItem>
                    ))}
                  </ScrollArea.Autosize>
                </MenuDropdown>
              </Menu>
            )}
          </Fragment>
        )}
        <Text fz={'sm'} fw={600} c={'gray'} span display={'block'}>
          {relativeCreatedDate}
        </Text>
      </Text>
    );
  };

  return (
    <Card p={0} className={styles.root} radius={'lg'}>
      <Stack gap={'xs'} p={'xs'}>
        <Group gap={'xs'} wrap="nowrap" align="center" justify="space-between">
          <Group gap={'xs'} wrap="nowrap" align="center">
            <LinkAvatar
              href={`/profile/${props.user.handle}`}
              src={props.user.avatarUrl?.replace('avatar', 'avatar_thumbnail')}
              alt={`${props.user.name}'s avatar`}
            />
            {renderActivityText()}
          </Group>
          {props.actions}
        </Group>
        {props.note && (
          <Spoiler
            showLabel={'Read more'}
            hideLabel={'See less'}
            maxHeight={100}
          >
            <Text fw={500} fs={'italic'} c={'gray'}>
              {props.note}
            </Text>
          </Spoiler>
        )}
      </Stack>
    </Card>
  );
}
