import { Box, Button, Modal, Typography, Divider } from "@mui/material";
import { RootState } from "../../../redux/store/store";
import { useSelector } from "react-redux";
import { useEffect, useState } from "react";
import CloseIcon from "@mui/icons-material/Close";

type Props = {
	open: boolean;
	setViewModal: Function;
	id?: string;
};

const style = {
	position: "absolute",
	top: "50%",
	left: "50%",
	transform: "translate(-50%, -50%)",
	width: 400,
	bgcolor: "background.paper",
	borderRadius: 2,
	boxShadow: "0px 4px 20px rgba(0, 0, 0, 0.15)",
	p: 4,
	display: "flex",
	flexDirection: "column",
	alignItems: "center",
	gap: 2,
};

const btnStyle = {
	mt: 2,
	px: 5,
	py: 1.2,
	width: "100%",
	textTransform: "capitalize",
};

export default function ViewModal({ open, setViewModal, id }: Props) {
	const { admins } = useSelector((state: RootState) => state.adminReducer);
	const [selectedAdmin, setSelectedAdmin] = useState<any>(null);

	useEffect(() => {
		if (id) {
			const admin = admins.find((admin) => admin.id === id);
			setSelectedAdmin(admin);
		}
	}, [id, admins]);

	return (
		<Modal
			open={open}
			aria-labelledby="modal-title"
			aria-describedby="modal-description"
		>
			<Box sx={style}>
				<Typography
					id="modal-title"
					variant="h5"
					fontWeight="bold"
					sx={{ width: "100%" }}
				>
					<Box
						sx={{
							display: "flex",
							alignItems: "center",
							justifyContent: "space-between",
							width: "100%",
						}}
					>
						<Box sx={{ flex: 1, textAlign: "center" }}>
							{selectedAdmin?.name}'s Details
						</Box>
						<Box
							onClick={() => setViewModal(false)}
							sx={{
								cursor: "pointer",
								display: "flex",
								alignItems: "center",
							}}
						>
							<CloseIcon />
						</Box>
					</Box>
				</Typography>

				<Divider sx={{ width: "100%" }} />

				{selectedAdmin ? (
					<Box
						sx={{
							width: "80%",
							textAlign: "left",
							display: "flex",
							flexDirection: "column",
							gap: 1.5,
							whiteSpace: "pre-wrap", // the text wraps properly
							wordBreak: "break-word", 
							overflowWrap: "break-word",
						}}
					>
						<Typography variant="body1">
							<b>Name:</b> {selectedAdmin.name}
						</Typography>
						<Typography variant="body1">
							<strong>Email:</strong> {selectedAdmin.email}
						</Typography>
						<Typography variant="body1">
							<strong>Phone:</strong> {selectedAdmin.phone}
						</Typography>
						<Typography variant="body1">
							<strong>Address:</strong>{" "}
							{selectedAdmin.registeredAddress ?? "N/A"}
						</Typography>
					</Box>
				) : (
					<Typography align="center">
						No admin found with this ID
					</Typography>
				)}

				{/* <Button variant="contained" color="error" sx={btnStyle} onClick={() => setViewModal(false)}>
					Close
				</Button> */}
			</Box>
		</Modal>
	);
}
