import React, { useMemo } from 'react';
import { Card, CardContent, Grid, Typography } from '@mui/material';
import { FuelLogResponse } from '../types/fuel-logs.types';
import { useUnits } from '../../../core/units/UnitsContext';

export const FuelStatsCard: React.FC<{ logs?: FuelLogResponse[] }> = ({ logs }) => {
  const { unitSystem, currencySymbol } = useUnits();
  const stats = useMemo(() => {
    if (!logs || logs.length === 0) return { count: 0, totalUnits: 0, totalCost: 0 };

    const totalUnits = logs.reduce((s, l) => {
      const fuelUnits = typeof l.fuelUnits === 'number' && !isNaN(l.fuelUnits) ? l.fuelUnits : 0;
      return s + fuelUnits;
    }, 0);

    const totalCost = logs.reduce((s, l) => {
      const cost = typeof l.totalCost === 'number' && !isNaN(l.totalCost) ? l.totalCost : 0;
      return s + cost;
    }, 0);

    return { count: logs.length, totalUnits, totalCost };
  }, [logs]);

  const unitLabel = unitSystem === 'imperial' ? 'gallons' : 'liters';

  return (
    <Card variant="outlined">
      <CardContent>
        <Grid container spacing={2}>
          <Grid item xs={4}>
            <Typography variant="overline" color="text.secondary">Logs</Typography>
            <Typography variant="h6">{stats.count}</Typography>
          </Grid>
          <Grid item xs={4}>
            <Typography variant="overline" color="text.secondary">Total Fuel</Typography>
            <Typography variant="h6">{(typeof stats.totalUnits === 'number' && !isNaN(stats.totalUnits) ? stats.totalUnits : 0).toFixed(2)} {unitLabel}</Typography>
          </Grid>
          <Grid item xs={4}>
            <Typography variant="overline" color="text.secondary">Total Cost</Typography>
            <Typography variant="h6">{currencySymbol}{(typeof stats.totalCost === 'number' && !isNaN(stats.totalCost) ? stats.totalCost : 0).toFixed(2)}</Typography>
          </Grid>
        </Grid>
      </CardContent>
    </Card>
  );
};

