'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 { useProfitLossAnalytics } from '../../../../../../services/queries/analytics'
import {
    ProductDataReport,
    ProfitLossReport
} from '../../../../../../types/services/analytic'

function formatMetricName(metric: string): string {
  const nameMap: { [key: string]: string } = {
    revenue: 'Revenue',
    cost: 'Cost',
    gross_profit: 'Gross Profit',
    gross_profit_margin: 'Gross Profit Margin (%)',
    tax: 'Tax',
    discount: 'Discount',
    net_profit: 'Net Profit',
    net_profit_margin: 'Net Profit Margin (%)',
    orders: 'Orders'
  }

  return nameMap[metric] || metric.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())
}

const DashboardProfitLoss = () => {
  const { data, isLoading } = useProfitLossAnalytics()

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

  const metrics = ['revenue', 'cost', 'gross_profit', 'net_profit']

  const transformSalesData = (data: ProfitLossReport) => {
    return [
      {
        type: 'products',
        avatarIcon: 'tabler-package',
        date: data.product_data.map((d: ProductDataReport) => d.product_name),
        series: [{ data: data.product_data.map((d: ProductDataReport) => d.revenue) }]
      },
    //   {
    //     type: 'profits',
    //     avatarIcon: 'tabler-currency-dollar',
    //     date: data.data.map((d: DailyData) => formatDate(d.date)),
    //     series: metrics.map(metric => ({
    //       name: formatMetricName(metric as string),
    //       data: data.data.map((item: any) => item[metric] as number)
    //     }))
    //   }
    ]
  }

  if (isLoading) return <Loading />

  return (
    <Grid container spacing={6}>
      <Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
        <DistributedBarChartOrder
          isLoading={isLoading}
          title='Total Cost'
          value={data?.summary.total_cost as number}
          avatarIcon={'tabler-currency-dollar'}
          avatarColor='primary'
          avatarSkin='light'
        />
      </Grid>
      <Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
        <DistributedBarChartOrder
          isLoading={isLoading}
          title='Total Rvenue'
          value={data?.summary.total_revenue as number}
          avatarIcon={'tabler-currency-dollar'}
          avatarColor='info'
          avatarSkin='light'
        />
      </Grid>
      <Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
        <DistributedBarChartOrder
          isLoading={isLoading}
          title='Gross Profit'
          value={data?.summary.gross_profit as number}
          avatarIcon={'tabler-trending-up'}
          avatarColor='warning'
          avatarSkin='light'
        />
      </Grid>
      <Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
        <DistributedBarChartOrder
          isLoading={isLoading}
          title='Net Profit'
          value={data?.summary.net_profit as number}
          avatarIcon={'tabler-currency-dollar'}
          avatarColor='success'
          avatarSkin='light'
        />
      </Grid>
      <Grid size={{ xs: 12, lg: 12 }}>
        <EarningReportsWithTabs data={transformSalesData(data!)} />
      </Grid>
    </Grid>
  )
}

export default DashboardProfitLoss
