import React, { useMemo, lazy, Suspense, useEffect } from 'react'
import { Container } from '@/components/shared'
import { Helmet } from 'react-helmet'
import { useLocalization } from '@/utils/hooks/useLocalization'
import { useParams, useLocation } from 'react-router-dom'
import { RequestOptions } from 'devexpress-reporting-react/dx-report-viewer'
import { APP_NAME } from '@/constants/app.constant'

// Lazy load
const ReportViewer = lazy(() =>
  import('devexpress-reporting-react/dx-report-viewer')
)

const loadViewerCss = () => {
  const styles = [
    new URL('@devexpress/analytics-core/dist/css/dx-analytics.common.css', import.meta.url).href,
    new URL('@devexpress/analytics-core/dist/css/dx-analytics.light.css', import.meta.url).href,
    new URL('devexpress-reporting/dist/css/dx-webdocumentviewer.css', import.meta.url).href,
  ]

  styles.forEach((href) => {
    if (document.querySelector(`link[href="${href}"]`)) return
    const link = document.createElement('link')
    link.rel = 'stylesheet'
    link.href = href
    document.head.appendChild(link)
  })
}

const DevexpressReportViewer: React.FC = () => {
  const { translate } = useLocalization()
  const { id } = useParams<{ id: string }>()
  const location = useLocation()

  useEffect(() => {
    loadViewerCss()
  }, [])

  const reportUrlWithParams = useMemo(() => {
    if (!id) return ''
    return location.search ? `${id}${location.search}` : id
  }, [id, location.search])

  if (!id) return null

  return (
    <Container>
      <Helmet
        titleTemplate={`%s | ${APP_NAME}`}
        title={translate('::App.Reports')}
        defaultTitle={APP_NAME}
      />

      <Suspense fallback={<div>Rapor yükleniyor...</div>}>
        <ReportViewer reportUrl={reportUrlWithParams}>
          <RequestOptions
            host={`${import.meta.env.VITE_API_URL}/`}
            invokeAction="DXXRDV"
          />
        </ReportViewer>
      </Suspense>
    </Container>
  )
}

export default DevexpressReportViewer
