import S3 from '@uppy/aws-s3';
import Uppy from '@uppy/core';
import { useCallback } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { toast } from '@/components/toast/Toast';

const useUploadImageFile = () => {
  const { session } = useStores();
  const uploadFile = useCallback(
    async (file: any, type: 'file_upload', nameOverride?: string) => {
      return await new Promise<{
        uploadId: string;
        title: string;
        imageUrl: string;
        errorMessage?: string;
      }>((resolve, reject) => {
        let uploadId: string | null = null;

        const uppy = new Uppy({
          restrictions: {
            maxNumberOfFiles: 1,
            maxFileSize: 10 * 1024 * 1024,
          },
        }).use(S3, {
          getUploadParameters: async () => {
            const { data, error } = await session.apiClient.POST(
              '/api/uploads/image/',
              {
                body: {
                  extension: 'jpeg',
                },
              }
            );

            if (!data) {
              console.error('Failed to fetch upload parameters');
              throw new Error('Failed to fetch upload parameters');
            }

            if (error) {
              console.error('Error starting image upload:', error);
              throw new Error(`Upload parameter error: ${error}`);
            }

            uploadId = data?.id;

            return {
              url: data?.url,
              fields: data.fields as Record<string, string>,
            };
          },
        });

        uppy.on('upload-error', () => {
          toast({
            title: 'Image upload failed',
            description: 'Please try again.',
            status: 'error',
            duration: 4000,
            isClosable: true,
          });
          reject(new Error(`Upload failed`));
        });

        uppy.on('complete', (result) => {
          if (result.successful.length > 0 && uploadId) {
            resolve({
              uploadId,
              title: file.name || 'Uploaded Image',
              imageUrl: result.successful[0].uploadURL || '',
            });
          } else {
            reject(new Error('Upload completed but no successful files'));
          }
        });

        uppy.addFile({
          name: nameOverride || file.name,
          type: file.type,
          data: file,
        });

        uppy.upload();
      });
    },
    []
  );

  return uploadFile;
};

export default useUploadImageFile;
