import React, { useEffect, useState } from "react";
import {
	Tabs,
	Tab,
	Box,
	Card,
	Typography,
	IconButton,
	Button,
} from "@mui/material";
import { CustomTextField } from "../../components/AddUserModal/styled.css.tsx";
import AddCircleIcon from "@mui/icons-material/AddCircle";
import DeleteIcon from "@mui/icons-material/Delete";
import CalendarTodayRoundedIcon from "@mui/icons-material/CalendarTodayRounded";
import { LocalizationProvider, DatePicker } from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import dayjs from "dayjs";
import { useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import {
	fetchAvailableSlots,
	createSlot,
	deleteSlot,
} from "../../redux/slices/slotSlice.ts";
import { RootState } from "../../redux/reducers.ts";
import BookingSlots from "../../components/BookingSlotsMangers/bookingslots.tsx";

const days = [
	"Monday",
	"Tuesday",
	"Wednesday",
	"Thursday",
	"Friday",
	"Saturday",
];

export default function EVSlotManagement() {
	const [selectedDay, setSelectedDay] = useState("Monday");
	const [breakTime, setBreakTime] = useState<any>([]);
	const [error, setError] = useState<string>("");
	const [selectedDate, setSelectedDate] = useState<dayjs.Dayjs | null>(
		dayjs()
	);
	const navigate = useNavigate();
	const dispatch = useDispatch();

	const { availableSlots } = useSelector(
		(state: RootState) => state?.slotReducer
	);

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

	const handleBack = () => {
		navigate("/panel/dashboard");
	};

	// Add Slot
	const addSlot = (start: string, end: string) => {
		const selectedDateFormatted = selectedDate?.format("YYYY-MM-DD");

		dispatch(
			createSlot({
				date: selectedDateFormatted,
				startHour: start,
				endHour: end,
				isAvailable: true,
			})
		).then(() => {
			dispatch(fetchAvailableSlots());
		});
	};

	// Delete slot
	const handleDeleteSlot = (slotId: string) => {
		dispatch(deleteSlot(slotId));
		dispatch(fetchAvailableSlots());
	};

	// Filter the available slots for the selected date's day
	const filteredSlots = availableSlots.filter((slot: any) => {
		// Get the day of the week for each slot
		const slotDate = dayjs(slot.date);
		const slotDay = slotDate.format("dddd"); // Get the day of the week (e.g., "Monday")

		// Compare the selected day with the slot's day
		return slotDay === selectedDay; // Only show slots that match the selected day
	});

	return (
		<Box sx={{ maxWidth: 600, mx: "auto", p: 2 }}>
			<Typography variant="h4" gutterBottom align="center">
				EV Station Slot Management
			</Typography>

			{/* Date Picker */}
			<Box
				sx={{ display: "flex", justifyContent: "space-between", mt: 3 }}
			>
				<Typography variant="h4" gutterBottom align="center">
					Select Date
				</Typography>
				<LocalizationProvider dateAdapter={AdapterDayjs}>
					<DatePicker
						value={selectedDate}
						onChange={(newDate) => setSelectedDate(newDate)}
						renderInput={(props) => (
							<CustomTextField
								{...props}
								fullWidth
								label="Select Date"
								InputProps={{
									startAdornment: (
										<CalendarTodayRoundedIcon fontSize="small" />
									),
								}}
							/>
						)}
					/>
				</LocalizationProvider>
			</Box>

			<Tabs
				value={selectedDay}
				onChange={(_event, newValue) => setSelectedDay(newValue)}
				variant="scrollable"
				scrollButtons="auto"
				sx={{ mt: 3 }}
			>
				{days.map((day) => (
					<Tab
						key={day}
						label={day}
						value={day}
						sx={{
							fontWeight: "bold",
							fontSize: "16px",
							"&.Mui-selected": {
								backgroundColor: "#52ACDF",
								color: "white",
								borderRadius: "8px",
							},
						}}
					/>
				))}
			</Tabs>

			<Card sx={{ mt: 2, p: 2 }}>
				<Typography variant="h6">Add Slots</Typography>
				<Box sx={{ display: "flex", gap: 2, mt: 1 }}>
					<CustomTextField
						type="time"
						label="Start Time"
						id="slotStart"
						fullWidth
					/>
					<CustomTextField
						type="time"
						label="End Time"
						id="slotEnd"
						fullWidth
					/>
					<Button
						sx={{
							backgroundColor: "#52ACDF",
							color: "white",
							borderRadius: "8px",
							width: "250px",
							"&:hover": { backgroundColor: "#439BC1" },
						}}
						onClick={() =>
							addSlot(
								document.getElementById("slotStart").value,
								document.getElementById("slotEnd").value
							)
						}
					>
						<AddCircleIcon sx={{ mr: 1 }} /> Add
					</Button>
				</Box>
				{error && (
					<Typography color="error" mt={1}>
						{error}
					</Typography>
				)}
			</Card>

			<Card sx={{ mt: 2, p: 2 }}>
				<Typography variant="h6" gutterBottom>
					Slots for {selectedDay}
				</Typography>
				{filteredSlots.length ? (
					filteredSlots.map((slot: any, index: number) => (
						<Box
							key={index}
							sx={{
								display: "flex",
								justifyContent: "space-between",
								alignItems: "center",
								mb: 1,
							}}
						>
							<Typography variant="body1">
								{dayjs(slot.date).format("YYYY-MM-DD")} -{" "}
								{dayjs(slot.startTime).format("HH:mm")} -{" "}
								{dayjs(slot.endTime).format("HH:mm")}
							</Typography>
							<IconButton
								onClick={() => handleDeleteSlot(slot.id)}
							>
								<DeleteIcon color="error" />
							</IconButton>
						</Box>
					))
				) : (
					<Typography>No slots added for {selectedDay}</Typography>
				)}
			</Card>
			
		
		</Box>
		
	);
}
