import { lookup } from 'mime-types'
import path from 'path'
import { useEffect, useState } from 'react'
import { defaultImage } from '../utils'

export const useFile = (customSrc?: string) => {
  const [imageFile, setImageFile] = useState<File>()
  const [imageBase64, setImageBase64] = useState<string>()

  const convertToFile = async (src: string, callback?: (file: File) => void) => {
    return fetch(src)
      .then(response => response.blob())
      .then(blob => {
        const reader = new FileReader()
        reader.onload = () => {
          const base64 = reader.result as string
          const fileName = path.basename(src)
          const file = base64ToFile(base64, fileName) // Move initialization here
          if (callback) callback(file)
        }
        reader.readAsDataURL(blob)
      })
  }

  const convertToBase64 = async (src: string, p0?: (base64: any) => void): Promise<string> => {
    const response = await fetch(src)
    const blob = await response.blob()
    const reader = new FileReader()

    return new Promise(resolve => {
      reader.onload = () => {
        resolve(reader.result as string) // Resolve inside onload
      }
      reader.readAsDataURL(blob)
    })
  }

  useEffect(() => {
    const convert = async () => {
      await convertToFile(customSrc ?? defaultImage, file => {
        setImageFile(file)
      })
      await convertToBase64(customSrc ?? defaultImage, base64 => {
        setImageBase64(base64)
      })
    }
    convert()
  }, [customSrc])

  function base64ToFile(base64data: string, filename: string) {
    const byteCharacters = atob(base64data?.split(',')[1])
    const byteNumbers = new Array(byteCharacters.length)
    for (let i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i)
    }
    const byteArray = new Uint8Array(byteNumbers)
    const mimeType = lookup(filename)
    const file = new File([byteArray], filename, {
      type: mimeType ? mimeType : 'image/png'
    })

    return file
  }

  return { imageBase64, imageFile, convertToFile, convertToBase64 }
}
