import ReactECharts from 'echarts-for-react'
import { useDataFieldQuery, useDataQuery } from '@/hooks/useQuery'

interface DataItem {
  [key: string]: any
  customer_gender: string
  brand: string
  sales_volume: number
  unit_price: number
}

interface ProcessedDataItem {
  gender: string
  [key: `${string}-${string}`]: number
}

export default function Chart() {
  const { getFieldName } = useDataFieldQuery()
  const {
    data: { list = [] },
  } = useDataQuery()

  const xField = 'customer_gender'
  const yField = ['sales_volume', 'unit_price']
  const labelField = 'brand'

  // Get unique genders for x-axis
  const genders = Array.from(new Set(list.map((item: DataItem) => item[xField]))) as string[]

  // Get unique brands for series
  const brands = Array.from(new Set(list.map((item: DataItem) => item[labelField])))

  // Prepare data structure
  const processedData: ProcessedDataItem[] = genders.map((gender) => {
    const genderData: { [key: `${string}-${string}`]: number } = {}
    brands.forEach((brand) => {
      const item = list.find((item: DataItem) => item[xField] === gender && item[labelField] === brand)
      if (item) {
        yField.forEach((field) => {
          genderData[`${brand}-${field}`] = item[field]
        })
      }
    })
    return {
      gender,
      ...genderData,
    }
  })

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    legend: {
      show: true,
      data: yField.map((field) => getFieldName(field)),
    },
    xAxis: {
      type: 'category',
      data: genders,
      axisLabel: {
        interval: 0,
      },
    },
    yAxis: [
      {
        type: 'value',
        name: '销量',
        position: 'left',
      },
      {
        type: 'value',
        name: '单价',
        position: 'right',
      },
    ],
    series: brands.flatMap((brand) => [
      {
        name: `sales_volume`,
        type: 'bar',
        yAxisIndex: 0,
        data: processedData.map((item) => item[`${brand}-sales_volume`] || 0),
        label: {
          show: true,
          position: 'top',
        },
      },
      {
        name: `unit_price`,
        type: 'bar',
        yAxisIndex: 1,
        data: processedData.map((item) => item[`${brand}-unit_price`] || 0),
        label: {
          show: true,
          position: 'top',
        },
      },
    ]),
  }
  return <ReactECharts option={option} style={{ height: '100%' }} />
}
