import React, { useEffect } from "react";
import Grid from "@mui/material/Grid";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import SessionsChart from "../SessionsChart/sessionChart";
import ResourcesPieChart from "../ResourcePieChart/resourcePieChart";
import RoundedBarChart from "../barChartCard/barChartCard";
import LineChartCard from "../LineChartCard/lineChartCard";
import { AppDispatch, RootState } from "../../redux/store/store";
import { useDispatch, useSelector } from "react-redux";
import { fetchDashboardData } from "../../redux/slices/dashboardSlice";
import AppTheme from "../../shared-theme/AppTheme"; // Import the custom theme
import StatCard from "../StatCard/statCard"; // Adjusted import for consistency

export default function MainGrid() {
	const dispatch = useDispatch<AppDispatch>();
	const {
		totalAdmins,
		totalManagers,
		totalUsers,
		totalStations,
		loading,
		error,
	} = useSelector((state: RootState) => state.dashboardReducer);

	useEffect(() => {
		dispatch(fetchDashboardData());
	}, [dispatch]);

	// Use fetched data if available, otherwise fall back to static data
	const data = {
		totalAdmins: totalAdmins || 86,
		totalManagers: totalManagers || 12,
		totalUsers: totalUsers || 24,
		totalStations: totalStations || 8,
	};

	const statCards = [
		{ title: "Total Admins", value: data.totalAdmins },
		{ title: "Total Managers", value: data.totalManagers },
		{ title: "Total Users", value: data.totalUsers },
		{ title: "Total Stations", value: data.totalStations },
	];

	return (
		<AppTheme>
			<Box
				sx={{
					width: "100%",
					maxWidth: "1800px",
					mx: "auto",
					px: { xs: 2, sm: 1, md: 0 },
					background: (theme) => theme.palette.background.default, // #DFECF1 from theme
				}}
			>
				{/* Dashboard Header */}
				<Typography
					component="h2"
					variant="h4" // Use h4 to match the "Good morning, James!" size and weight
					sx={{
						mb: 3,
				
						
					}}
				>
					Dashboard 
				</Typography>

				{/* Grid Layout */}
				<Grid container spacing={3} columns={12}>
					{/* Statistic Cards */}
					{statCards.map((card, index) => (
						<Grid key={index} item xs={12} sm={6} md={3} lg={3}>
							<StatCard {...card} />
						</Grid>
					))}

					{/* Charts */}
					<Grid item xs={12} sm={12} md={6} lg={6}>
						<SessionsChart />
					</Grid>
					<Grid item xs={12} sm={12} md={6} lg={6}>
						<ResourcesPieChart />
					</Grid>
					<Grid item xs={12} sm={12} md={6} lg={6}>
						<RoundedBarChart />
					</Grid>
					<Grid item xs={12} sm={12} md={6} lg={6}>
						<LineChartCard />
					</Grid>
				</Grid>
			</Box>
		</AppTheme>
	);
}
