import {useCallback, useState} from 'react'

import {
  ContentVisibility,
  Content,
  ContentCreateUserErrors,
} from '@shopify/shop-minis-platform'

import {useHandleAction} from '../../internal/useHandleAction'
import {useShopActions} from '../../internal/useShopActions'
import {useImageUpload} from '../storage/useImageUpload'

interface CreateImageContentParams {
  image: File
  contentTitle: string
  visibility?: ContentVisibility[] | null
}

interface UseCreateImageContentReturns {
  /**
   * Upload an image and create content.
   */
  createImageContent: (
    params: CreateImageContentParams
  ) => Promise<{data: Content; userErrors?: ContentCreateUserErrors[]}>
  /**
   * Whether the content is being created.
   */
  loading: boolean
}

export const useCreateImageContent = (): UseCreateImageContentReturns => {
  const {createContent} = useShopActions()
  const {uploadImage} = useImageUpload()
  const [loading, setLoading] = useState(false)

  const createImageContent = useCallback(
    async (params: CreateImageContentParams) => {
      setLoading(true)

      const {image, contentTitle, visibility} = params

      if (!image.type) {
        throw new Error('Unable to determine file type')
      }
      if (!image.type.startsWith('image/')) {
        throw new Error('Invalid file type: must be an image')
      }

      const [uploadImageResult] = await uploadImage(image)
      const uploadImageUrl = uploadImageResult.imageUrl

      if (!uploadImageUrl) {
        throw new Error('Image upload failed')
      }

      const createContentResult = await createContent({
        title: contentTitle,
        imageUrl: uploadImageUrl,
        visibility,
      })

      setLoading(false)

      return createContentResult
    },
    [createContent, uploadImage]
  )

  return {
    createImageContent: useHandleAction(createImageContent),
    loading,
  }
}
