import { AxiosError } from 'axios'
import React, { useEffect, useRef, useState } from 'react'
import { Order } from '@/app/merchant-dashboard/[id]/orders/types'
import Image from 'next/image'
import { downloadPaymentProof } from '@/lib/services/order-services'
import { useMerchant } from '@/lib/context/MerchantContext'

interface FileViewerProps {
  order: Order
  proofID: number
  fileType: 'pdf' | 'image'
}

export default function FileViewer(props: FileViewerProps) {
  const { merchant } = useMerchant()
  const embedRef = useRef<HTMLEmbedElement>(null)
  const [blobUrl, setBlobUrl] = useState('')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  useEffect(() => {
    const fetchPaymentProof = async () => {
      try {
        setLoading(true)

        const paymentProofBlob = await downloadPaymentProof({
          merchantId: merchant?.id as number,
          orderId: props.order.id,
          proofId: props.proofID,
        })

        const blob = new Blob([paymentProofBlob], {
          type: props.fileType === 'pdf' ? 'application/pdf' : 'image/*',
        })
        const url = URL.createObjectURL(blob)
        setBlobUrl(url)
        setError(null)
      } catch (err) {
        if (err instanceof AxiosError) {
          setError(err.response?.data?.message || 'Error Loading Payment Proof')
        }

        console.error('Error loading Payment Proof:', err)
      } finally {
        setLoading(false)
      }
    }

    fetchPaymentProof()
  }, [props.proofID, props.fileType, props.order.id, merchant])

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

  if (loading) {
    return (
      <div className="w-full h-96 flex items-center justify-center bg-gray-50 rounded-lg">
        <div className="text-gray-500">Loading Payment Proof...</div>
      </div>
    )
  }

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

  return (
    <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">
        {props.fileType === 'pdf' ? (
          <embed
            src={blobUrl}
            ref={embedRef}
            className="w-full h-96 transition-transform duration-200"
            type="application/pdf"
          />
        ) : (
          <Image height={500} width={500} src={blobUrl} alt="Payment Proof" />
        )}
      </div>
    </div>
  )
}
