'use client'

import { defaultImage } from '@/@core/utils'
import { ChangeEvent, Dispatch, SetStateAction, useState } from 'react'
export type TUseModal = {
  imgSrc: string
  setImgSrc: Dispatch<SetStateAction<string>>
  inputValue: any
  setInputValue: Dispatch<SetStateAction<string>>
  handleInputImageChange: (
    file: ChangeEvent<HTMLInputElement>,
    callback?: (event: ChangeEvent<HTMLInputElement>) => void
  ) => void
  handleInputImageReset: (src?: string) => void
}
const useUpload = (): TUseModal => {
  const [inputValue, setInputValue] = useState<string>('')
  const [imgSrc, setImgSrc] = useState<string>(defaultImage)
  const handleInputImageChange = (
    file: ChangeEvent<HTMLInputElement>,
    callback?: (event: ChangeEvent<HTMLInputElement>) => void
  ) => {
    const reader = new FileReader()
    const { files } = file.target as HTMLInputElement
    if (files && files.length !== 0) {
      // reader.onload = () => setImgSrc(reader.result as string)
      const objectUrl = URL.createObjectURL(files[0])

      reader.onload = () => setImgSrc(objectUrl)
      reader.readAsDataURL(files[0])

      if (reader.result !== null) {
        setInputValue(reader.result as string)
      }
    }
    if (callback) callback(file)
  }
  const handleInputImageReset = (src?: string) => {
    setInputValue('')
    setImgSrc(src ?? defaultImage)
  }
  return {
    imgSrc,
    setImgSrc,
    inputValue,
    setInputValue,
    handleInputImageChange,
    handleInputImageReset
  }
}

export default useUpload

// reader.onload = event => {
//   const img = new Image()
//   img.src = event.target.result as any

//   img.onload = () => {
//     if (img.width === 1285 && img.height === 475) {
//       setImgSrc(reader.result as string)
//     } else {
//       toast.error(t('you should choose image with 1285 x 475 dimensions'))
//     }
//   }
// }
