import React, { useEffect, useRef, useState } from 'react'
import { checkFileExists } from '../services/file-services'
import Image from 'next/image'
import { useMerchant } from '../context/MerchantContext'

interface FileViewerProps {
  url: string
}

const FileViewer: React.FC<FileViewerProps> = (props) => {
  const embedRef = useRef<HTMLEmbedElement>(null)
  const { merchant } = useMerchant()
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  // Helper function to get file type from URL extension
  const getFileTypeFromUrl = (url: string): string => {
    const extension = url.split('.').pop()?.toLowerCase()

    switch (extension) {
      case 'pdf':
        return 'pdf'
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif':
      case 'bmp':
      case 'webp':
      case 'svg':
        return 'image'
      default:
        return 'unknown'
    }
  }

  const fileType = getFileTypeFromUrl(props.url)

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

        await checkFileExists({
          merchantId: merchant?.id as number,
          url: props.url,
        })

        setError(null)
      } catch {
        setError('Error Loading Payment Proof')
      } finally {
        setLoading(false)
      }
    }

    fetchFileUrl()
  }, [props.url, merchant])

  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">
        {fileType === 'pdf' ? (
          <embed
            src={props.url}
            ref={embedRef}
            className="w-full h-96 transition-transform duration-200"
            type="application/pdf"
          />
        ) : fileType === 'image' ? (
          <Image
            src={props.url}
            height={500}
            width={500}
            alt="File preview"
            className="w-full h-full object-cover"
          />
        ) : (
          <div className="text-gray-500">Unsupported file type</div>
        )}
      </div>
    </div>
  )
}

export default FileViewer
