import * as React from "react";
import { useTheme } from "@mui/material/styles";
import {
	Card,
	CardContent,
	Typography,
	Box,
	TextField,
	Button,
} from "@mui/material";
import { BarChart } from "@mui/x-charts/BarChart";
import { axisClasses } from "@mui/x-charts/ChartsAxis";
import useMediaQuery from "@mui/material/useMediaQuery";
import { AppDispatch, RootState } from "../../redux/store/store";
import { useDispatch, useSelector } from "react-redux";
import { fetchDashboardData } from "../../redux/slices/dashboardSlice";

export default function RoundedBarChart() {
	const theme = useTheme();
	const isXsScreen = useMediaQuery(theme.breakpoints.down("sm"));
	const isSmScreen = useMediaQuery(theme.breakpoints.between("sm", "md"));
	const dispatch = useDispatch<AppDispatch>();

	// Fetch role and topStations from Redux state
	const { user } = useSelector((state: RootState) => state.profileReducer); // Assuming user role is stored in Redux
	const { topStations } = useSelector(
		(state: RootState) => state.dashboardReducer
	);

	// State for filtering
	const [startDateStations, setStartDateStations] = React.useState("");
	const [endDateStations, setEndDateStations] = React.useState("");

	// Handle fetching data with date filters
	const handleFetchData = () => {
		dispatch(fetchDashboardData({ startDateStations, endDateStations }));
	};

	// Responsive chart settings
	const getChartSettings = () => {
		const baseSettings = {
			yAxis: [
				{
					label: isXsScreen ? "" : "Count",
					tickFormatter: (value: number) => `${value}`,
				},
			],
			xAxis: [
				{
					dataKey: "name",
					scaleType: "band" as const,
					bandWidth: isXsScreen ? 8 : 15,
				},
			],
			sx: {
				[`.${axisClasses.left} .${axisClasses.label}`]: {
					transform: "translate(-10px, 0)",
				},
			},
		};

		// Screen-specific settings
		if (isXsScreen) {
			return {
				...baseSettings,
				width: 280,
				height: 220,
			};
		} else if (isSmScreen) {
			return {
				...baseSettings,
				width: 380,
				height: 260,
			};
		} else {
			return {
				...baseSettings,
				width: 400,
				height: 280,
			};
		}
	};

	const chartSetting = getChartSettings();

	// Data transformation for BarChart
	const chartData = topStations.map((station) => ({
		name: station?.ChargingStation?.name,
		count: parseInt(station.count, 10), // Ensure count is a number
	}));

	return (
		<Card
			variant="outlined"
			sx={{
				width: "100%",
				height: "auto",
				minHeight: { xs: "360px", sm: "400px", md: "444px" },
				borderRadius: "30px",
				border: "none",
				background: "#D0E1E9",
			}}
		>
			<CardContent
				sx={{
					padding: { xs: 2, md: 3 },
					"&:last-child": { paddingBottom: { xs: 2, md: 3 } },
				}}
			>
				{/* Header */}
				<Box
					display="flex"
					alignItems="center"
					color="#F2F2F2"
					flexDirection={isXsScreen ? "column" : "row"}
					sx={{ mb: isXsScreen ? 2 : 0 }}
				>
					<Typography
						variant="h6"
						// color="#F2F2F2"
						color="#000000"
						align={isXsScreen ? "center" : "left"}
						sx={{
							fontWeight: 600,
							fontSize: { xs: "12px", sm: "14px", md: "16px" },
							lineHeight: "24px",
							marginBottom: isXsScreen ? 2 : 0,
							width: isXsScreen ? "100%" : "auto",
						}}
					>
						Top Stations Stats
					</Typography>
				</Box>

				{/* Date Filters */}
				<Box
					display="flex"
					flexDirection={isXsScreen ? "column" : "row"}
					gap={2}
					mt={2}
				>
					<TextField
						type="date"
						label="Start Date"
						variant="outlined"
						fullWidth
						InputLabelProps={{ shrink: true }}
						value={startDateStations}
						onChange={(e) => setStartDateStations(e.target.value)}
						sx={{
							// backgroundColor: "#202020",
							backgroundColor: "#D9E7ED",
							border: "1px solid rgba(87, 85, 85, 0.53)",
							borderRadius: "8px",
							// "& .MuiInputBase-input": {
							// 	color: "#F2F2F2",
							// },
						}}
					/>
					<TextField
						type="date"
						label="End Date"
						variant="outlined"
						fullWidth
						InputLabelProps={{
							shrink: true, // ensures the label always stays above
						}}
						value={endDateStations}
						onChange={(e) => setEndDateStations(e.target.value)}
						sx={{
							// backgroundColor: "#202020",
							backgroundColor: "#D9E7ED",
							border: "1px solid rgba(87, 85, 85, 0.53)",
							borderRadius: "8px",
							// "& .MuiInputBase-input": {
							// 	color: "#F2F2F2",
							// },
						}}
					/>
					<Button
						onClick={handleFetchData}
						sx={{
							// backgroundColor: "#52ACDF",
							backgroundColor: "#000000",
							color: "white",
							borderRadius: "8px",
							width: "117px",
							// "&:hover": { backgroundColor: "#439BC1" },
							"&:hover": { backgroundColor: "#000000" },
						}}
					>
						Apply
					</Button>
				</Box>

				{/* Chart */}
				<Box
					sx={{
						display: "flex",
						justifyContent: "center",
						alignItems: "center",
						width: "100%",
						mt: 4,
					}}
				>
					<BarChart
						borderRadius={0}
						dataset={chartData}
						series={[
							{
								dataKey: "count",
								color: "#000000",
							},
						]}
						layout="vertical"
						{...chartSetting}
					/>
				</Box>
			</CardContent>
		</Card>
	);
}
