import { useEffect, useState } from 'react'
import PageContainer from '@/components/yaui/Wrapper/PageWrapper'
import ContentWrapper from '@/components/yaui/Wrapper/ContentWrapper'
import YaPie, { genPieSeriesOps } from '@/components/echarts/Pie'
import YaPolyline, { genPolylineSeriesOps } from '@/components/echarts/Polyline'
import { getPieData, getPolylineData } from '@/services/showcase'
import { useSelectedMode } from '@/components/context/YaThemeProdiver'
import type { EChartsOption } from '@/components/echarts/types'

export default (): JSX.Element => {
  const [pieLoading, setPieLoading] = useState<boolean>(false)
  const [polylineLoading, setPolylineLoading] = useState<boolean>(false)
  const [pieData, setPieData] = useState<EChartsOption['series']>()
  const [polylineData, setPolylineData] = useState<EChartsOption['series']>()
  const [polylineOpts, setPolylineOpts] = useState<EChartsOption>()
  const mode = useSelectedMode()

  const fetchPie = async () => {
    setPieLoading(true)
    const res = await getPieData()
    const pieSeriesOps = genPieSeriesOps()
    setPieData([
      {
        ...pieSeriesOps,
        data: res,
        name: 'pie',
      },
    ])
    setPieLoading(false)
  }

  const fetchPolyline = async () => {
    setPolylineLoading(true)
    const { category, series } = await getPolylineData()
    const polylineSeriesOps = genPolylineSeriesOps()
    const polylineSeries = series.map((item: any) => {
      const { name, data } = item
      return {
        ...polylineSeriesOps,
        name,
        data,
      }
    })
    setPolylineData(polylineSeries)
    setPolylineOpts({
      xAxis: {
        data: category,
      },
    })
    setPolylineLoading(false)
  }
  const init = async () => {
    Promise.all([fetchPie(), fetchPolyline()])
  }

  useEffect(() => {
    ;(async () => {
      await init()
    })()
  }, [])
  return (
    <PageContainer>
      <ContentWrapper title="Pie" style={{ margin: '1rem 0' }}>
        <YaPie loading={pieLoading} series={pieData} mode={mode} />
      </ContentWrapper>
      <ContentWrapper title="Polyline" style={{ marginBottom: '1rem' }}>
        <YaPolyline
          loading={polylineLoading}
          series={polylineData}
          mode={mode}
          opts={polylineOpts}
        />
      </ContentWrapper>
    </PageContainer>
  )
}
