import React, { useState, useEffect, useMemo } from 'react';
import {
  Box,
  Typography,
  Paper,
  Grid,
  Card,
  CardContent,
  CardHeader,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  TextField,
  CircularProgress,
  Alert,
  Tabs,
  Tab,
  Divider,
  Button
} from '@mui/material';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  PieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer
} from 'recharts';
import {
  startOfDay,
  endOfDay,
  startOfWeek,
  endOfWeek,
  startOfMonth,
  endOfMonth,
  startOfYear,
  endOfYear,
  addDays,
  addWeeks,
  addMonths,
  addYears,
  format,
  isWithinInterval,
  parseISO,
  subMonths,
  subWeeks,
  subYears,
  subDays,
  isValid,
  parse
} from 'date-fns';
import { useAdminOrders } from '../../hooks/adminHooks';
import { useQuery } from '@tanstack/react-query';
import apiClient from '../../services/api';

// COLORS for charts
const COLORS = ['#8884d8', '#82ca9d', '#ffc658', '#ff8042', '#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

const ReportsPage = () => {
  // Tab state
  const [activeTab, setActiveTab] = useState(0);
  
  // Time period filter states
  const [timelineType, setTimelineType] = useState('monthly');
  const [fromDate, setFromDate] = useState(subMonths(new Date(), 1));
  const [toDate, setToDate] = useState(new Date());
  
  // State for date inputs
  const [fromDateString, setFromDateString] = useState(format(fromDate, 'yyyy-MM-dd'));
  const [toDateString, setToDateString] = useState(format(toDate, 'yyyy-MM-dd'));
  
  // Fetch data
  const { data: orders, isLoading: ordersLoading } = useAdminOrders();
  const { data: products, isLoading: productsLoading } = useQuery({
    queryKey: ['admin-products'],
    queryFn: async () => {
      const response = await apiClient.get('/products');
      return response.data;
    }
  });
  
  // Update date objects when string inputs change
  useEffect(() => {
    const parsedFromDate = parse(fromDateString, 'yyyy-MM-dd', new Date());
    if (isValid(parsedFromDate)) {
      setFromDate(parsedFromDate);
    }
  }, [fromDateString]);
  
  useEffect(() => {
    const parsedToDate = parse(toDateString, 'yyyy-MM-dd', new Date());
    if (isValid(parsedToDate)) {
      setToDate(parsedToDate);
    }
  }, [toDateString]);
  
  // Handle tab change
  const handleTabChange = (event, newValue) => {
    setActiveTab(newValue);
  };
  
  // Handle timeline type change
  const handleTimelineChange = (event) => {
    const newTimelineType = event.target.value;
    setTimelineType(newTimelineType);
    
    // Adjust the date range based on the new timeline type
    const today = new Date();
    let newFromDate;
    
    switch (newTimelineType) {
      case 'daily':
        newFromDate = subDays(today, 7); // Last 7 days
        break;
      case 'weekly':
        newFromDate = subWeeks(today, 4); // Last 4 weeks
        break;
      case 'monthly':
        newFromDate = subMonths(today, 1); // Last month
        break;
      case 'annually':
        newFromDate = subYears(today, 1); // Last year
        break;
      default:
        newFromDate = subMonths(today, 1);
    }
    
    setFromDate(newFromDate);
    setToDate(today);
    setFromDateString(format(newFromDate, 'yyyy-MM-dd'));
    setToDateString(format(today, 'yyyy-MM-dd'));
  };
  
  // Handle date input changes
  const handleFromDateChange = (e) => {
    setFromDateString(e.target.value);
  };
  
  const handleToDateChange = (e) => {
    setToDateString(e.target.value);
  };
  
  // Filter orders based on selected date range
  const filteredOrders = useMemo(() => {
    if (!orders) return [];
    
    return orders.filter(order => {
      const orderDate = parseISO(order.created_at);
      return isWithinInterval(orderDate, {
        start: startOfDay(fromDate),
        end: endOfDay(toDate)
      });
    });
  }, [orders, fromDate, toDate]);
  
  // Calculate total revenue for the selected period
  const totalRevenue = useMemo(() => {
    return filteredOrders.reduce((sum, order) => {
      if (order.payment_completed) {
        return sum + parseFloat(order.total_amount || 0);
      }
      return sum;
    }, 0);
  }, [filteredOrders]);
  
  // Calculate average order value
  const averageOrderValue = useMemo(() => {
    const completedOrders = filteredOrders.filter(order => order.payment_completed);
    if (completedOrders.length === 0) return 0;
    
    const total = completedOrders.reduce((sum, order) => sum + parseFloat(order.total_amount || 0), 0);
    return total / completedOrders.length;
  }, [filteredOrders]);
  
  // Group orders by status
  const ordersByStatus = useMemo(() => {
    const statusCounts = {};
    
    filteredOrders.forEach(order => {
      const status = order.status || 'unknown';
      statusCounts[status] = (statusCounts[status] || 0) + 1;
    });
    
    return Object.entries(statusCounts).map(([status, count]) => ({
      name: status.charAt(0).toUpperCase() + status.slice(1),
      value: count
    }));
  }, [filteredOrders]);
  
  // Group orders by location (state/province)
  const ordersByLocation = useMemo(() => {
    const locationCounts = {};
    
    filteredOrders.forEach(order => {
      if (!order.shipping_address) return;
      
      // Basic location extraction from shipping address
      let location = 'Unknown';
      
      try {
        // Try to extract state/province from the address
        // This is a simple approach - might need to be refined based on your address format
        const addressLines = order.shipping_address.split('\n');
        const stateLine = addressLines.find(line => line.includes(','));
        
        if (stateLine) {
          const statePart = stateLine.split(',')[1];
          if (statePart) {
            // Extract state code (usually 2 letters before zip code)
            const stateMatch = statePart.trim().match(/^([A-Z]{2})/);
            location = stateMatch ? stateMatch[1] : statePart.trim().split(' ')[0];
          }
        }
      } catch (error) {
        console.error('Error parsing location from address:', error);
      }
      
      locationCounts[location] = (locationCounts[location] || 0) + 1;
    });
    
    return Object.entries(locationCounts)
      .map(([location, count]) => ({
        name: location,
        value: count
      }))
      .sort((a, b) => b.value - a.value) // Sort by count descending
      .slice(0, 8); // Top 8 locations
  }, [filteredOrders]);
  
  // Debug - log filtered orders
  useEffect(() => {
    console.log("Filtered orders:", filteredOrders);
  }, [filteredOrders]);
  
  // Prepare time series data for revenue chart
  const revenueTimeSeriesData = useMemo(() => {
    if (!orders) return [];
    
    const dataMap = new Map();
    let dateFormat;
    let step;
    
    // Determine format and grouping based on timeline type
    switch (timelineType) {
      case 'daily':
        dateFormat = 'MMM d';
        step = (date) => addDays(date, 1);
        break;
      case 'weekly':
        dateFormat = "'Week' w, yyyy";
        step = (date) => addWeeks(date, 1);
        break;
      case 'monthly':
        dateFormat = 'MMM yyyy';
        step = (date) => addMonths(date, 1);
        break;
      case 'annually':
        dateFormat = 'yyyy';
        step = (date) => addYears(date, 1);
        break;
      default:
        dateFormat = 'MMM yyyy';
        step = (date) => addMonths(date, 1);
    }
    
    // Initialize dataMap with all periods in the range
    let currentDate = new Date(fromDate);
    while (currentDate <= toDate) {
      const key = format(currentDate, dateFormat);
      dataMap.set(key, { name: key, revenue: 0, orders: 0 });
      currentDate = step(currentDate);
    }
    
    // Add order data to the map
    filteredOrders.forEach(order => {
      const orderDate = parseISO(order.created_at);
      const key = format(orderDate, dateFormat);
      
      if (dataMap.has(key)) {
        const entry = dataMap.get(key);
        if (order.payment_completed) {
          entry.revenue += parseFloat(order.total_amount || 0);
        }
        entry.orders += 1;
        dataMap.set(key, entry);
      }
    });
    
    // Convert map to array and sort by date
    return Array.from(dataMap.values());
  }, [filteredOrders, timelineType, fromDate, toDate]);
  
  // Fetch order details for product analysis
  const { data: orderDetails, isLoading: orderDetailsLoading } = useQuery({
    queryKey: ['admin-order-details', filteredOrders.map(order => order.id)],
    queryFn: async () => {
      // Only fetch if we have filtered orders
      if (!filteredOrders.length) return [];
      
      // Fetch details for each order in parallel
      const detailPromises = filteredOrders.map(order => 
        apiClient.get(`/admin/orders/${order.id}`)
          .then(response => response.data)
          .catch(error => {
            console.error(`Error fetching details for order ${order.id}:`, error);
            return null;
          })
      );
      
      const results = await Promise.all(detailPromises);
      return results.filter(Boolean); // Remove any failed requests
    },
    enabled: filteredOrders.length > 0
  });


  // Debug - log order details
  useEffect(() => {
    if (orderDetails) {
      console.log("Order details:", orderDetails);
    }
  }, [orderDetails]);

  
  // Prepare product sales data
  const productSalesData = useMemo(() => {
    if (!products || !orderDetails) return [];
    
    const productSales = {};
    
    // Initialize with all products
    products.forEach(product => {
      productSales[product.id] = {
        id: product.id,
        name: product.name,
        category: product.category_name,
        quantity: 0,
        revenue: 0
      };
    });
    
    // Aggregate sales data from order details
    orderDetails.forEach(order => {
      if (order.items && Array.isArray(order.items)) {
        order.items.forEach(item => {
          if (productSales[item.product_id]) {
            productSales[item.product_id].quantity += parseInt(item.quantity) || 0;
            productSales[item.product_id].revenue += parseFloat(item.price_at_purchase || 0) * (parseInt(item.quantity) || 0);
          } else {
            // Handle case where product might exist in orders but not in current products list
            console.log(`Product ${item.product_id} found in orders but not in products list`);
            productSales[item.product_id] = {
              id: item.product_id,
              name: item.product_name || `Product ${item.product_id.substring(0, 8)}...`,
              category: item.product_category || 'Unknown',
              quantity: parseInt(item.quantity) || 0,
              revenue: parseFloat(item.price_at_purchase || 0) * (parseInt(item.quantity) || 0)
            };
          }
        });
      }
    });
    
    // Convert to array and sort by quantity
    return Object.values(productSales)
      .filter(product => product.quantity > 0)
      .sort((a, b) => b.quantity - a.quantity);
  }, [products, orderDetails]);
  
  // Top selling products for the chart
  const topSellingProducts = useMemo(() => {
    return productSalesData.slice(0, 5);
  }, [productSalesData]);
  
  // Category sales distribution
  const categorySalesData = useMemo(() => {
    if (!productSalesData.length) return [];
    
    const categoryMap = {};
    
    productSalesData.forEach(product => {
      const category = product.category || 'Uncategorized';
      
      if (!categoryMap[category]) {
        categoryMap[category] = {
          name: category,
          value: 0,
          revenue: 0
        };
      }
      
      categoryMap[category].value += product.quantity;
      categoryMap[category].revenue += product.revenue;
    });
    
    return Object.values(categoryMap).sort((a, b) => b.value - a.value);
  }, [productSalesData]);
  
  // Loading state
  const isLoading = ordersLoading || productsLoading || orderDetailsLoading;
  
  // Handle export reports
  const handleExportCSV = () => {
    // Generate CSV content
    let csvContent = 'data:text/csv;charset=utf-8,';
    
    // Add headers
    csvContent += 'Period,Revenue,Orders\n';
    
    // Add data rows
    revenueTimeSeriesData.forEach(item => {
      csvContent += `${item.name},${item.revenue.toFixed(2)},${item.orders}\n`;
    });
    
    // Create download link
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement('a');
    link.setAttribute('href', encodedUri);
    link.setAttribute('download', `sales-report-${format(new Date(), 'yyyy-MM-dd')}.csv`);
    document.body.appendChild(link);
    
    // Trigger download
    link.click();
    
    // Clean up
    document.body.removeChild(link);
  };
  
  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }
  
  return (
    <Box>
      <Typography variant="h4" component="h1" gutterBottom>
        Reports & Analytics
      </Typography>
      
      {/* Filters */}
      <Paper sx={{ p: 3, mb: 3 }}>
        <Grid container spacing={3} alignItems="center">
          <Grid item xs={12} md={3}>
            <FormControl fullWidth>
              <InputLabel id="timeline-label">Timeline</InputLabel>
              <Select
                labelId="timeline-label"
                value={timelineType}
                label="Timeline"
                onChange={handleTimelineChange}
              >
                <MenuItem value="daily">Daily</MenuItem>
                <MenuItem value="weekly">Weekly</MenuItem>
                <MenuItem value="monthly">Monthly</MenuItem>
                <MenuItem value="annually">Annually</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          
          <Grid item xs={12} md={4}>
            <TextField
              label="From Date"
              type="date"
              value={fromDateString}
              onChange={handleFromDateChange}
              fullWidth
              InputLabelProps={{
                shrink: true,
              }}
              inputProps={{
                max: toDateString
              }}
            />
          </Grid>
          
          <Grid item xs={12} md={4}>
            <TextField
              label="To Date"
              type="date"
              value={toDateString}
              onChange={handleToDateChange}
              fullWidth
              InputLabelProps={{
                shrink: true,
              }}
              inputProps={{
                min: fromDateString,
                max: format(new Date(), 'yyyy-MM-dd')
              }}
            />
          </Grid>
          
          <Grid item xs={12} md={1}>
            <Button 
              variant="outlined" 
              fullWidth
              onClick={handleExportCSV}
            >
              Export
            </Button>
          </Grid>
        </Grid>
      </Paper>
      
      {/* Summary Cards */}
      <Grid container spacing={3} sx={{ mb: 3 }}>
        <Grid item xs={12} md={3}>
          <Card>
            <CardContent sx={{ textAlign: 'center' }}>
              <Typography variant="h6" color="textSecondary" gutterBottom>
                Total Revenue
              </Typography>
              <Typography variant="h4">
                ${totalRevenue.toFixed(2)}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        
        <Grid item xs={12} md={3}>
          <Card>
            <CardContent sx={{ textAlign: 'center' }}>
              <Typography variant="h6" color="textSecondary" gutterBottom>
                Orders
              </Typography>
              <Typography variant="h4">
                {filteredOrders.length}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        
        <Grid item xs={12} md={3}>
          <Card>
            <CardContent sx={{ textAlign: 'center' }}>
              <Typography variant="h6" color="textSecondary" gutterBottom>
                Average Order Value
              </Typography>
              <Typography variant="h4">
                ${averageOrderValue.toFixed(2)}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        
        <Grid item xs={12} md={3}>
          <Card>
            <CardContent sx={{ textAlign: 'center' }}>
              <Typography variant="h6" color="textSecondary" gutterBottom>
                Completed Orders
              </Typography>
              <Typography variant="h4">
                {filteredOrders.filter(order => order.payment_completed).length}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
      </Grid>
      
      {/* Tabs for different reports */}
      <Paper sx={{ mb: 3 }}>
        <Tabs
          value={activeTab}
          onChange={handleTabChange}
          variant="scrollable"
          scrollButtons="auto"
        >
          <Tab label="Sales Overview" />
          <Tab label="Product Performance" />
          <Tab label="Order Analysis" />
          <Tab label="Geographic Distribution" />
        </Tabs>
        
        <Box sx={{ p: 3 }}>
          {/* Sales Overview Tab */}
          {activeTab === 0 && (
            <Grid container spacing={3}>
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom>
                  Revenue & Orders Over Time
                </Typography>
                <Box sx={{ height: 400 }}>
                  <ResponsiveContainer width="100%" height="100%">
                    <LineChart
                      data={revenueTimeSeriesData}
                      margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                    >
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="name" />
                      <YAxis yAxisId="left" />
                      <YAxis yAxisId="right" orientation="right" />
                      <Tooltip formatter={(value, name) => {
                        return name === 'revenue' ? `$${value.toFixed(2)}` : value;
                      }} />
                      <Legend />
                      <Line yAxisId="left" type="monotone" dataKey="revenue" name="Revenue ($)" stroke="#8884d8" activeDot={{ r: 8 }} />
                      <Line yAxisId="right" type="monotone" dataKey="orders" name="Orders" stroke="#82ca9d" />
                    </LineChart>
                  </ResponsiveContainer>
                </Box>
              </Grid>
              
              <Grid item xs={12} md={6}>
                <Typography variant="h6" gutterBottom>
                  Order Status Distribution
                </Typography>
                <Box sx={{ height: 300 }}>
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie
                        data={ordersByStatus}
                        cx="50%"
                        cy="50%"
                        labelLine={false}
                        label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                        outerRadius={100}
                        fill="#8884d8"
                        dataKey="value"
                      >
                        {ordersByStatus.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                        ))}
                      </Pie>
                      <Tooltip formatter={(value, name, props) => [`${value} orders`, props.payload.name]} />
                      <Legend />
                    </PieChart>
                  </ResponsiveContainer>
                </Box>
              </Grid>
              
              <Grid item xs={12} md={6}>
                <Typography variant="h6" gutterBottom>
                  Category Sales Distribution
                </Typography>
                <Box sx={{ height: 300 }}>
                  <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                      <Pie
                        data={categorySalesData}
                        cx="50%"
                        cy="50%"
                        labelLine={false}
                        label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                        outerRadius={100}
                        fill="#8884d8"
                        dataKey="value"
                      >
                        {categorySalesData.map((entry, index) => (
                          <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                        ))}
                      </Pie>
                      <Tooltip formatter={(value, name, props) => [`${value} items`, props.payload.name]} />
                      <Legend />
                    </PieChart>
                  </ResponsiveContainer>
                </Box>
              </Grid>
            </Grid>
          )}
          
          {/* Product Performance Tab */}
          {activeTab === 1 && (
            <Grid container spacing={3}>
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom>
                  Top Selling Products
                </Typography>
                {topSellingProducts.length > 0 ? (
                  <Box sx={{ height: 400 }}>
                    <ResponsiveContainer width="100%" height="100%">
                      <BarChart
                        data={topSellingProducts}
                        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                      >
                        <CartesianGrid strokeDasharray="3 3" />
                        <XAxis dataKey="name" />
                        <YAxis />
                        <Tooltip formatter={(value, name) => {
                          return name === 'revenue' ? `${value.toFixed(2)}` : value;
                        }} />
                        <Legend />
                        <Bar dataKey="quantity" name="Units Sold" fill="#8884d8" />
                        <Bar dataKey="revenue" name="Revenue ($)" fill="#82ca9d" />
                      </BarChart>
                    </ResponsiveContainer>
                  </Box>
                ) : (
                  <Box sx={{ p: 4, textAlign: 'center', bgcolor: 'background.paper', borderRadius: 1 }}>
                    <Typography variant="body1" color="text.secondary">
                      No product sales data available for the selected time period.
                    </Typography>
                  </Box>
                )}
              </Grid>
              
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom>
                  Product Sales Details
                </Typography>
                <Box sx={{ overflowX: 'auto' }}>
                  {productSalesData.length > 0 ? (
                    <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                      <thead>
                        <tr>
                          <th style={{ textAlign: 'left', padding: '8px', borderBottom: '1px solid #ddd' }}>Product</th>
                          <th style={{ textAlign: 'left', padding: '8px', borderBottom: '1px solid #ddd' }}>Category</th>
                          <th style={{ textAlign: 'right', padding: '8px', borderBottom: '1px solid #ddd' }}>Units Sold</th>
                          <th style={{ textAlign: 'right', padding: '8px', borderBottom: '1px solid #ddd' }}>Revenue</th>
                        </tr>
                      </thead>
                      <tbody>
                        {productSalesData.map((product) => (
                          <tr key={product.id}>
                            <td style={{ padding: '8px', borderBottom: '1px solid #f0f0f0' }}>{product.name}</td>
                            <td style={{ padding: '8px', borderBottom: '1px solid #f0f0f0' }}>{product.category}</td>
                            <td style={{ textAlign: 'right', padding: '8px', borderBottom: '1px solid #f0f0f0' }}>{product.quantity}</td>
                            <td style={{ textAlign: 'right', padding: '8px', borderBottom: '1px solid #f0f0f0' }}>${product.revenue.toFixed(2)}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  ) : (
                    <Box sx={{ p: 4, textAlign: 'center', bgcolor: 'background.paper', borderRadius: 1 }}>
                      <Typography variant="body1" color="text.secondary">
                        No product sales data available for the selected time period.
                      </Typography>
                    </Box>
                  )}
                </Box>
              </Grid>
              
              {orderDetailsLoading && (
                <Grid item xs={12} sx={{ display: 'flex', justifyContent: 'center', py: 2 }}>
                  <CircularProgress size={28} />
                  <Typography variant="body2" color="text.secondary" sx={{ ml: 2 }}>
                    Loading product data...
                  </Typography>
                </Grid>
              )}
            </Grid>
          )}
          
          {/* Order Analysis Tab */}
          {activeTab === 2 && (
            <Grid container spacing={3}>
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom>
                  Orders Over Time
                </Typography>
                <Box sx={{ height: 400 }}>
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart
                      data={revenueTimeSeriesData}
                      margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                    >
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="name" />
                      <YAxis />
                      <Tooltip />
                      <Legend />
                      <Bar dataKey="orders" name="Number of Orders" fill="#8884d8" />
                    </BarChart>
                  </ResponsiveContainer>
                </Box>
              </Grid>
              
              <Grid item xs={12} md={6}>
                <Card>
                  <CardHeader title="Order Completion Rate" />
                  <CardContent>
                    <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <Box sx={{ position: 'relative', display: 'inline-flex' }}>
                        <CircularProgress
                          variant="determinate"
                          value={filteredOrders.length > 0 ? (filteredOrders.filter(o => o.payment_completed).length / filteredOrders.length) * 100 : 0}
                          size={100}
                          thickness={5}
                          sx={{ color: '#82ca9d' }}
                        />
                        <Box
                          sx={{
                            top: 0,
                            left: 0,
                            bottom: 0,
                            right: 0,
                            position: 'absolute',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                          }}
                        >
                          <Typography variant="h6" component="div">
                            {filteredOrders.length > 0 ? Math.round((filteredOrders.filter(o => o.payment_completed).length / filteredOrders.length) * 100) : 0}%
                          </Typography>
                        </Box>
                      </Box>
                    </Box>
                    <Typography variant="body2" sx={{ mt: 2, textAlign: 'center' }}>
                      {filteredOrders.filter(o => o.payment_completed).length} out of {filteredOrders.length} orders completed
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
              
              <Grid item xs={12} md={6}>
                <Card>
                  <CardHeader title="Average Order Value Trend" />
                  <CardContent>
                    <Box sx={{ height: 200 }}>
                      <ResponsiveContainer width="100%" height="100%">
                        <LineChart
                          data={revenueTimeSeriesData.map(item => ({
                            name: item.name,
                            avgValue: item.orders > 0 ? item.revenue / item.orders : 0
                          }))}
                          margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                        >
                          <CartesianGrid strokeDasharray="3 3" />
                          <XAxis dataKey="name" />
                          <YAxis />
                          <Tooltip formatter={(value) => `$${value.toFixed(2)}`} />
                          <Line type="monotone" dataKey="avgValue" name="Avg. Order Value" stroke="#ff7300" />
                        </LineChart>
                      </ResponsiveContainer>
                    </Box>
                  </CardContent>
                </Card>
              </Grid>
            </Grid>
          )}
          
          {/* Geographic Distribution Tab */}
          {activeTab === 3 && (
            <Grid container spacing={3}>
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom>
                  Orders by Location
                </Typography>
                <Box sx={{ height: 400 }}>
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart
                      data={ordersByLocation}
                      margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                      layout="vertical"
                    >
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis type="number" />
                      <YAxis dataKey="name" type="category" width={100} />
                      <Tooltip />
                      <Legend />
                      <Bar dataKey="value" name="Number of Orders" fill="#8884d8" />
                    </BarChart>
                  </ResponsiveContainer>
                </Box>
              </Grid>
              
              <Grid item xs={12}>
                <Typography variant="body2" color="text.secondary">
                  Note: Location data is extracted from shipping addresses. The accuracy may vary based on address format.
                </Typography>
              </Grid>
            </Grid>
          )}
        </Box>
      </Paper>
    </Box>
  );
};

export default ReportsPage;