import {useState} from 'react'
import {UseFormSetError, UseFormClearErrors, UseFormSetValue} from 'react-hook-form'

export const ALLOWED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
export const ALLOWED_VIDEO_TYPES = ['video/mp4', 'video/webm', 'video/ogg']

export const validateFileType = (file: File, mediaType: number) => {
  if (mediaType === 1 && !ALLOWED_IMAGE_TYPES.includes(file.type)) {
    return 'Для типа "Фото" разрешены только форматы: JPG, PNG, GIF, WEBP'
  }

  if (mediaType === 2 && !ALLOWED_VIDEO_TYPES.includes(file.type)) {
    return 'Для типа "Видео" разрешены только форматы: MP4, WEBM, OGG'
  }

  return null
}

type UseMediaFileUploadProps = {
  selectedMediaType: number
  setError: UseFormSetError<any>
  clearErrors: UseFormClearErrors<any>
  setValue: UseFormSetValue<any>
}

export const useMediaFileUpload = ({selectedMediaType, setError, clearErrors, setValue}: UseMediaFileUploadProps) => {
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [previewUrl, setPreviewUrl] = useState<string | null>(null)

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (!file) return

    if (selectedMediaType) {
      const error = validateFileType(file, selectedMediaType)
      if (error) {
        setError('file', {type: 'manual', message: error})
        event.target.value = ''
        return
      }
    }

    clearErrors('file')
    setValue('file', file)
    setSelectedFile(file)

    if (file.type.startsWith('image/')) {
      const url = URL.createObjectURL(file)
      setPreviewUrl(url)
    } else {
      setPreviewUrl(null)
    }
  }

  const handleMediaTypeChange = (newMediaType: number | null) => {
    setValue('media_type', newMediaType || null)

    if (selectedFile && newMediaType) {
      const error = validateFileType(selectedFile, newMediaType)
      if (error) {
        setError('file', {type: 'manual', message: error})
        setValue('file', null)
        setSelectedFile(null)
        setPreviewUrl(null)
      } else {
        clearErrors('file')
      }
    }
  }

  return {
    selectedFile,
    setSelectedFile,
    previewUrl,
    setPreviewUrl,
    handleFileChange,
    handleMediaTypeChange,
  }
}
