import { useEffect, useMemo, useState } from 'react'
import Image from 'next/image'
import { AxiosError } from 'axios'
import { Modal, ModalHeader } from 'flowbite-react'

import * as withdrawalServices from '@/lib/services/withdrawal-services'
import modalTheme from '@/lib/themes/modal'
import { Withdrawal } from '../types'

export interface TransferProofModalProps {
  withdrawal: Withdrawal | null
  transferProofModal: ModalState
  setTransferProofModal: React.Dispatch<React.SetStateAction<ModalState>>
}

export default function TransferProofModal({
  withdrawal,
  transferProofModal,
  setTransferProofModal,
}: TransferProofModalProps) {
  const [transferProofBlobUrl, setTransferProofBlobUrl] = useState<
    string | null
  >(null)
  const [isLoadingTransferProof, setIsLoadingTransferProof] = useState(false)
  const [transferProofErrorMessage, setTransferProofErrorMessage] = useState('')
  const fileType = useMemo(() => {
    return withdrawal?.transfer_proof?.split('.').pop()
  }, [withdrawal?.transfer_proof])

  useEffect(() => {
    const fetchTransferProof = async () => {
      try {
        setIsLoadingTransferProof(true)

        const transferProofBlob =
          await withdrawalServices.downloadTransferProof(withdrawal!.id)

        const blob = new Blob([transferProofBlob], {
          type: fileType === 'pdf' ? 'application/pdf' : 'image/*',
        })
        const transferProofUrl = URL.createObjectURL(blob)
        setTransferProofBlobUrl(transferProofUrl)
        setTransferProofErrorMessage('')
      } catch (err) {
        if (err instanceof AxiosError) {
          setTransferProofErrorMessage(
            err.response?.data?.message || 'Failed to load transfer proof.',
          )
        }

        console.error('Error loading transfer proof:', err)
      } finally {
        setIsLoadingTransferProof(false)
      }
    }

    if (transferProofModal.isOpened && withdrawal) {
      fetchTransferProof()
    }
  }, [withdrawal, transferProofModal, fileType])

  useEffect(() => {
    return () => {
      if (transferProofBlobUrl) {
        URL.revokeObjectURL(transferProofBlobUrl)
      }
    }
  }, [transferProofBlobUrl])

  return (
    <Modal
      position="center"
      theme={modalTheme.modal}
      dismissible
      show={transferProofModal.isOpened}
      onClose={() => setTransferProofModal({ type: 'view', isOpened: false })}
    >
      <ModalHeader>Transfer Proof - {withdrawal?.transfer_proof}</ModalHeader>

      <div className="mt-4 mb-4">
        {isLoadingTransferProof && (
          <div className="w-full h-96 flex items-center justify-center bg-gray-50 rounded-lg">
            <div className="text-gray-500">Loading Transfer Proof...</div>
          </div>
        )}

        {transferProofErrorMessage && (
          <div className="w-full h-96 flex items-center justify-center bg-gray-50 rounded-lg">
            <div className="text-red-500">{transferProofErrorMessage}</div>
          </div>
        )}

        {!isLoadingTransferProof && !transferProofErrorMessage && (
          <div className="flex flex-col items-center">
            <div className="w-full bg-gray-100 rounded-lg p-4 min-h-96 flex items-center justify-center">
              {fileType === 'pdf' ? (
                <embed
                  src={transferProofBlobUrl as string}
                  className="w-full h-96 transition-transform duration-200"
                  type="application/pdf"
                />
              ) : (
                <Image
                  height={500}
                  width={500}
                  src={transferProofBlobUrl as string}
                  alt="Payment Proof"
                />
              )}
            </div>
          </div>
        )}
      </div>
    </Modal>
  )
}
