import { getUrlCards } from '@/features/cards/lib/dal';
import { Card, Group, ScrollAreaAutosize, Stack, Text } from '@mantine/core';
import { BiRightArrowAlt } from 'react-icons/bi';
import ActivityCard from '../activityCard/ActivityCard';
import ActivityCardSkeleton from '../activityCard/Skeleton.ActivityCard';
import { Suspense } from 'react';
import { unstable_cache } from 'next/cache';
import { LinkButton } from '@/components/link/MantineLink';

const getRecentActivity = unstable_cache(
  async () => {
    try {
      const results = await Promise.allSettled([
        getUrlCards('ronentk.me', { limit: 1 }),
        getUrlCards('wesleyfinck.org', { limit: 1 }),
        getUrlCards('pouriade.com', { limit: 1 }),
        getUrlCards('tynanpurdy.com', { limit: 1 }),
        getUrlCards('erlend.sh', { limit: 1 }),
        getUrlCards('bmann.ca', { limit: 1 }),
        getUrlCards('tgoerke.bsky.social', { limit: 1 }),
        getUrlCards('psingletary.com', { limit: 1 }),
      ]);

      return results
        .filter((result) => result.status === 'fulfilled')
        .flatMap((result) => result.value.cards)
        .sort(
          (a, b) =>
            new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),
        );
    } catch (err) {
      return null;
    }
  },
  ['recent-activity-cards'],
  {
    revalidate: 60 * 60 * 3, // every 3 hours
  },
);

export default async function RecentActivity() {
  const cards = await getRecentActivity();

  if (!cards) return null;

  return (
    <Card withBorder component="article" p="xs" radius="lg">
      <Stack gap="md">
        <Group gap="xs" justify="space-between">
          <Text fz="xl" fw={600}>
            Highlights from our community
          </Text>
          <LinkButton
            href="/explore"
            variant="light"
            color="grape"
            rightSection={<BiRightArrowAlt size={20} />}
          >
            Explore
          </LinkButton>
        </Group>

        <ScrollAreaAutosize type="auto" mah={{ base: 250, xs: 400 }}>
          <Stack gap="xl">
            {cards.map((c, i) => (
              <Suspense key={i} fallback={<ActivityCardSkeleton />}>
                <ActivityCard
                  id={c.id}
                  url={c.url}
                  uri={c.uri}
                  note={c.note}
                  cardAuthor={c.author}
                  cardContent={c.cardContent}
                  createdAt={c.createdAt}
                  urlLibraryCount={c.urlLibraryCount}
                />
              </Suspense>
            ))}
          </Stack>
        </ScrollAreaAutosize>
      </Stack>
    </Card>
  );
}
