import { useMemo } from 'react';

import ErrorText from '~/src/components/ErrorText';
import { useAppAlert } from '~/src/components/NextApp/lib/CoreUi';
import useFetchSessionUser from '~/src/hooks/useFetchSessionUser';
import { useTracker } from '~/src/lib/tracker/useTracker';
import uploadImage from './uploadImage';

/**
 * Upload image with added event tracking and error handling.
 */
const useUploadImage = ({ trackingId }: { trackingId: string }) => {
  const { trackEvent } = useTracker();
  const { userAccountId } = useFetchSessionUser();
  const appAlert = useAppAlert();

  return useMemo(
    () => ({
      uploadImage: async (params: Parameters<typeof uploadImage>[0]) => {
        try {
          const result = await uploadImage({
            ...params,
            accountId: userAccountId,
          });

          trackEvent({
            type: 'upload-image',
            subType: trackingId,
            format: params.file.type,
            imageUrl: result.url,
          });

          return result;
        } catch (error) {
          appAlert({
            title: 'Error uploading image',
            content: <ErrorText error={error} />,
          });

          throw error;
        }
      },
    }),
    []
  );
};

export default useUploadImage;
