'use client';

import { AppBskyFeedDefs, AppBskyFeedPost } from '@atproto/api';
import { ReactElement } from 'react';
import { Group, Stack, Text, Box, Anchor, Tooltip, Alert } from '@mantine/core';
import RichTextRenderer from '@/components/contentDisplay/richTextRenderer/RichTextRenderer';
import useGetBlueskyPost from '../../lib/queries/useGetBlueskyPost';
import PostEmbed from '../postEmbed/PostEmbed';
import ContentHider from '../contentHider/ContentHider';
import {
  getPostModerationUI,
  getModerationReasonText,
} from '../../lib/moderation';

import BotLabel from '@/features/profile/components/botLabel/BotLabel';
import { isBotAccount } from '../../lib/utils/account';
import { detectUrlPlatform, SupportedPlatform } from '@/lib/utils/link';
import { getPostUriFromUrl } from '@/lib/utils/atproto';
import BlueskyPlatformIcon from '../blueskyPlatformIcon/BlueskyPlatformIcon';
import { useUserSettings } from '@/features/settings/lib/queries/useUserSettings';
import { LinkAvatar } from '@/components/link/MantineLink';

interface Props {
  url: string;
  fallbackCardContent: ReactElement;
}

export default function BlueskyPost(props: Props) {
  const { settings } = useUserSettings();
  const uri = getPostUriFromUrl(props.url);
  const { data } = useGetBlueskyPost({ uri });
  const showEmbed = settings.cardView === 'grid';
  const platform = detectUrlPlatform(props.url);
  const platformIcon = <BlueskyPlatformIcon platform={platform.type} />;

  if (!data) {
    return (
      <Stack justify="space-between" gap="xs">
        <Group gap="xs" justify="flex-end" wrap="nowrap" w={'100%'}>
          <Tooltip
            label={`View on ${platform.type === SupportedPlatform.BLUESKY_POST ? 'Bluesky' : 'Blacksky'}`}
          >
            <Anchor
              href={props.url}
              target="_blank"
              onClick={(e) => e.stopPropagation()}
            >
              {platformIcon}
            </Anchor>
          </Tooltip>
        </Group>
        <Alert
          component={'button'}
          variant="transparent"
          mx={'auto'}
          color="gray"
          p={'sm'}
          title="Post not found"
          style={{ cursor: 'pointer' }}
        />
      </Stack>
    );
  }

  if (
    !data.thread ||
    !AppBskyFeedDefs.isThreadViewPost(data.thread) ||
    AppBskyFeedDefs.isBlockedPost(data.thread.post)
  ) {
    return props.fallbackCardContent;
  }

  const post = data.thread.post;
  const record = post.record as AppBskyFeedPost.Record;
  const moderation = getPostModerationUI(post);

  if (moderation.filter) {
    return props.fallbackCardContent;
  }

  return (
    <Stack justify="space-between" gap="xs">
      <Group gap="xs" justify="space-between" wrap="nowrap" w={'100%'}>
        <Group gap={'xs'} wrap="nowrap">
          <LinkAvatar
            href={`https://bsky.app/profile/${post.author.handle}`}
            src={post.author.avatar?.replace('avatar', 'avatar_thumbnail')}
            alt={`${post.author.handle} avatar`}
            size={'sm'}
            radius="xl"
            onClick={(e) => e.stopPropagation()}
          />

          <Text c="bright" lineClamp={1} fw={500}>
            {post.author.displayName || post.author.handle}
          </Text>
          {isBotAccount(post.author) && <BotLabel />}
        </Group>
        <Tooltip
          label={`View on ${platform.type === SupportedPlatform.BLUESKY_POST ? 'Bluesky' : 'Blacksky'}`}
        >
          <Anchor
            href={props.url}
            target="_blank"
            onClick={(e) => e.stopPropagation()}
          >
            {platformIcon}
          </Anchor>
        </Tooltip>
      </Group>
      <ContentHider
        blur={moderation.blur}
        noOverride={moderation.noOverride}
        reason={getModerationReasonText(moderation)}
      >
        <Stack gap={'xs'} w={'100%'}>
          <Box>
            <RichTextRenderer
              text={record.text}
              textProps={{ lineClamp: settings.cardView === 'grid' ? 3 : 1 }}
            />
          </Box>
          {post.embed && showEmbed && <PostEmbed embed={post.embed} />}
        </Stack>
      </ContentHider>
    </Stack>
  );
}
