'use client';

import { CollectionAccessType, type Collection } from '@/api-client';
import { getRecordKey } from '@/lib/utils/atproto';
import { getRelativeTime } from '@/lib/utils/time';
import { Card, Group, Stack, Text } from '@mantine/core';
import CollectionCardPreview from '../collectionCardPreview/CollectionCardPreview';
import { Suspense } from 'react';
import CollectionCardPreviewSkeleton from '../collectionCardPreview/Skeleton.CollectionCardPreview';
import { useUserSettings } from '@/features/settings/lib/queries/useUserSettings';
import CollectionCardDebugView from '../collectionCardDebugView/CollectionCardDebugView';
import { useRouter } from 'next/navigation';
import { MouseEvent } from 'react';
import { isMarginUri, getMarginUrl } from '@/lib/utils/margin';
import MarginLogo from '@/components/MarginLogo';
import { LinkAvatar } from '@/components/link/MantineLink';
import styles from './CollectionCard.module.css';

interface Props {
  size?: 'large' | 'compact' | 'list' | 'basic';
  showAuthor?: boolean;
  collection: Collection;
}

export default function CollectionCard(props: Props) {
  const { collection } = props;
  const rkey = getRecordKey(collection.uri!!);
  const time = getRelativeTime(collection.updatedAt);
  const accessType = collection.accessType;
  const { settings } = useUserSettings();
  const router = useRouter();
  const marginUrl = getMarginUrl(collection.uri, collection.author.handle);

  const handleNavigateToCollection = (e: MouseEvent<HTMLElement>) => {
    e.stopPropagation();

    const targetUrl = `/profile/${collection.author.handle}/collections/${rkey}`;

    // Open in new tab if Cmd+Click (Mac), Ctrl+Click (Windows/Linux), or middle click
    if (e.metaKey || e.ctrlKey || e.button === 1) {
      window.open(targetUrl, '_blank', 'noopener,noreferrer');
      return;
    }

    router.push(targetUrl);
  };

  const handleAuxClick = (e: MouseEvent<HTMLElement>) => {
    // Handle middle mouse button (button 1)
    if (e.button === 1) {
      handleNavigateToCollection(e);
    }
  };

  return (
    <Card
      withBorder
      radius={'lg'}
      p={'sm'}
      className={styles.root}
      h={'100%'}
      onClick={handleNavigateToCollection}
      onAuxClick={handleAuxClick}
    >
      <Stack justify="space-between" h="100%">
        <Stack gap={'xs'}>
          <Stack gap={0}>
            <Group justify="space-between" wrap="nowrap">
              <Group gap={4}>
                <Text
                  fw={500}
                  lineClamp={1}
                  c={
                    accessType === CollectionAccessType.OPEN
                      ? 'green'
                      : 'bright'
                  }
                >
                  {collection.name}
                </Text>
                {isMarginUri(collection.uri) && (
                  <MarginLogo size={14} marginUrl={marginUrl} />
                )}
              </Group>

              {props.showAuthor && (
                <LinkAvatar
                  href={`/profile/${collection.author.handle}`}
                  src={collection.author.avatarUrl?.replace(
                    'avatar',
                    'avatar_thumbnail',
                  )}
                  alt={`${collection.author.handle}'s avatar`}
                  size={'sm'}
                />
              )}
            </Group>
            {collection.description && (
              <Text fz={'sm'} c={'gray'} lineClamp={3}>
                {collection.description}
              </Text>
            )}
          </Stack>

          {settings.collectionView === 'grid' && (
            <Suspense fallback={<CollectionCardPreviewSkeleton />}>
              <CollectionCardPreview
                rkey={rkey}
                handle={props.collection.author.handle}
              />
            </Suspense>
          )}

          {settings.tinkerMode && (
            <CollectionCardDebugView collection={props.collection} />
          )}
        </Stack>

        <Group justify="space-between" gap={'xs'}>
          <Text c={'gray'} fz={'sm'}>
            {collection.cardCount}{' '}
            {collection.cardCount === 1 ? 'card' : 'cards'}
          </Text>
          <Text c={'gray'} fz={'sm'}>
            {time}
          </Text>
        </Group>
      </Stack>
    </Card>
  );
}
