import { ChatAttachmentModel } from '../../store'
import { useRef, useState } from 'react'

export const useChatAttachment = (
  attachment: ChatAttachmentModel,
  getAttachmentLocation: (fileId: string) => Promise<string | undefined>
) => {
  const anchorRef = useRef<HTMLAnchorElement>(null)
  const [isAttachmentLoading, setAttachmentLoading] = useState(false)
  const [hasAttachmentError, setAttachmentError] = useState(false)
  const [attachmentUrl, setAttachmentUrl] = useState('')

  const handleDownloadFailed = (error: Error) => {
    console.error(error)
    setAttachmentError(true)
  }

  const downloadAttachment = async () => {
    setAttachmentLoading(true)
    try {
      const url = await getAttachmentLocation(attachment.fileId)
      if (url && anchorRef && anchorRef.current) {
        setAttachmentUrl(url)
        anchorRef.current.href = url
        anchorRef.current.click()
      }
    } catch (error: any) {
      handleDownloadFailed(error)
    } finally {
      setAttachmentLoading(false)
    }
  }

  return {
    anchorRef,
    isAttachmentLoading,
    hasAttachmentError,
    attachmentUrl,
    downloadAttachment,
  }
}
