import React, { useState, useEffect } from 'react';
import {
  Box, 
  Typography, 
  Grid, 
  Paper, 
  Card, 
  CardContent, 
  CardHeader, 
  List,
  ListItem,
  ListItemText,
  Divider,
  Button,
  CircularProgress,
  Alert
} from '@mui/material';
import {
  People as PeopleIcon,
  ShoppingCart as ShoppingCartIcon,
  Store as StoreIcon,
  AttachMoney as MoneyIcon,
  Class as CategoryIcon
} from '@mui/icons-material';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import apiClient from '../../services/api';
import { useAdminCategories } from '../../hooks/categoryAdminHooks';
import { useAdminOrders, useAdminUsers } from '../../hooks/adminHooks';
import { format } from 'date-fns';

const AdminDashboardPage = () => {
  const navigate = useNavigate();
  
  // Fetch data with React Query
  const { data: products, isLoading: productsLoading, error: productsError } = useQuery({
    queryKey: ['admin-products'],
    queryFn: async () => {
      try {
        const response = await apiClient.get('/products');
        return response.data;
      } catch (error) {
        throw new Error('Failed to fetch products');
      }
    },
  });

  const { data: categories, isLoading: categoriesLoading } = useAdminCategories();
  const { data: orders, isLoading: ordersLoading } = useAdminOrders();
  const { data: users, isLoading: usersLoading } = useAdminUsers();

  // Calculate total revenue from orders
  const calculateTotalRevenue = () => {
    if (!orders || orders.length === 0) return 0;
    return orders.reduce((sum, order) => {
      // Only count orders that are completed/paid
      if (order.payment_completed) {
        return sum + parseFloat(order.total_amount || 0);
      }
      return sum;
    }, 0);
  };

  // Get recent orders (last 4)
  const getRecentOrders = () => {
    if (!orders || orders.length === 0) return [];
    
    // Sort orders by created_at date (newest first) and take the first 4
    return orders
      .sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
      .slice(0, 4);
  };

  // Format date
  const formatDate = (dateString) => {
    if (!dateString) return '';
    try {
      return format(new Date(dateString), 'yyyy-MM-dd');
    } catch (error) {
      return dateString;
    }
  };

  // Stats state
  const [stats, setStats] = useState({
    totalProducts: 0,
    totalUsers: 0,
    totalOrders: 0,
    revenue: 0,
    totalCategories: 0
  });

  // Update stats when data is loaded
  useEffect(() => {
    const newStats = {
      totalProducts: products?.length || 0,
      totalUsers: users?.length || 0,
      totalOrders: orders?.length || 0,
      revenue: calculateTotalRevenue(),
      totalCategories: categories?.length || 0
    };
    setStats(newStats);
  }, [products, categories, orders, users]);

  // Recent orders
  const recentOrders = getRecentOrders();

  // Placeholder for when we add actual API calls
  const isLoading = productsLoading || categoriesLoading || ordersLoading || usersLoading;
  const error = productsError;

  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Alert severity="error" sx={{ my: 2 }}>
        Error loading dashboard data: {error.message}
      </Alert>
    );
  }

  return (
    <Box>
      <Typography variant="h4" component="h1" gutterBottom>
        Admin Dashboard
      </Typography>

      {/* Stats Cards */}
      <Grid container spacing={3} sx={{ mb: 4 }}>
        <Grid item xs={12} sm={6} md={3}>
          <Paper
            sx={{
              p: 2,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              bgcolor: 'primary.light',
              color: 'primary.contrastText',
            }}
          >
            <StoreIcon sx={{ fontSize: 40, mb: 1 }} />
            <Typography component="h2" variant="h5">
              {stats.totalProducts}
            </Typography>
            <Typography variant="body1">Products</Typography>
          </Paper>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Paper
            sx={{
              p: 2,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              bgcolor: 'info.light',
              color: 'info.contrastText',
            }}
          >
            <CategoryIcon sx={{ fontSize: 40, mb: 1 }} />
            <Typography component="h2" variant="h5">
              {stats.totalCategories}
            </Typography>
            <Typography variant="body1">Categories</Typography>
          </Paper>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Paper
            sx={{
              p: 2,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              bgcolor: 'secondary.light',
              color: 'secondary.contrastText',
            }}
          >
            <PeopleIcon sx={{ fontSize: 40, mb: 1 }} />
            <Typography component="h2" variant="h5">
              {stats.totalUsers}
            </Typography>
            <Typography variant="body1">Users</Typography>
          </Paper>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Paper
            sx={{
              p: 2,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              bgcolor: 'success.light',
              color: 'success.contrastText',
            }}
          >
            <MoneyIcon sx={{ fontSize: 40, mb: 1 }} />
            <Typography component="h2" variant="h5">
              ${stats.revenue.toFixed(2)}
            </Typography>
            <Typography variant="body1">Revenue</Typography>
          </Paper>
        </Grid>
      </Grid>

      {/* Recent Activity Section */}
      <Grid container spacing={3}>
        {/* Recent Orders */}
        <Grid item xs={12} md={6}>
          <Card>
            <CardHeader 
              title="Recent Orders" 
              action={
                <Button 
                  size="small" 
                  component={RouterLink}
                  to="/admin/orders"
                >
                  View All
                </Button>
              }
            />
            <CardContent sx={{ pt: 0 }}>
              <List>
                {recentOrders.length > 0 ? (
                  recentOrders.map((order, index) => (
                    <React.Fragment key={order.id}>
                      <ListItem>
                        <ListItemText
                          primary={`Order #${order.id.substring(0, 8)} - ${order.first_name} ${order.last_name}`}
                          secondary={`Date: ${formatDate(order.created_at)} | Total: $${parseFloat(order.total_amount).toFixed(2)} | Status: ${order.status}`}
                        />
                      </ListItem>
                      {index < recentOrders.length - 1 && <Divider />}
                    </React.Fragment>
                  ))
                ) : (
                  <ListItem>
                    <ListItemText primary="No orders found" />
                  </ListItem>
                )}
              </List>
            </CardContent>
          </Card>
        </Grid>

        {/* Recent Products */}
        <Grid item xs={12} md={6}>
          <Card>
            <CardHeader 
              title="Recent Products" 
              action={
                <Button 
                  size="small" 
                  component={RouterLink}
                  to="/admin/products"
                >
                  View All
                </Button>
              }
            />
            <CardContent sx={{ pt: 0 }}>
              <List>
                {products && products.slice(0, 4).map((product, index) => (
                  <React.Fragment key={product.id}>
                    <ListItem>
                      <ListItemText
                        primary={product.name}
                        secondary={`Category: ${product.category_name} | Price: $${parseFloat(product.price).toFixed(2)} | Stock: ${product.stock_quantity}`}
                      />
                    </ListItem>
                    {index < 3 && <Divider />}
                  </React.Fragment>
                ))}
              </List>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* Quick Actions */}
      <Paper sx={{ p: 3, mt: 4 }}>
        <Typography variant="h6" gutterBottom>
          Quick Actions
        </Typography>
        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 2 }}>
          <Button 
            variant="contained" 
            color="primary"
            component={RouterLink}
            to="/admin/products/new"
          >
            Add New Product
          </Button>
          <Button 
            variant="contained"
            color="secondary"
            component={RouterLink}
            to="/admin/categories"
          >
            Manage Categories
          </Button>
          <Button 
            variant="outlined"
            component={RouterLink}
            to="/admin/products"
          >
            Manage Products
          </Button>
          <Button 
            variant="outlined"
            component={RouterLink}
            to="/admin/orders"
          >
            View Orders
          </Button>
        </Box>
      </Paper>
    </Box>
  );
};

export default AdminDashboardPage;