import { type FC } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

import { IconEdit } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';

import { logEvent } from 'src/config/logging';
import { useAuth } from 'src/contexts/JWTContext';
import useGeneralError from 'src/hooks/useGeneralError';
import MarketplacePostAddDrawer from 'src/pages/dashboard/marketplace/components/MarketplacePostAddDrawer';
import { pushMarketplaceListData } from 'src/pages/dashboard/marketplace/queries';
import { createMarketplacePost } from 'src/services/marketplace';
import { EventName } from 'src/types/amplitude';
import { type MarketplacePost } from 'src/types/marketplace';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import ProfilePicture from 'src/components/user/ProfilePicture';

export const MarketplacePostAddButton: FC = () => {
  const { t } = useTranslation(['marketplace', 'general']);
  const { user } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const showGeneralError = useGeneralError();

  const handleClick = () => {
    navigate('#add');
  };

  const handleCancel = () => {
    navigate('');
  };

  const handleSuccess = (post: MarketplacePost) => {
    logEvent(EventName.POST_MARKETPLACE_CREATE, { postId: post?.id });

    pushMarketplaceListData(post);
    navigate('');
  };

  const handleError = (error: unknown) => {
    showGeneralError(error, t('marketplace:error_create_post'));
  };

  if (!user) return null;

  return (
    <>
      <HuCardContainer fullWidth>
        <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}>
          <ProfilePicture
            id={user.id}
            user={user}
            withLink
          />
          <Button
            onClick={handleClick}
            variant="outlined"
            startIcon={<IconEdit />}
            sx={{ width: '100%' }}
          >
            {t('marketplace:marketplace_create_post')}
          </Button>
        </Stack>
      </HuCardContainer>
      <MarketplacePostAddDrawer
        request={createMarketplacePost}
        open={location.hash === '#add'}
        onCancel={handleCancel}
        onSuccess={handleSuccess}
        onError={handleError}
      />
    </>
  );
};

export default MarketplacePostAddButton;
