'use client'

// MUI Imports
import Grid from '@mui/material/Grid2'

// Component Imports
import DistributedBarChartOrder from '@views/dashboards/crm/DistributedBarChartOrder'
import EarningReportsWithTabs from '@views/dashboards/crm/EarningReportsWithTabs'

// Server Action Imports
import Loading from '../../../../../../components/layout/shared/Loading'
import { useProductSalesAnalytics } from '../../../../../../services/queries/analytics'
import ProductSales from '../../../../../../views/dashboards/products/ProductSales'

const DashboardProduct = () => {
  const { data, isLoading } = useProductSalesAnalytics()

  const summary = {
    totalProducts: data?.data.length,
    totalQuantitySold: data?.data.reduce((sum, item) => sum + item.quantity_sold, 0),
    totalRevenue: data?.data.reduce((sum, item) => sum + item.revenue, 0),
    totalOrders: data?.data.reduce((sum, item) => sum + item.order_count, 0),
    averageOrderValue: data?.data
      ? data!.data.reduce((sum, item) => sum + item.revenue, 0) /
        data!.data.reduce((sum, item) => sum + item.order_count, 0)
      : 0
  }

  const formatDate = (dateString: any) => {
    return new Date(dateString).toLocaleDateString('id-ID', {
      month: 'short',
      day: 'numeric'
    })
  }

  const transformSalesData = (data: any) => {
    return [
      {
        type: 'products',
        avatarIcon: 'tabler-package',
        date: data.map((d: any) => d.product_name),
        series: [{ data: data.map((d: any) => d.revenue) }]
      }
    ]
  }

  if (isLoading) return <Loading />

  return (
    <Grid container spacing={6}>
      <Grid size={{ xs: 12, lg: 12 }}>{data?.data && <ProductSales title='Product Sales' productData={data.data} />}</Grid>
    </Grid>
  )
}

export default DashboardProduct
