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

const ReportDesigner = lazy(() =>
  import('devexpress-reporting-react/dx-report-designer')
)

const loadDesignerCss = () => {
  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/analytics-core/dist/css/dx-querybuilder.css', import.meta.url).href,
    new URL('devexpress-reporting/dist/css/dx-webdocumentviewer.css', import.meta.url).href,
    new URL('devexpress-reporting/dist/css/dx-reportdesigner.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 DevexpressReportDesigner: React.FC = () => {
  const { translate } = useLocalization()
  const { id } = useParams<{ id: string }>()

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

  if (!id) return null

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

      <Suspense fallback={<div>Rapor tasarımcısı yükleniyor...</div>}>
        <ReportDesigner reportUrl={id}>
          <RequestOptions
            host={`${import.meta.env.VITE_API_URL}/`}
            getDesignerModelAction="DXXRD/GetDesignerModel"
          />
        </ReportDesigner>
      </Suspense>
    </Container>
  )
}

export default DevexpressReportDesigner
