import React, { useEffect, useState } from "react";
import { Box, Button, Typography, Modal, InputAdornment } 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 "../AddUserModal/styled.css";
import { autofillFix } from "../../shared-theme/customizations/autoFill";

//By Jaanvi : Edit Model :: 11-feb-25
interface AddEditCategoryModalProps {
	open: boolean;
	handleClose: () => void;
	handleCreate: (data: FormData) => void;
	handleUpdate: (
		id: string,
		name: string,
		email: string,
		phone: string,
		registeredAddress: string,
		password: string
	) => void;
	editRow: any;
}

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

const AddEditCategoryModal: React.FC<AddEditCategoryModalProps> = ({
	open,
	handleClose,
	handleCreate,
	handleUpdate,
	editRow,
}) => {
	const [showPassword, setShowPassword] = React.useState(false);
	const {
		control,
		handleSubmit,
		formState: { errors },
		setValue,
		reset,
		clearErrors,
	} = useForm<FormData>({
		defaultValues: {
			name: "",
			email: "",
			phone: "",
			registeredAddress: "",
			password: "",
		},
	});

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

	const togglePasswordVisibility = () => {
		setShowPassword((prev) => !prev);
	};

	useEffect(() => {
		if (editRow) {
			setValue("name", editRow.name);
			setValue("email", editRow.email);
			setValue("phone", editRow.phone);
			setValue("registeredAddress", editRow.registeredAddress);
			clearErrors();
		} else {
			reset();
			clearErrors();
		}
	}, [editRow, setValue, reset]);

	const handleCloseModal = () => {
		reset();
		clearErrors();
		handleClose();
	};

	return (
		<Modal
			open={open}
			key={open ? "open" : "closed"}
			onClose={(e, reason) => {
				if (reason === "backdropClick") {
					return;
				}

				handleCloseModal();
			}}
			aria-labelledby="add-edit-category-modal"
		>
			<Box
				sx={{
					position: "absolute",
					top: "50%",
					left: "50%",
					transform: "translate(-50%, -50%)",
					width: 600,
					boxShadow: 24,
					p: 0,
					borderRadius: 2,
				}}
			>
				{/* Header */}
				<Box
					sx={{
						display: "flex",
						justifyContent: "space-between",
						alignItems: "center",
						backgroundColor: "#000000",
						color: "#D0E1E9",

						padding: "16px 24px",
						borderRadius: "10px 10px 0 0",
					}}
				>
					{" "}
					<Typography
						variant="h6"
						fontWeight={600}
						fontSize={"16px"}
						color="#D0E1E9"
					>
						{editRow ? "Edit Admin" : "Add Admin"}
					</Typography>
					<CustomIconButton onClick={handleCloseModal}>
						<CloseIcon />
					</CustomIconButton>
				</Box>

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

				<Box
					sx={{
						backgroundColor: "#b5c4cb",
						padding: "24px",
						borderRadius: "0 0 10px 10px",
					}}
				>
					<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: "50%",
										...autofillFix,
									}}
								>
									<Typography
										variant="body2"
										fontWeight={500}
										color="#000000"
										fontSize={"16px"}
									>
										Admin Name
									</Typography>
									<Controller
										name="name"
										control={control}
										rules={{
											required: "Admin 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:
													"Admin Name must only contain letters and spaces",
											},
										}}
										render={({ field }) => (
											<CustomTextField
												{...field}
												required
												placeholder="Enter Admin Name"
												// autoComplete="new-username"
												type="text"
												fullWidth
												size="small"
												sx={{ marginTop: 1 }}
												error={!!errors.name}
												helperText={
													errors.name?.message
												}
											/>
										)}
									/>
								</Box>

								<Box
									sx={{
										display: "flex",
										flexDirection: "column",
										width: "50%",
										...autofillFix,
									}}
								>
									<Typography
										variant="body2"
										fontWeight={500}
										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}
												error={!!errors.email}
												helperText={
													errors.email?.message
												}
												id="email"
												type="email"
												placeholder="Email"
												autoComplete="new-email"
												sx={{ marginTop: 1 }}
												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: "50%",
											...autofillFix,
										}}
									>
										<Typography
											variant="body2"
											fontWeight={500}
											color="#000000"
											fontSize={"16px"}
										>
											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"
													autoComplete="new-password"
													type={
														showPassword
															? "text"
															: "password"
													}
													id="password"
													fullWidth
													color={
														errors.password
															? "error"
															: "primary"
													}
													size="small"
													sx={{ marginTop: 1 }}
													slotProps={{
														input: {
															endAdornment: (
																<InputAdornment position="end">
																	<CustomIconButton
																		aria-label="toggle password visibility"
																		onClick={
																			togglePasswordVisibility
																		}
																		edge="end"
																		sx={{
																			color: "#000000",
																		}}
																	>
																		{showPassword ? (
																			<VisibilityOff />
																		) : (
																			<Visibility />
																		)}
																	</CustomIconButton>
																</InputAdornment>
															),
														},
													}}
													error={!!errors.password}
													helperText={
														errors.password?.message
													}
												/>
											)}
										/>
									</Box>
								)}
								<Box
									sx={{
										display: "flex",
										flexDirection: "column",
										width: "50%",
										...autofillFix,
									}}
								>
									<Typography
										variant="body2"
										fontWeight={500}
										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}
												required
												placeholder="Enter Phone Number"
												size="small"
												sx={{ marginTop: 1 }}
												error={!!errors.phone}
												helperText={
													errors.phone?.message
												}
											/>
										)}
									/>
								</Box>
							</Box>

							{/* Third Row - One Input */}
							<Box
								sx={{
									display: "flex",
									flexDirection: "column",
									width: "50%",
									...autofillFix,
								}}
							>
								<Typography
									variant="body2"
									fontWeight={500}
									color="#000000"
									fontSize={"16px"}
								>
									Address
								</Typography>
								<Controller
									name="registeredAddress"
									control={control}
									rules={{
										required: "Address is required",
										maxLength: {
											value: 100,
											message:
												"Address cannot exceed 100 characters",
										},
									}}
									render={({ field }) => (
										<CustomTextField
											{...field}
											required
											sx={{ marginTop: 1 }}
											placeholder="Enter Address"
											fullWidth
											size="small"
											error={!!errors.registeredAddress}
											helperText={
												errors.registeredAddress
													?.message
											}
										/>
									)}
								/>
							</Box>
						</Box>

						{/* Submit Button */}
						<Box
							sx={{
								display: "flex",
								justifyContent: "flex-end",
								width: "100%",
								mt: 3,
							}}
						>
							<Button
								type="submit"
								sx={{
									backgroundColor: "#000000",
									color: "#D0E1E9",
									borderRadius: "8px",
									fontSize: "16px",
									width: "125px",
									"&:hover": { backgroundColor: "#454545" },
								}}
							>
								{editRow ? "Update Admin" : "Add Admin"}
							</Button>
						</Box>
					</form>
				</Box>
			</Box>
		</Modal>
	);
};

export default AddEditCategoryModal;
