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.ts"; // Import the updateManager action
import { CustomIconButton, CustomTextField } from "../AddUserModal/styled.css"; // 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: 500,
					boxShadow: 24,
					p: 0,
					borderRadius: 2,
				}}
			>
				{/* Header */}
				<Box
					sx={{
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
						backgroundColor: "#000000",
						color: "#D0E1E9",
						padding: "20px 24px",
						borderRadius: "10px 10px 0 0",
					}}
				>
					<Typography variant="h6" fontWeight={600} color="#D0E1E9">
						Edit Manager
					</Typography>
					<CustomIconButton onClick={handleClose}>
						<CloseIcon />
					</CustomIconButton>
				</Box>

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

				<Box
					sx={{
						backgroundColor: "#b5c4cb", // light background for body
						padding: "20px",
						borderRadius: "0 0 10px 10px",
					}}
				>
					<Box sx={{ display: "flex", flexWrap: "wrap", gap: 2 }}>
						{/* Manager Name */}
						<Box sx={{ flex: "1 1 48%" }}>
							<Typography
								variant="body2"
								fontWeight={500}
								mb={0.5}
								color="#000000"
								fontSize={"16px"}
							>
								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"
										sx={{ marginTop: 1 }}
										error={!!errors.name}
										helperText={errors.name?.message}
									/>
								)}
							/>
						</Box>

						{/* Email */}
						<Box sx={{ flex: "1 1 48%" }}>
							<Typography
								variant="body2"
								fontWeight={500}
								mb={0.5}
								color="#000000"
								fontSize={"16px"}
							>
								Email
							</Typography>
							<Controller
								name="email"
								control={control}
								rules={{
									required: "Email is required",
									pattern: {
										value: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
										message:
											"Please enter a valid email address (e.g., example@domain.com).",
									},
								}}
								render={({ field }) => (
									<CustomTextField
										{...field}
										fullWidth
										placeholder="Enter Email"
										size="small"
										sx={{ marginTop: 1 }}
										error={!!errors.email}
										helperText={errors.email?.message}
									/>
								)}
							/>
						</Box>

						{/* Phone Number */}
						<Box sx={{ flex: "1 1 48%" }}>
							<Typography
								variant="body2"
								fontWeight={500}
								mb={0.5}
								color="#000000"
								fontSize={"16px"}
							>
								Phone Number
							</Typography>
							<Controller
								name="phone"
								control={control}
								rules={{
									required: "Phone number is required",
									validate: (value) => {
										if (!/^[0-9]*$/.test(value)) {
											return "Only numbers are allowed";
										}
										if (value.length < 6) {
											return "Phone number must be at least 6 digits";
										}
										if (value.length > 14) {
											return "Phone number must be at most 14 digits";
										}
										return true; // No errors
									},
								}}
								render={({ field }) => (
									<CustomTextField
										{...field}
										fullWidth
										placeholder="Enter Phone Number"
										size="small"
										sx={{ marginTop: 1 }}
										error={!!errors.phone}
										helperText={errors.phone?.message}
									/>
								)}
							/>
						</Box>
					</Box>

					{/* Submit Button */}
					<Box
						sx={{
							display: "flex",
							justifyContent: "flex-end",
							mt: 3,
						}}
					>
						<Button
							type="submit"
							sx={{
								backgroundColor: "#000000",
								color: "#D0E1E9",
								borderRadius: "8px",
								fontSize:"16px",
								width: "150px",
								"&:hover": { backgroundColor: "#454545" },
								whiteSpace: "pre",
							}}
							disabled={loading}
						>
							{loading ? (
								<CircularProgress size={24} color="inherit" />
							) : (
								"Update Manager"
							)}
						</Button>
					</Box>
				</Box>
			</Box>
		</Modal>
	);
};
export default EditManagerModal;
