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 } from "../../redux/slices/slotSlice"; // Update with correct action
import {
	CustomIconButton,
	CustomTextField,
} from "../AddEditUserModel/styled.css.tsx"; // Custom styled components

interface EditSlotModalProps {
	open: boolean;
	handleClose: () => 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(); // Use dispatch to send Redux actions
	const {
		control,
		handleSubmit,
		formState: { errors },
		setValue,
		reset,
	} = useForm<FormData>({
		defaultValues: {
			date: "",
			startTime: "",
			endTime: "",
			isAvailable: false,
		},
	});

	const [loading, setLoading] = useState(false);
	const [isAvailable, setIsAvailable] = useState<boolean>(
		editRow?.isAvailable || false
	); // Default to editRow availability

	// Set values if editRow is provided
	useEffect(() => {
		if (editRow) {
			setValue("date", editRow.date);
			setValue("startTime", editRow.startTime);
			setValue("endTime", editRow.endTime);
			setIsAvailable(editRow.isAvailable); // Set the initial availability correctly
		} else {
			reset();
		}
	}, [editRow, setValue, reset]);

	const onSubmit = async (data: FormData) => {
		if (editRow) {
			try {
				// Convert boolean availability to 1/0
				const availabilityStatus = isAvailable ? true : false;

				await dispatch(
					updateSlot({
						id: editRow.id, // Slot ID
						slotData: {
							date: data.date,
							startTime: data.startTime,
							endTime: data.endTime,
							isAvailable: availabilityStatus,
						},
					})
				).unwrap(); // Ensure that it throws an error if the update fails
				dispatch(fetchAvailableSlots()); // Assuming this action fetches the updated slot list
				handleClose(); // Close modal on success
				reset(); // Reset form fields after submit
			} catch (error) {
				console.error(error);
				// Handle the error or show a toast
			} finally {
				setLoading(false); // Stop loading state
			}
		}
	};

	return (
		<Modal
			open={open}
			onClose={(e, reason) => {
				if (reason === "backdropClick") {
					return;
				}
				handleClose(); // Close modal when clicking cross or cancel
			}}
			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: "background.paper",
					boxShadow: 24,
					p: 3,
					borderRadius: 2,
				}}
			>
				{/* Header */}
				<Box
					sx={{
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
					}}
				>
					<Typography variant="h6" fontWeight={600}>
						Edit Slot
					</Typography>
					<CustomIconButton onClick={handleClose}>
						<CloseIcon />
					</CustomIconButton>
				</Box>

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

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

					{/* Start Time */}
					<Box sx={{ flex: "1 1 48%" }}>
						<Typography variant="body2" fontWeight={500} mb={0.5}>
							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}>
							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>

					{/* Availability Toggle */}
					<Box
						display="flex"
						alignItems="center"
						justifyContent="space-between"
						gap={2}
						sx={{ flex: "1 1 100%" }}
					>
						<Button
							onClick={() => {
								const newAvailability = !isAvailable;
								setIsAvailable(newAvailability); // Update local state
								setValue("isAvailable", newAvailability); // Update form value for isAvailable
							}}
							variant={isAvailable ? "contained" : "outlined"}
							color="primary"
						>
							{isAvailable ? "Available" : "Not Available"}
						</Button>
						<Typography>
							{isAvailable ? "Available" : "Not Available"}
						</Typography>
					</Box>
				</Box>

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

export default EditSlotModal;
