import React, { useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import {
	Box,
	Button,
	Typography,
	Modal,
	MenuItem,
	Select,
	InputLabel,
	FormControl,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { useDispatch, useSelector } from "react-redux";
import {
	addBooking,
	bookingList,
	getCarNames,
	getCarPorts,
} from "../../redux/slices/bookSlice.ts";
import { AppDispatch, RootState } from "../../redux/store/store.ts";
import { toast } from "sonner";
import { CustomIconButton, CustomTextField } from "../AddUserModal/styled.css";
import { getAllStations } from "../../redux/slices/stationSlice.ts";
import { fetchAvailableSlots } from "../../redux/slices/slotSlice.ts";
import { autofillFix } from "../../shared-theme/customizations/autoFill";
export default function AddBookingModal({
	open,
	handleClose,
}: {
	open: boolean;
	handleClose: () => void;
}) {
	const dispatch = useDispatch<AppDispatch>();
	const {
		control,
		register,
		handleSubmit,
		formState: { errors },
		reset,
	} = useForm();
	const [carNames, setCarNames] = useState<any[]>([]); // To hold the car names
	const [carPorts, setCarPorts] = useState<any[]>([]); // To hold the car ports
	const stations = useSelector(
		(state: RootState) => state?.stationReducer.stations
	);
	const availableSlots = useSelector(
		(state: RootState) => state.slotReducer.availableSlots
	);
	useEffect(() => {
		dispatch(fetchAvailableSlots());
		dispatch(getAllStations());
	}, [dispatch]);

	useEffect(() => {
		// Fetch car names and car ports
		dispatch(getCarNames()).then((response: any) => {
			const fetchedCarNames = response.payload || [];
			setCarNames(fetchedCarNames);
		});

		dispatch(getCarPorts()).then((response: any) => {
			const fetchedCarPorts = response.payload || [];
			setCarPorts(fetchedCarPorts);
		});

		// Fetch the bookings after this
		dispatch(bookingList());
	}, [dispatch]);
	console.log("Car Ports: ", carPorts);
	// Get today's date in yyyy-mm-dd format
	const today = new Date().toISOString().split("T")[0];

	const onSubmit = async (data: any) => {
		const bookingData = {
			stationId: data.stationId, // Using stationId here for the backend
			date: data.date,
			startTime: data.startTime,
			endTime: data.endTime,
			carName: data.carName,
			carNumber: data.carNumber,
			carPort: data.carPort,
		};

		try {
			await dispatch(addBooking(bookingData));
			dispatch(bookingList());
			handleClose(); // Close modal after successful addition
			reset(); // Reset form fields
		} catch (error) {
			console.error("Error adding booking:", error);
			toast.error("Failed to add booking.");
		}
	};

	return (
		<Modal
			open={open}
			onClose={(e, reason) => {
				if (reason === "backdropClick") return;
				handleClose();
			}}
			aria-labelledby="add-booking-modal"
		>
			<Box
				sx={{
					position: "absolute",
					top: "50%",
					left: "50%",
					transform: "translate(-50%, -50%)",
					boxShadow: 24,
					p: 0,
					borderRadius: 2,
					width: "100%",
					maxWidth: 600,
					overflow: "auto",
				}}
			>
				<Box
					sx={{
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
						backgroundColor: "#000000",
						color: "#D0E1E9",

						padding: "16px 24px",
						borderRadius: "10px 10px 0 0",
					}}
				>
					<Typography
						variant="h6"
						fontWeight={600}
						fontSize={"16px"}
						color="#D0E1E9"
					>
						Add Booking
					</Typography>
					<CustomIconButton onClick={handleClose}>
						<CloseIcon />
					</CustomIconButton>
				</Box>
				{/* <Box sx={{ borderBottom: "1px solid #ddd", my: 2 }} /> */}
				<Box
					sx={{
						backgroundColor: "#b5c4cb",
						padding: "24px",
						borderRadius: "0 0 10px 10px",
					}}
				>
					<form onSubmit={handleSubmit(onSubmit)}>
						{/* Station ID and Car Name */}
						<Box sx={{ display: "flex", gap: 2, mb: 2 }}>
							{/* Station ID */}
							<Box
								sx={{
									display: "flex",
									flexDirection: "column",
									width: "50%",
									...autofillFix,
								}}
							>
								<Typography
									variant="body2"
									fontWeight={500}
									mb={1}
									color="#000000"
								>
									Select Station
								</Typography>
								{/* Station ID Field */}
								<FormControl
									fullWidth
									error={!!errors.stationId}
								>
									<Select
										{...register("stationId", {
											required:
												"Station Name is required", // Validation rule
										})}
										defaultValue=""
										size="small"
										displayEmpty
										sx={{
											textOverflow: "ellipsis", // Truncate long text
											whiteSpace: "nowrap",
											overflow: "hidden",
										}}
									>
										{/* Placeholder */}
										<MenuItem value="" disabled>
											<Typography color="text.secondary">
												Choose Station
											</Typography>
										</MenuItem>

										{/* Station Options */}
										{stations.map((station) => (
											<MenuItem
												key={station.id}
												value={station.id}
											>
												{station.name}
											</MenuItem>
										))}
									</Select>
									{/* Safely render the error message */}
									{errors.stationId && (
										<Typography
											color="error"
											variant="body2"
										>
											{errors.stationId.message}
										</Typography>
									)}
								</FormControl>
							</Box>

							<Box
								sx={{
									display: "flex",
									flexDirection: "column",
									width: "50%",
									...autofillFix,
								}}
							>
								<Typography
									variant="body2"
									fontWeight={500}
									mb={1}
									color="#000000"
								>
									Date
								</Typography>
								<CustomTextField
									fullWidth
									type="date"
									size="small"
									error={!!errors.date}
									helperText={
										errors.date ? errors.date.message : ""
									}
									{...register("date", {
										required: "Date is required",
										validate: (value) =>
											value >= today ||
											"Date cannot be in the past",
									})}
									slotProps={{
										inputLabel: {
											shrink: true,
										},
										htmlInput: {
											min: today,
										},
									}}
								/>
							</Box>
						</Box>

						{/* Car Port and Date */}
						<Box sx={{ display: "flex", gap: 2, mb: 2 }}>
							{/* Car Name */}
							<Box
								sx={{
									display: "flex",
									flexDirection: "column",
									width: "50%",
									...autofillFix,
								}}
							>
								<Typography
									variant="body2"
									fontWeight={500}
									mb={1}
									color="#000000"
								>
									Car Name
								</Typography>
								<Controller
									control={control}
									name="carName"
									render={({ field }) => (
										<FormControl
											fullWidth
											size="small"
											error={!!errors.carName}
										>
											<Select
												{...field}
												defaultValue=""
												size="small"
												displayEmpty
												sx={{
													textOverflow: "ellipsis",
													whiteSpace: "nowrap",
													overflow: "hidden",
												}}
											>
												{/* Placeholder item */}
												<MenuItem value="" disabled>
													<Typography color="text.secondary">
														Choose Car Name
													</Typography>
												</MenuItem>

												{/* Car names */}
												{carNames.map((car) => (
													<MenuItem
														key={car.id}
														value={car.name}
													>
														{car.name}
													</MenuItem>
												))}
											</Select>

											{errors.carName && (
												<Typography
													color="error"
													variant="body2"
													sx={{ mt: 1 }}
												>
													{errors.carName.message}
												</Typography>
											)}
										</FormControl>
									)}
									rules={{ required: "Car Name is required" }}
								/>
							</Box>
							{/* Car Port */}
							<Box
								sx={{
									display: "flex",
									flexDirection: "column",
									width: "50%",
									...autofillFix,
								}}
							>
								<Typography
									variant="body2"
									fontWeight={500}
									mb={1}
									color="#000000"
								>
									Car Port
								</Typography>
								<Controller
									control={control}
									name="carPort"
									render={({ field }) => (
										<FormControl
											fullWidth
											size="small"
											error={!!errors.carPort}
										>
											<Select
												{...field}
												defaultValue="" // Set the default value as empty
												size="small"
												displayEmpty // Ensures the placeholder is visible by default
											>
												{/* Placeholder MenuItem */}
												<MenuItem value="" disabled>
													<Typography color="text.secondary">
														Choose Car Port
													</Typography>
												</MenuItem>

												{/* Car Ports */}
												{carPorts.map((port, index) => (
													<MenuItem
														key={index}
														value={port}
													>
														{port}
													</MenuItem>
												))}
											</Select>

											{errors.carPort && (
												<Typography
													color="error"
													variant="body2"
													sx={{ mt: 1 }}
												>
													{errors.carPort.message}
												</Typography>
											)}
										</FormControl>
									)}
									rules={{ required: "Car Port is required" }}
								/>
							</Box>
						</Box>

						{/* Start Time and End Time */}
						<Box sx={{ display: "flex", gap: 2, mb: 2 }}>
							<Box
								sx={{
									display: "flex",
									flexDirection: "column",
									width: "50%",
									...autofillFix,
								}}
							>
								<Typography
									variant="body2"
									fontWeight={500}
									mb={1}
									color="#000000"
								>
									Start Time
								</Typography>
								<CustomTextField
									fullWidth
									type="time"
									size="small"
									error={!!errors.startTime}
									helperText={
										errors.startTime
											? errors.startTime.message
											: ""
									}
									{...register("startTime", {
										required: "Start Time is required",
									})}
								/>
							</Box>

							<Box
								sx={{
									display: "flex",
									flexDirection: "column",
									width: "50%",
									...autofillFix,
								}}
							>
								<Typography
									variant="body2"
									fontWeight={500}
									mb={1}
									color="#000000"
								>
									End Time
								</Typography>
								<CustomTextField
									fullWidth
									type="time"
									size="small"
									error={!!errors.endTime}
									helperText={
										errors.endTime
											? errors.endTime.message
											: ""
									}
									{...register("endTime", {
										required: "End Time is required",
									})}
								/>
							</Box>
						</Box>

						{/* Car Number */}
						<Box sx={{ display: "flex", gap: 2, mb: 2 }}>
							<Box
								sx={{
									display: "flex",
									flexDirection: "column",
									width: "50%",
									...autofillFix,
								}}
							>
								<Typography
									variant="body2"
									fontWeight={500}
									mb={1}
									color="#000000"
								>
									Car Number
								</Typography>
								<CustomTextField
									fullWidth
									placeholder="Enter Car Number"
									size="small"
									error={!!errors.carNumber}
									helperText={
										errors.carNumber
											? errors.carNumber.message
											: ""
									}
									{...register("carNumber", {
										required: "Car Number is required",
									})}
								/>
							</Box>
						</Box>

						{/* Submit Button */}
						<Box
							sx={{
								display: "flex",
								justifyContent: "flex-end",
								mt: 2,
							}}
						>
							<Button
								type="submit"
								sx={{
									backgroundColor: "#000000",
									color: "#D0E1E9",
									borderRadius: "8px",
									fontSize: "16px",
									width: "117px",
									"&:hover": { backgroundColor: "#454545" },
								}}
							>
								Add Booking
							</Button>
						</Box>
					</form>
				</Box>
			</Box>
		</Modal>
	);
}
