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 { managerList, updateManager } from "../../redux/slices/managerSlice"; // Import the updateManager action
import {
	CustomIconButton,
	CustomTextField,
} from "../AddEditUserModel/styled.css.tsx"; // Custom styled components
import { AppDispatch } from "../../redux/store/store.ts";

interface EditManagerModalProps {
	open: boolean;
	handleClose: () => void;
	handleUpdate: (
		id: string,
		name: string,
		email: string,
		phone: string,
		stationId: string
	) => Promise<void>;
	editRow: any;
}

interface FormData {
	name: string;
	email: string;
	phone: string;
	stationId: string;
}

const EditManagerModal: React.FC<EditManagerModalProps> = ({
	open,
	handleClose,
	editRow,
}) => {
	const dispatch = useDispatch<AppDispatch>();
	const {
		control,
		handleSubmit,
		formState: { errors },
		setValue,
		reset,
	} = useForm<FormData>({
		defaultValues: {
			name: "",
			email: "",
			phone: "",
			stationId: "",
		},
	});

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

	// Set values if editRow is provided
	useEffect(() => {
		if (editRow) {
			setValue("name", editRow.name);
			setValue("email", editRow.email);
			setValue("phone", editRow.phone);
			setValue("stationId", editRow.stationId);
		} else {
			reset();
		}
	}, [editRow, setValue, reset]);

	const onSubmit = async (data: FormData) => {
		if (editRow) {
			try {
				await dispatch(
					updateManager({
						id: editRow.id, // Manager ID
						managerData: {
							name: data.name,
							email: data.email,
							phone: data.phone,
							stationId: data.stationId,
						
						},
					})
				).unwrap(); // Ensure that it throws an error if the update fails
				dispatch(managerList());
				handleClose(); // Close modal on success
				reset(); // Reset form fields after submit
			} catch (error) {
				console.error(error);
				// You can handle the error here 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-manager-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 Manager
					</Typography>
					<CustomIconButton onClick={handleClose}>
						<CloseIcon />
					</CustomIconButton>
				</Box>

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

				{/* Input Fields (Name, Email, and Phone) */}
				<Box sx={{ display: "flex", flexWrap: "wrap", gap: 2 }}>
					{/* Manager Name */}
					<Box sx={{ flex: "1 1 48%" }}>
						<Typography variant="body2" fontWeight={500} mb={0.5}>
							Manager Name
						</Typography>
						<Controller
							name="name"
							control={control}
							rules={{
								required: "Manager Name is required",
								minLength: {
									value: 3,
									message: "Minimum 3 characters required",
								},
								maxLength: {
									value: 30,
									message: "Maximum 30 characters allowed",
								},
								pattern: {
									value: /^[A-Za-z\s]+$/, // Only letters and spaces are allowed
									message:
										"Manager Name must only contain letters and spaces",
								},
							}}
							render={({ field }) => (
								<CustomTextField
									{...field}
									fullWidth
									placeholder="Enter Manager Name"
									size="small"
									error={!!errors.name}
									helperText={errors.name?.message}
								/>
							)}
						/>
					</Box>

					{/* Email */}
					<Box sx={{ flex: "1 1 48%" }}>
						<Typography variant="body2" fontWeight={500} mb={0.5}>
							Email
						</Typography>
						<Controller
							name="email"
							control={control}
							rules={{ required: "Email is required" }}
							render={({ field }) => (
								<CustomTextField
									{...field}
									fullWidth
									placeholder="Enter Email"
									size="small"
									error={!!errors.email}
									helperText={errors.email?.message}
								/>
							)}
						/>
					</Box>

					{/* Phone Number */}
					<Box sx={{ flex: "1 1 48%" }}>
						<Typography variant="body2" fontWeight={500} mb={0.5}>
							Phone Number
						</Typography>
						<Controller
							name="phone"
							control={control}
							rules={{ required: "Phone number is required" }}
							render={({ field }) => (
								<CustomTextField
									{...field}
									fullWidth
									placeholder="Enter Phone Number"
									size="small"
									error={!!errors.phone}
									helperText={errors.phone?.message}
								/>
							)}
						/>
					</Box>
					{/* <Box sx={{ flex: "1 1 48%" }}>
						<Typography variant="body2" fontWeight={500} mb={0.5}>
							StationId
						</Typography>
						<Controller
							name="stationId"
							control={control}
							rules={{ required: "StationId is required" }}
							render={({ field }) => (
								<CustomTextField
									{...field}
									fullWidth
									placeholder="Enter Station Id"
									size="small"
									error={!!errors.stationId}
									helperText={errors.stationId?.message}
								/>
							)}
						/>
					</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 Manager"
						)}
					</Button>
				</Box>
			</Box>
		</Modal>
	);
};
export default EditManagerModal;