import React, { useEffect } from "react";
import { Box, Button, Typography, Modal, Grid } from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { useForm, Controller } from "react-hook-form";
import { CustomIconButton, CustomTextField } from "../AddUserModal/styled.css";

interface EditUserModalProps {
	open: boolean;
	handleClose: () => void;
	handleUpdate: (
		id: number,
		name: string,
		email: string,
		phone: string
	) => void;
	editRow: any;
}

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

const EditUserModal: React.FC<EditUserModalProps> = ({
	open,
	handleClose,
	handleUpdate,
	editRow,
}) => {
	const {
		control,
		handleSubmit,
		formState: { errors },
		setValue,
		reset,
	} = useForm<FormData>({
		defaultValues: {
			name: "",
			email: "",
			phone: "",
		},
	});

	// Set values if editRow is provided
	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);
		}
		handleClose(); // Close the modal
		reset(); // Reset the form fields
	};

	return (
		<Modal
			open={open}
			onClose={(e, reason) => {
				if (reason === "backdropClick") {
					return;
				}
				handleClose();
			}}
			aria-labelledby="edit-user-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}
						fontSize={"16px"}
						color="#D0E1E9"
					>
						Edit User
					</Typography>
					<CustomIconButton onClick={handleClose}>
						<CloseIcon />
					</CustomIconButton>
				</Box>

				{/* Input Fields */}
				
				<Box
					sx={{
						backgroundColor: "#b5c4cb", // light background for body
						padding: "20px",
						borderRadius: "0 0 10px 10px",
					}}
				>
					<Grid container spacing={2}>
						{/* Name Field */}
						<Grid item xs={12} sm={6}>
							<Typography
								variant="body2"
								fontWeight={500}
								mb={0.5}
								color="#000000"
								fontSize={"16px"}
							>
								Full 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",
									},
								}}
								render={({ field }) => (
									<CustomTextField
										{...field}
										fullWidth
										placeholder="Enter Full Name"
										size="small"
										sx={{ marginTop: 1 }}
										error={!!errors.name}
										helperText={errors.name?.message}
									/>
								)}
							/>
						</Grid>

						{/* Email Field */}
						<Grid item xs={12} sm={6}>
							<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: /\S+@\S+\.\S+/,
										message:
											"Please enter a valid email address.",
									},
								}}
								render={({ field }) => (
									<CustomTextField
										{...field}
										type="email"
										fullWidth
										placeholder="Enter Email"
										size="small"
										sx={{ marginTop: 1 }}
										error={!!errors.email}
										helperText={errors.email?.message}
									/>
								)}
							/>
						</Grid>

						{/* Phone Field */}
						<Grid item xs={12} sm={6}>
							<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 "At least 6 digits required";
										if (value.length > 14)
											return "At most 14 digits allowed";
										return true;
									},
								}}
								render={({ field }) => (
									<CustomTextField
										{...field}
										fullWidth
										placeholder="Enter Phone Number"
										size="small"
										sx={{ marginTop: 1 }}
										error={!!errors.phone}
										helperText={errors.phone?.message}
									/>
								)}
							/>
						</Grid>
					</Grid>

					{/* Submit Button */}
					<Box
						sx={{
							display: "flex",
							justifyContent: "flex-end",
							mt: 3,
						}}
					>
						<Button
							type="submit"
							sx={{
								backgroundColor: "#000000",
								color: "#D0E1E9",
								borderRadius: "8px",
								fontSize: "16px",
								width: "117px",
								"&:hover": { backgroundColor: "#454545" },
							}}
						>
							Update User
						</Button>
					</Box>
				</Box>

				{/* Submit Button */}
			</Box>
		</Modal>
	);
};

export default EditUserModal;
