import ChartsEmbedSDK from '@mongodb-js/charts-embed-dom'
import { useEffect, useRef, useState } from 'react'

interface DashboardProps {
  token: any
  dashboardId: string
  charts: any
  chartFilters: any
  sx?: any
}

const MongoDashboard: React.FC<DashboardProps> = ({
  token,
  dashboardId,
  charts,
  chartFilters,
  sx = {},
}) => {
  const [rendered, setRendered] = useState<Boolean>(false)
  const [dashboard, setDashboard] = useState<any>(null)
  const chartDiv = useRef(null)

  const sdk = new ChartsEmbedSDK({
    baseUrl: 'https://charts.mongodb.com/charts-project-0-cnovv',
    getUserToken: () => token,
  })

  useEffect(() => {
    const initDashboard = async () => {
      const dashboard = sdk.createDashboard({
        dashboardId: dashboardId,
        showAttribution: false,
        background: 'transparent',
        widthMode: 'scale',
        heightMode: 'scale',
      })

      setDashboard(dashboard)
      try {
        await dashboard.render(chartDiv.current)

        setRendered(true)
      } catch (err) {
        console.log('Error during Charts rendering:', err)
      }
    }

    initDashboard()
  }, [])

  useEffect(() => {
    if (dashboard && rendered) {
      const applyFiltersToChart = async () => {
        charts.map((chartGroup, index) => {
          chartGroup.map(async (chartId) => {
            const chart = await dashboard.getChart(chartId)
            console.log(chartFilters[index], chart)
            try {
              await chart.setFilter(chartFilters[index])
            } catch (err) {
              console.log(
                'Error while applying filters to specific chart.',
                err,
              )
            }
          })
        })

        // charts.default.map(async (chartId) => {
        //   const chart = await dashboard.getChart(chartId)

        //   try {
        //     await chart.setFilter(filters)
        //   } catch (err) {
        //     console.log('Error while applying filters to specific chart.', err)
        //   }
        // })

        // charts.lessThanAcademicYear.map(async (chartId) => {
        //   const chart = await dashboard.getChart(chartId)

        //   try {
        //     await chart.setFilter({
        //       ...filters,
        //       academicYear: { $lt: filters.academicYear },
        //     })
        //   } catch (err) {
        //     console.log('Error while applying filters to specific chart.', err)
        //   }
        // })

        // charts.lessThanOrEqualAcademicYear.map(async (chartId) => {
        //   const chart = await dashboard.getChart(chartId)

        //   try {
        //     await chart.setFilter({
        //       ...filters,
        //       academicYear: { $lte: filters.academicYear },
        //     })
        //   } catch (err) {
        //     console.log('Error while applying filters to specific chart.', err)
        //   }
        // })

        // charts.dateRangeByAcademicYear.map(async (chartId) => {
        //   const chart = await dashboard.getChart(chartId)

        //   try {
        //     await chart.setFilter({
        //       'admissionSubValue.tenantId':
        //         filters['admissionSubValue.tenantId'],
        //       'admissionSubValue.institutionId':
        //         filters['admissionSubValue.institutionId'],
        //       'feeTypeObject.feeType': filters['feeTypeObject.feeType'],
        //       createdAt: {
        //         $gte: startDate,
        //         $lte: endDate,
        //       },
        //     })
        //   } catch (err) {
        //     console.log('Error while applying filters to specific chart.', err)
        //   }
        // })
      }

      applyFiltersToChart()
    }
  }, [dashboard, chartFilters, rendered])

  return (
    <div
      className="chart"
      ref={chartDiv}
      style={{
        height: '200vh',
        margin: '25px 10px',
        backgroundColor: '#EEEE',
        padding: '15px 0px',
        borderRadius: '10px',
        ...sx,
      }}
    />
  )
}

export default MongoDashboard
