import { CommonProps } from '@/@types/common'
import { Meta } from '@/@types/routes'
import { Container } from '@/components/shared'
import { DX_CLASSNAMES } from '@/constants/app.constant'
import { useLocalization } from '@/utils/hooks/useLocalization'
import DxChart from 'devextreme-react/chart'
import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet'
import { useParams, useSearchParams } from 'react-router-dom'
import { useListFormCustomDataSource } from '@/shared/useListFormCustomDataSource'
import { GridDto } from '@/proxy/form/models'
import { usePermission } from '@/utils/hooks/usePermission'
import { Button } from '@/components/ui'
import { ROUTES_ENUM } from '@/routes/route.constant'
import { usePWA } from '@/utils/hooks/usePWA'
import { FaInfoCircle } from 'react-icons/fa'

interface ChartProps extends CommonProps, Meta {
  listFormCode: string
  filter?: string
  isSubForm?: boolean
  level?: number
  refreshData?: () => Promise<void>
  gridDto?: GridDto
}

const Chart = (props: ChartProps) => {
  const { listFormCode, filter, isSubForm, level, gridDto } = props
  const { translate } = useLocalization()
  const { checkPermission } = usePermission()
  const isPwaMode = usePWA()

  const [searchParams] = useSearchParams()
  const [chartOptions, setChartOptions] = useState<any>()
  const { createSelectDataSource } = useListFormCustomDataSource({})

  const params = useParams()
  const _listFormCode = props?.listFormCode ?? params?.listFormCode ?? ''

  useEffect(() => {
    if (!gridDto) return

    // console.log(
    //   gridDto.gridOptions?.seriesDto?.map((s) => `${s.argumentField} asc false`).join(', '),
    // )
    // console.log(gridDto.gridOptions?.seriesDto?.map((s) => `${s.valueField} count`).join(', '))

    const dataSource = createSelectDataSource(
      gridDto.gridOptions,
      listFormCode,
      searchParams,
      // [],
      // gridDto.gridOptions?.seriesDto?.map((s) => `${s.argumentField} asc false`).join(', '),
      // gridDto.gridOptions?.seriesDto?.map((s) => `${s.valueField} count`).join(', '),
    )

    const options = {
      dataSource: dataSource,

      adjustOnZoom: gridDto.gridOptions.commonDto?.adjustOnZoom ?? true,
      containerBackgroundColor:
        gridDto.gridOptions.commonDto?.containerBackgroundColor ?? '#FFFFFF',
      disabled: gridDto.gridOptions.commonDto?.disabled ?? false,
      palette: gridDto.gridOptions.commonDto?.palette ?? 'Material',
      paletteExtensionMode: gridDto.gridOptions.commonDto?.paletteExtensionMode ?? 'blend',
      //theme: s(chartDto.commonDto?.theme, 'generic.light'),

      title: gridDto.gridOptions.titleDto,
      size: gridDto.gridOptions.sizeDto?.useSize
        ? { width: gridDto.gridOptions.sizeDto.width, height: gridDto.gridOptions.sizeDto.height }
        : { width: '100%', height: window.innerHeight - 210 },
      legend: gridDto.gridOptions.legendDto,
      margin: gridDto.gridOptions.marginDto,
      adaptiveLayout: gridDto.gridOptions.adaptivelayoutDto,
      defaultPane: gridDto.gridOptions.commonDto?.defaultPane,

      scrollBar: gridDto.gridOptions.scrollBarDto,
      zoomAndPan: gridDto.gridOptions.zoomAndPanDto,
      animation: gridDto.gridOptions.animationDto,
      export: gridDto.gridOptions.exportDto,
      crosshair: gridDto.gridOptions.crosshairDto,
      argumentAxis: gridDto.gridOptions.argumentAxisDto,
      valueAxis: gridDto.gridOptions.valueAxisDto,
      tooltip: gridDto.gridOptions.tooltipDto,

      series: gridDto.gridOptions.seriesDto,
      // gridDto.gridOptions.seriesDto?.length > 0
      //   ? gridDto.gridOptions.seriesDto.map((s) => ({
      //       argumentField: 'key',
      //       valueField: 'summary',
      //     }))
      //   : undefined,
      panes: gridDto.gridOptions.panesDto?.length > 0 ? gridDto.gridOptions.panesDto : undefined,
      commonSeriesSettings: gridDto.gridOptions.commonSeriesSettingsDto,
      commonPaneSettings: gridDto.gridOptions.commonPaneSettingsDto,
      commonAxisSettings: gridDto.gridOptions.commonAxisSettingsDto,
      annotations: gridDto.gridOptions.annotationsDto,
      commonAnnotationSettings: gridDto.gridOptions.commonAnnotationSettingsDto,

      loadingIndicator: {
        enabled: true,
      },
    }

    setChartOptions(options)
  }, [gridDto, searchParams])

  return (
    <Container className={DX_CLASSNAMES}>
      {!isSubForm && gridDto && (
        <Helmet
          titleTemplate="%s | Sözsoft Kurs Platform"
          title={translate('::' + gridDto?.gridOptions?.title)}
          defaultTitle="Sözsoft Kurs Platform"
        ></Helmet>
      )}
      {_listFormCode && chartOptions && (
        <div className="p-1 bg-white dark:bg-neutral-800 dark:border-neutral-700 ">
          <div className="flex justify-end items-center">
            <div className="relative pb-1 flex gap-1 border-b-1">
              {checkPermission(gridDto?.gridOptions.permissionDto.u) && (
                <Button
                  size="xs"
                  variant={'default'}
                  className="text-sm"
                  onClick={() => {
                    window.open(
                      ROUTES_ENUM.protected.saas.listFormManagement.edit.replace(
                        ':listFormCode',
                        listFormCode,
                      ),
                      isPwaMode ? '_self' : '_blank',
                    )
                  }}
                  title="Form Manager"
                >
                  <FaInfoCircle className="w-3 h-3" />
                </Button>
              )}
            </div>
          </div>
          <DxChart key={'DxChart' + _listFormCode} {...chartOptions}></DxChart>
        </div>
      )}
    </Container>
  )
}

export default Chart
