import { File } from './FileProps';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { useState } from 'react';

export const useDownloadFile = ({ file }: { file: File }) => {
  const {
    httpClient,
    window,
    errorHandler: { withErrorHandler, showError },
    translate: t,
  } = useWixPatternsContainer();

  const [isDownloading, setIsDownloading] = useState(false);

  const downloadFile = async () => {
    try {
      setIsDownloading(true);

      const { generateFileDownloadUrl } = await import(
        '@wix/bex-utils/@wix/ambassador-media-site-media-v1-file-descriptor/http'
      );

      const { data } = await withErrorHandler(
        () =>
          httpClient.request(generateFileDownloadUrl({ fileId: file.mediaId })),
        {
          INVALID_ASSET_KEY: false,
        },
      );

      const downloadableUrl = data.downloadUrls?.[0]?.url;

      if (!downloadableUrl) {
        throw new Error(t('cairo.downloadable-url.error.generic'));
      }

      window.download(downloadableUrl, file.displayName);
    } catch (error) {
      showError?.(error);
    } finally {
      setIsDownloading(false);
    }
  };

  return { downloadFile, isDownloading };
};
