import { FC, memo } from 'react';

import { useNavigate } from 'react-router-dom';

import { useAuth } from 'src/contexts/JWTContext';
import useGeneralError from 'src/hooks/useGeneralError';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import usePermissions from 'src/hooks/usePermissions';
import { createChat } from 'src/services/chats';
import { MarketplacePost } from 'src/types/marketplace';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';
import { canContact } from 'src/utils/marketplace';
import { UserPermissions } from 'src/utils/permissions';

import { chatRoutes } from 'src/components/dashboard/chat/routes';
import UnifiedPostCard from 'src/components/post/UnifiedPostCard/index';
import { NormalizedMarketplacePost } from 'src/components/post/UnifiedPostCard/types';

import { useOpenConversation } from '../../Conversations/hooks/useConversationsQueries';

export type MarketplacePostCardProps = MarketplacePost & {
  isDetail?: boolean;
  hideFeatures?: boolean;
  onAddReaction?: (id: number, emoji: string, unified: string) => void;
  onRemoveReaction?: (id: number, emoji: string) => void;
  matchText?: string;
};

/** Normalize MarketplacePost dates from Date to string */
const normalizePost = (post: MarketplacePost): NormalizedMarketplacePost => ({
  ...post,
  createdAt:
    post.createdAt instanceof Date
      ? post.createdAt.toISOString()
      : post.createdAt,
  updatedAt:
    post.updatedAt instanceof Date
      ? post.updatedAt.toISOString()
      : post.updatedAt,
  publicationDatetime:
    post.publicationDatetime instanceof Date
      ? post.publicationDatetime.toISOString()
      : post.publicationDatetime,
});

/**
 * Marketplace post card using UnifiedPostCard.
 * View tracking is handled at the list level via usePostsViewTracking.
 */
const MarketplacePostCard: FC<MarketplacePostCardProps> = memo(props => {
  const {
    isDetail = false,
    hideFeatures = false,
    onAddReaction,
    onRemoveReaction,
    matchText = '',
    ...postProps
  } = props;

  const { user } = postProps;
  const normalizedPost = normalizePost(postProps);

  const { user: loggedUser, permissions } = useAuth();
  const navigate = useNavigate();
  const showGeneralError = useGeneralError();
  const { t } = useTranslation(['marketplace', 'general']);

  const showContactUser = loggedUser
    ? canContact(loggedUser.id, user.id, permissions)
    : false;

  const { hasAll: canViewConversations } = usePermissions([
    UserPermissions.VIEW_CHATS_V2,
  ]);
  const openConversationMutation = useOpenConversation();

  const handleContact = async () => {
    if (canViewConversations) {
      openConversationMutation.mutateAsync({ users: [user.id.toString()] });
    } else {
      try {
        const { data: thread } = await createChat(user.id);

        const chatId = thread.chat.id;
        const state = {
          thread,
          message: t('marketplace:contact_message'),
        };

        navigate(chatRoutes.thread.detail(chatId), { state });
      } catch (err) {
        showGeneralError(err, t('general:error_creating_chat'));
      }
    }
  };

  return (
    <UnifiedPostCard
      context="marketplace"
      post={normalizedPost}
      isDetail={isDetail}
      hideFeatures={hideFeatures}
      matchText={matchText}
      showContact={showContactUser}
      onContact={handleContact}
      onAddReaction={onAddReaction}
      onRemoveReaction={onRemoveReaction}
    />
  );
});

MarketplacePostCard.displayName = 'MarketplacePostCard';

const MarketplacePostCardThemeProvider = (props: MarketplacePostCardProps) => {
  const HugoThemeProvider = useHuGoTheme();

  return (
    <HugoThemeProvider>
      <MarketplacePostCard {...props} />
    </HugoThemeProvider>
  );
};

export default MarketplacePostCardThemeProvider;
