import React, { useEffect, useState } from "react";
import {
	Box,
	Button,
	Typography,
	TextField,
	Modal,
	IconButton,
	InputAdornment,
	styled,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import Visibility from "@mui/icons-material/Visibility";
import VisibilityOff from "@mui/icons-material/VisibilityOff";
import { useForm, Controller } from "react-hook-form";
import { CustomIconButton, CustomTextField } from "./styled.css.tsx";


interface FormData {
	name: string;
	email: string;
	password: string;	
	phone: string;
}
interface AddUserModalProps {
	open: boolean;
	handleClose: () => void;
	handleCreate: (data: FormData) => void;
	handleUpdate: (
		id: string,
		name: string,
		email: string,
		phone: string,
	
	) => void;
	editRow: any;
}
const AddUserModal: React.FC<AddUserModalProps> = ({
	open,
	handleClose,
	handleCreate,
	handleUpdate,
	editRow,
}) => {
	const [showPassword, setShowPassword] = useState(false);

	const {
		control,
		handleSubmit,
		formState: { errors },
		reset,
		setValue,
	} = useForm<FormData>({
		defaultValues: {
			name: "",
			email: "",
			phone: "",
		},
	});
	
	useEffect(() => {
		if (editRow) {
			setValue("name", editRow.name);
			setValue("email", editRow.email);
			setValue("phone", editRow.phone);
		} else {
			reset();
		}
	}, [editRow, setValue,reset]);

	const onSubmit = (data: FormData) => {
		if (editRow) {
			handleUpdate(
				editRow.id,
				data.name,
				data.email,
				data.phone
			);
		} else {
			handleCreate(data);
		}

		handleClose();
		reset();
	};

	const togglePasswordVisibility = () => {
		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-user-modal"
		>
			<Box
				sx={{
					position: "absolute",
					top: "50%",
					left: "50%",
					transform: "translate(-50%, -50%)",
					width: 600, // Adjusted the width for a wider modal
					bgcolor: "background.paper",
					boxShadow: 24,
					p: 3,
					borderRadius: 2,
				}}
			>
				{/* Header */}
				<Box
					sx={{
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
					}}
				>
					<Typography variant="h6" fontWeight={600}>
						{editRow ? "Edit User" : "Add User"}
					</Typography>
					<CustomIconButton onClick={handleClose}>
						<CloseIcon />
					</CustomIconButton>
				</Box>

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

				{/* Form */}
				<form onSubmit={handleSubmit(onSubmit)}>
					{/* Input Fields */}
					<Box
						sx={{
							display: "flex",
							flexDirection: "column",
							gap: 2,
						}}
					>
						{/* First Row - Two Inputs */}
						<Box sx={{ display: "flex", gap: 2 }}>
							<Box
								sx={{
									display: "flex",
									flexDirection: "column",
									width: "100%",
								}}
							>
								<Typography variant="body2" fontWeight={500}>
									User Name
								</Typography>
								<Controller
									name="name"
									control={control}
									rules={{
										required: "User 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:
												"User Name must only contain letters and spaces",
										},
									}}
									render={({ field }) => (
										<CustomTextField
											{...field}
											required
											placeholder="Enter User Name"
											fullWidth
											size="small"
											error={!!errors.name}
											helperText={errors.name?.message}
										/>
									)}
								/>
							</Box>

							<Box
								sx={{
									display: "flex",
									flexDirection: "column",
									width: "100%",
								}}
							>
								<Typography variant="body2" fontWeight={500}>
									Email
								</Typography>
								<Controller
									name="email"
									control={control}
									rules={{
										required: "Email is required",
										pattern: {
											value: /\S+@\S+\.\S+/,
											message:
												"Please enter a valid email address.",
										},
									}}
									render={({ field }) => (
										<CustomTextField
											{...field}
											error={!!errors.email}
											helperText={errors.email?.message}
											id="email"
											type="email"
											placeholder="Email"
											required
											fullWidth
											color={
												errors.email
													? "error"
													: "primary"
											}
										/>
									)}
								/>
							</Box>
						</Box>

						{/* Second Row - Two Inputs */}
						<Box sx={{ display: "flex", gap: 2 }}>
						{!editRow && (	<Box
								sx={{
									display: "flex",
									flexDirection: "column",
									width: "100%",
								}}
							>
								<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"
											}
											id="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
								sx={{
									display: "flex",
									flexDirection: "column",
									width: "100%",
								}}
							>
								<Typography variant="body2" fontWeight={500}>
									Phone Number
								</Typography>
								<Controller
									name="phone"
									control={control}
									rules={{
										required: "Phone number is required",
										pattern: {
											value: /^[0-9]*$/,
											message: "Only numbers are allowed",
										},
										minLength: {
											value: 6,
											message:
												"Phone number must be at least 6 digits",
										},
										maxLength: {
											value: 14,
											message:
												"Phone number must be at most 14 digits",
										},
									}}
									render={({ field }) => (
										<CustomTextField
											{...field}
											required
											placeholder="Enter Phone Number"
											size="small"
											error={!!errors.phone}
											helperText={errors.phone?.message}
										/>
									)}
								/>
							</Box>
						</Box>
					</Box>

					{/* Submit Button */}
					<Box
						sx={{
							display: "flex",
							justifyContent: "flex-end",
							width: "100%",
							mt: 3,
						}}
					>
						<Button
							type="submit"
							sx={{
								backgroundColor: "#52ACDF",
								color: "white",
								borderRadius: "8px",
								width: "117px",
								"&:hover": { backgroundColor: "#439BC1" },
							}}
						>
							{editRow ? "Update User" : "Add User"}
						</Button>
					</Box>
				</form>
			</Box>
		</Modal>
	);
};

export default AddUserModal;



