import Grid from '@mui/material/Grid2'
import type { UserDataType } from '@components/card-statistics/HorizontalWithSubtitle'
import HorizontalWithSubtitle from '@components/card-statistics/HorizontalWithSubtitle'
import { ProfitLossReport, SalesReport } from '@/types/services/analytic'

// Utility functions
const formatIDR = (amount: number) => {
  return new Intl.NumberFormat('id-ID', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 0
  }).format(amount)
}

const formatPercentage = (value: number) => {
  return `${value.toFixed(1)}%`
}

interface ReportSalesOrderCardProps {
  sales: SalesReport | undefined
}

const ReportSalesOrderCard = ({ sales }: ReportSalesOrderCardProps) => {
  if (!sales) {
    return null // Will be handled by parent loading state
  }

  // Using actual data from API response with correct field names
  const data: UserDataType[] = [
    {
      title: 'Penjualan',
      stats: formatIDR(sales.summary.total_sales),
      avatarIcon: 'tabler-trending-up',
      avatarColor: 'success',
      trend: 'positive',
      trendNumber: '',
      subtitle: 'Total Penjualan'
    },
    {
      title: 'Total Pesanan',
      stats: sales.summary.total_orders.toString(),
      avatarIcon: 'tabler-gauge',
      avatarColor: 'success',
      trend: 'positive',
      trendNumber: '',
      subtitle: 'Total Pesanan'
    },
    {
      title: 'Rata Rata',
      stats: formatIDR(sales.summary.average_order_value),
      avatarIcon: 'tabler-trending-up',
      avatarColor: sales.summary.average_order_value >= 0 ? 'success' : 'error',
      trend: sales.summary.average_order_value >= 0 ? 'positive' : 'negative',
      trendNumber: '',
      subtitle: 'Rata Rata Nilai Pesanan'
    },
    {
      title: 'Penjualan Bersih',
      stats: formatIDR(sales.summary.net_sales),
      avatarIcon: sales.summary.net_sales >= 0 ? 'tabler-trending-up' : 'tabler-trending-down',
      avatarColor: sales.summary.net_sales >= 0 ? 'success' : 'error',
      trend: sales.summary.net_sales >= 0 ? 'positive' : 'negative',
      trendNumber: '',
      subtitle: 'Net Profit'
    }
  ]

  return (
    <Grid container spacing={6}>
      {data.map((item, i) => (
        <Grid key={i} size={{ xs: 12, sm: 6, md: 3 }}>
          <HorizontalWithSubtitle {...item} />
        </Grid>
      ))}
    </Grid>
  )
}

export default ReportSalesOrderCard
