import React, { useState } from "react";
import {
	Dialog,
	DialogActions,
	DialogContent,
	DialogTitle,
	Button,
	TextField,
	Typography,
	Box,
	FormControlLabel,
	Switch,
} from "@mui/material";
import { useForm } from "react-hook-form";

const AddSlotModal = ({ open, handleClose, handleAddSlot }: any) => {
	const {
		register,
		handleSubmit,
		reset,
		formState: { errors },
	} = useForm();
	const [isAvailable, setIsAvailable] = useState<boolean>(true);
	const [isDateRange, setIsDateRange] = useState<boolean>(false);

	// Get today's date in the format yyyy-mm-dd
	const today = new Date().toISOString().split("T")[0];

	const onSubmit = (data: any) => {
		const { date, startDate, endDate, startHour, endHour, duration } = data;
		const slots = [];

		const generateSlotsForDate = (date: string) => {
			const startTime = new Date(`1970-01-01T${startHour}:00`);
			const endTime = new Date(`1970-01-01T${endHour}:00`);
			const durationMinutes = parseInt(duration, 10);

			for (
				let time = startTime;
				time < endTime;
				time.setMinutes(time.getMinutes() + durationMinutes)
			) {
				const slotEndTime = new Date(time);
				slotEndTime.setMinutes(
					slotEndTime.getMinutes() + durationMinutes
				);

				if (slotEndTime <= endTime) {
					slots.push({
						date,
						startHour: time.toTimeString().slice(0, 5),
						endHour: slotEndTime.toTimeString().slice(0, 5),
						isAvailable,
						duration,
					});
				}
			}
		};

		if (isDateRange) {
			const start = new Date(startDate);
			const end = new Date(endDate);
			for (
				let d = new Date(start);
				d <= end;
				d.setDate(d.getDate() + 1)
			) {
				const dateString = d.toISOString().split("T")[0];
				generateSlotsForDate(dateString);
			}
		} else {
			generateSlotsForDate(date);
		}

		handleAddSlot(slots);
		reset();
		handleClose();
	};

	return (
		<Dialog open={open} onClose={handleClose}>
			<DialogTitle>Add EV Slot</DialogTitle>
			<DialogContent
				sx={{
					display: "flex",
					flexDirection: "column",
					padding:0
				}}
			>
				<form onSubmit={handleSubmit(onSubmit)}>
					<FormControlLabel
						control={
							<Switch
								checked={isDateRange}
								onChange={() => setIsDateRange(!isDateRange)}
							/>
						}
						label="Select Date Range"
					/>
					{isDateRange ? (
						<>
							<Typography variant="body2" fontWeight={500}>
								Start Date
							</Typography>
							<TextField
								{...register("startDate", {
									required: "Start date is required",
									validate: (value) =>
										value >= today ||
										"Start date cannot be in the past",
								})}
								type="date"
								fullWidth
								margin="normal"
								error={!!errors.startDate}
								helperText={errors.startDate?.message}
								inputProps={{ min: today }}
							/>
							<Typography variant="body2" fontWeight={500}>
								End Date
							</Typography>
							<TextField
								{...register("endDate", {
									required: "End date is required",
									validate: (value) =>
										value >= today ||
										"End date cannot be in the past",
								})}
								type="date"
								fullWidth
								margin="normal"
								error={!!errors.endDate}
								helperText={errors.endDate?.message}
								inputProps={{ min: today }}
							/>
						</>
					) : (
						<>
							<Typography variant="body2" fontWeight={500}>
								Date
							</Typography>
							<TextField
								{...register("date", {
									required: "Date is required",
									validate: (value) =>
										value >= today ||
										"Date cannot be in the past",
								})}
								type="date"
								fullWidth
								margin="normal"
								error={!!errors.date}
								helperText={errors.date?.message}
								inputProps={{ min: today }}
							/>
						</>
					)}
					<Typography variant="body2" fontWeight={500}>
						Start Hour
					</Typography>
					<TextField
						{...register("startHour", {
							required: "Start hour is required",
						})}
						type="time"
						fullWidth
						margin="normal"
						error={!!errors.startHour}
						helperText={errors.startHour?.message}
					/>
					<Typography variant="body2" fontWeight={500}>
						End Hour
					</Typography>
					<TextField
						{...register("endHour", {
							required: "End hour is required",
						})}
						type="time"
						fullWidth
						margin="normal"
						error={!!errors.endHour}
						helperText={errors.endHour?.message}
					/>
					<Typography variant="body2" fontWeight={500}>
						Slot Duration (minutes)
					</Typography>
					<TextField
						{...register("duration", {
							required: "Duration is required",
							pattern: {
								value: /^[0-9]+$/,
								message: "Duration must be a number",
							},
						})}
						type="number"
						fullWidth
						margin="normal"
						error={!!errors.duration}
						helperText={errors.duration?.message}
					/>
					<Box
						display="flex"
						alignItems="center"
						justifyContent="space-between"
						gap={2}
					>
						<Button
							onClick={() => setIsAvailable((prev) => !prev)}
							variant={isAvailable ? "contained" : "outlined"}
							color="primary"
							sx={{ marginTop: 1 }}
						>
							Check Availability
						</Button>
						<Typography>
							{isAvailable ? "Available" : "Not Available"}
						</Typography>
					</Box>
					<DialogActions>
						<Button onClick={handleClose} color="secondary">
							Cancel
						</Button>
						<Button
							type="submit"
							sx={{
								backgroundColor: "#52ACDF",
								color: "white",
								borderRadius: "8px",
								width: "100px",
								"&:hover": { backgroundColor: "#439BC1" },
							}}
						>
							Add Booking
						</Button>
					</DialogActions>
				</form>
			</DialogContent>
		</Dialog>
	);
};

export default AddSlotModal;
