import { Controller, useForm } from "react-hook-form";
import {
	Box,
	Button,
	Typography,
	Modal,
	IconButton,
	InputAdornment,
	Select,
	MenuItem,
	InputLabel,
	FormControl,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { Visibility, VisibilityOff } from "@mui/icons-material";
import { useDispatch, useSelector } from "react-redux";
import { addManager, managerList } from "../../redux/slices/managerSlice";
import {
	CustomIconButton,
	CustomTextField,
} from "../AddEditUserModel/styled.css.tsx";
import React, { useEffect, useState } from "react";
import { RootState } from "../../redux/reducers.ts";
import { stationList } from "../../redux/slices/stationSlice.ts";

export default function AddManagerModal({
	open,
	handleClose,
	handleAddManager,
	// Assume the stations prop contains a list of station objects with 'id' and 'name'
}) {
	const dispatch = useDispatch();
	const {
		control,
		register,
		handleSubmit,
		formState: { errors },
		reset,
	} = useForm();
	const [showPassword, setShowPassword] = useState(false);
   const stations = useSelector(
		(state: RootState) => state?.stationReducer.stations
   );
   
useEffect(() => {
	dispatch(stationList());
}, [dispatch]);

	// Handle form submission
	const onSubmit = async (data: any) => {
		// Retrieve the stationId based on the stationName selected
		const selectedStation = stations.find(
			(station) => station.name === data.stationName
		);
		const managerData = {
			name: data.name,
			email: data.email,
			phone: data.phone,
			password: data.password,
			stationId: selectedStation?.id, // Send stationId here
		};

		try {
			// Dispatch the addManager action
			await dispatch(addManager(managerData));
			dispatch(managerList());
			handleClose(); // Close modal after successful addition
			reset(); // Reset form fields
		} catch (error) {
			console.error("Error adding manager:", error);
		}
	};

	const togglePasswordVisibility = (e: React.MouseEvent) => {
		e.preventDefault(); // Prevent focus loss
		setShowPassword((prev) => !prev);
	};

	return (
		<Modal
			open={open}
			onClose={(e, reason) => {
				if (reason === "backdropClick") {
					return;
				}
				handleClose(); // Close modal when clicking cross or cancel
			}}
			aria-labelledby="add-manager-modal"
		>
			<Box
				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}>
						Add Manager
					</Typography>
					<CustomIconButton onClick={handleClose}>
						<CloseIcon />
					</CustomIconButton>
				</Box>

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

				{/* Form */}
				<form onSubmit={handleSubmit(onSubmit)}>
					{/* Manager Name */}
					<Box sx={{ display: "flex", gap: 2, mb: 2 }}>
						<Box sx={{ flex: 1 }}>
							<Typography variant="body2" fontWeight={500}>
								Manager Name
							</Typography>
							<CustomTextField
								fullWidth
								placeholder="Enter Manager Name"
								size="small"
								error={!!errors.name}
								helperText={
									errors.name ? errors.name.message : ""
								}
								{...register("name", {
									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]+$/,
										message:
											"Manager Name must only contain letters and spaces",
									},
								})}
							/>
						</Box>
					</Box>

					{/* Station Dropdown */}
					<Box sx={{ display: "flex", gap: 2, mb: 2 }}>
						<Box sx={{ flex: 1 }}>
							<Typography variant="body2" fontWeight={500}>
								Select Station
							</Typography>
							<FormControl fullWidth error={!!errors.stationName}>
								<InputLabel>Select Station</InputLabel>
								<Select
									{...register("stationName", {
										required: "Station Name is required",
									})}
									defaultValue=""
									size="small"
								>
									{stations.map((station) => (
										<MenuItem
											key={station.id}
											value={station.name}
										>
											{station.name}
										</MenuItem>
									))}
								</Select>
								{errors.stationName && (
									<Typography color="error" variant="body2">
										{errors.stationName.message}
									</Typography>
								)}
							</FormControl>
						</Box>
					</Box>

					{/* Email and Password */}
					<Box sx={{ display: "flex", gap: 2, mb: 2 }}>
						{/* Email */}
						<Box sx={{ flex: 1 }}>
							<Typography variant="body2" fontWeight={500}>
								Email
							</Typography>
							<CustomTextField
								fullWidth
								placeholder="Enter Manager Email"
								size="small"
								error={!!errors.email}
								helperText={
									errors.email ? errors.email.message : ""
								}
								{...register("email", {
									required: "Email is required",
									pattern: {
										value: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
										message: "Invalid email address",
									},
								})}
							/>
						</Box>

						{/* Password */}
						<Box sx={{ flex: 1 }}>
							<Typography variant="body2" fontWeight={500}>
								Password
							</Typography>
							<Controller
								name="password"
								control={control}
								rules={{
									required: "Password is required",
									minLength: {
										value: 6,
										message:
											"Password must be at least 6 characters long.",
									},
									pattern: {
										value: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,}$/,
										message:
											"Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character.",
									},
								}}
								render={({ field }) => (
									<CustomTextField
										{...field}
										required
										placeholder="Enter Password"
										type={
											showPassword ? "text" : "password"
										}
										fullWidth
										color={
											errors.password
												? "error"
												: "primary"
										}
										size="small"
										InputProps={{
											endAdornment: (
												<InputAdornment position="end">
													<CustomIconButton
														aria-label="toggle password visibility"
														onClick={
															togglePasswordVisibility
														}
														edge="end"
													>
														{showPassword ? (
															<VisibilityOff />
														) : (
															<Visibility />
														)}
													</CustomIconButton>
												</InputAdornment>
											),
										}}
										error={!!errors.password}
										helperText={errors.password?.message}
									/>
								)}
							/>
						</Box>
					</Box>

					{/* Phone Number */}
					<Box sx={{ display: "flex", gap: 2, mb: 2 }}>
						<Box sx={{ flex: 1 }}>
							<Typography variant="body2" fontWeight={500}>
								Phone Number
							</Typography>
							<CustomTextField
								fullWidth
								placeholder="Enter Phone Number"
								size="small"
								error={!!errors.phone}
								helperText={
									errors.phone ? errors.phone.message : ""
								}
								{...register("phone", {
									required: "Phone Number is required",
									pattern: {
										value: /^[0-9]{10}$/,
										message:
											"Phone number must be 10 digits",
									},
								})}
							/>
						</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" },
							}}
						>
							Add Manager
						</Button>
					</Box>
				</form>
			</Box>
		</Modal>
	);
}
