import React, { useEffect, useState } from "react";
import {
	Box,
	Button,
	Typography,
	Modal,
	CircularProgress,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { useForm, Controller } from "react-hook-form";
import { useDispatch } from "react-redux";
import {
	updateSlot,
	fetchAvailableSlots,
	fetchManagersSlots,
} from "../../redux/slices/slotSlice.ts"; // Update with correct action
import { CustomIconButton, CustomTextField } from "../AddUserModal/styled.css"; // Custom styled components
import { AppDispatch } from "../../redux/store/store.ts";

interface EditSlotModalProps {
	open: boolean;
	handleClose: () => void;
	handleUpdate: (
		id: string,
		startTime: string,
		endTime: string,
		isAvailable: boolean
	) => Promise<void>;
	editRow: any; // Slot data including id
}

interface FormData {
	date: string;
	startTime: string;
	endTime: string;
	isAvailable: boolean;
}

const EditSlotModal: React.FC<EditSlotModalProps> = ({
	open,
	handleClose,
	editRow,
}) => {
	const dispatch = useDispatch<AppDispatch>();
	const {
		control,
		handleSubmit,
		formState: { errors },
		setValue,
		reset,
	} = useForm<FormData>({
		defaultValues: {
			date: "",
			startTime: "",
			endTime: "",
			isAvailable: false,
		},
	});

	const [loading, setLoading] = useState(false);

	useEffect(() => {
		if (editRow) {
			setValue("startTime", editRow.startTime);
			setValue("endTime", editRow.endTime);
		} else {
			reset();
		}
	}, [editRow, setValue, reset]);

	const onSubmit = async (data: FormData) => {
		if (editRow) {
			setLoading(true);

			try {

				await dispatch(
					updateSlot({
						id: editRow.id, 
						startTime: data.startTime,
						endTime: data.endTime,
					})
				).unwrap();
				dispatch(fetchManagersSlots());
				handleClose(); 
				reset(); 
			} catch (error) {
				console.error("Error updating slot:", error);
			} finally {
				setLoading(false); 
			}
		}
	};

	return (
		<Modal
			open={open}
			onClose={(e, reason) => {
				if (reason === "backdropClick") {
					return;
				}
				handleClose();
			}}
			aria-labelledby="edit-slot-modal"
		>
			<Box
				component="form"
				onSubmit={handleSubmit(onSubmit)}
				sx={{
					position: "absolute",
					top: "50%",
					left: "50%",
					transform: "translate(-50%, -50%)",
					width: 400,
					bgcolor: "#000000",
					boxShadow: 24,
					p: 3,
					borderRadius: 2,
				}}
			>
				{/* Header */}
				<Box
					sx={{
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
					}}
				>
					<Typography
						variant="h6"
						fontWeight={600}
						fontSize={"16px"}
						color="#D0E1E9"
					>
						Edit Slot
					</Typography>
					<CustomIconButton
						onClick={handleClose}
						sx={{ "& .MuiSvgIcon-root": { color: "#FFFFFF" } }}
					>
						<CloseIcon />
					</CustomIconButton>
				</Box>

				{/* Horizontal Line */}
				<Box sx={{ borderBottom: "1px solid #ddd", my: 2 }} />

				{/* Input Fields */}
				<Box sx={{ display: "flex", flexWrap: "wrap", gap: 2 }}>
					{/* Start Time */}
					<Box sx={{ flex: "1 1 48%" }}>
						<Typography
							variant="body2"
							fontWeight={500}
							mb={0.5}
							color="#D0E1E9"
						>
							Start Time
						</Typography>
						<Controller
							name="startTime"
							control={control}
							rules={{ required: "Start Time is required" }}
							render={({ field }) => (
								<CustomTextField
									{...field}
									type="time"
									fullWidth
									size="small"
									error={!!errors.startTime}
									helperText={errors.startTime?.message}
								/>
							)}
						/>
					</Box>

					{/* End Time */}
					<Box sx={{ flex: "1 1 48%" }}>
						<Typography
							variant="body2"
							fontWeight={500}
							mb={0.5}
							color="#D0E1E9"
						>
							End Time
						</Typography>
						<Controller
							name="endTime"
							control={control}
							rules={{ required: "End Time is required" }}
							render={({ field }) => (
								<CustomTextField
									{...field}
									type="time"
									fullWidth
									size="small"
									error={!!errors.endTime}
									helperText={errors.endTime?.message}
								/>
							)}
						/>
					</Box>
				</Box>

				{/* Submit Button */}
				<Box
					sx={{ display: "flex", justifyContent: "flex-end", mt: 3 }}
				>
					<Button
						type="submit"
						sx={{
							backgroundColor: "#D0E1E9",
							color: "#000000",
							borderRadius: "8px",
							fontSize: "16px",
							width: "117px",
							"&:hover": { backgroundColor: "#D0E1E9" },
						}}
						disabled={loading} // Disable the button during loading state
					>
						{loading ? (
							<CircularProgress size={24} color="inherit" />
						) : (
							"Update Slot"
						)}
					</Button>
				</Box>
			</Box>
		</Modal>
	);
};

export default EditSlotModal;
