import React, { useMemo, useEffect, useState } 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 ReportViewer, {
  RequestOptions,
} from 'devexpress-reporting-react/dx-report-viewer'
import { ajaxSetup } from '@devexpress/analytics-core/analytics-utils-native'
import { APP_NAME } from '@/constants/app.constant'
import { useStoreState } from '@/store'

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()
  const token = useStoreState((state) => state.auth.session.token)
  const [isRequestAuthReady, setIsRequestAuthReady] = useState(false)

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

  useEffect(() => {
    setIsRequestAuthReady(false)
    const authorization = token ? `Bearer ${token}` : undefined

    const ajaxHeaders = ajaxSetup.ajaxSettings.headers ?? {}

    if (authorization) {
      ajaxSetup.ajaxSettings.headers = {
        ...ajaxHeaders,
        Authorization: authorization,
      }
      setIsRequestAuthReady(true)
      return
    }

    const { Authorization: _ajaxAuthorization, ...nextAjaxHeaders } = ajaxHeaders
    ajaxSetup.ajaxSettings.headers = nextAjaxHeaders
    setIsRequestAuthReady(true)
  }, [token])

  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}
      />

      {isRequestAuthReady && (
        <ReportViewer reportUrl={reportUrlWithParams}>
          <RequestOptions
            host={import.meta.env.VITE_API_URL}
            invokeAction="/DXXRDV"
          />
        </ReportViewer>
      )}
    </Container>
  )
}

export default DevexpressReportViewer
