// import * as React from "react";
// import { styled } from "@mui/material/styles";
// import Table from "@mui/material/Table";
// import TableBody from "@mui/material/TableBody";
// import TableCell, { tableCellClasses } from "@mui/material/TableCell";
// import TableContainer from "@mui/material/TableContainer";
// import TableHead from "@mui/material/TableHead";
// import TableRow from "@mui/material/TableRow";
// import Paper, { paperClasses } from "@mui/material/Paper";
// import { adminList, deleteAdmin } from "../../redux/slices/adminSlice";
// import { useDispatch } from "react-redux";
// import {
// 	Box,
// 	Button,
// 	dividerClasses,
// 	IconButton,
// 	listClasses,
// 	Menu,
// } from "@mui/material";
// import MoreVertRoundedIcon from "@mui/icons-material/MoreVertRounded";
// import DeleteModal from "../Modals/DeleteModal";
// import { AppDispatch } from "../../redux/store/store";
// import ViewModal from "../Modals/ViewModal";

// // Styled components for customization
// const StyledTableCell = styled(TableCell)(({ theme }) => ({
// 	[`&.${tableCellClasses.head}`]: {
// 		backgroundColor: " #1565c0",
// 		color: theme.palette.common.white,
// 	},
// 	[`&.${tableCellClasses.body}`]: {
// 		fontSize: 14,
// 	},
// }));

// const StyledTableRow = styled(TableRow)(({ theme }) => ({
// 	"&:nth-of-type(odd)": {
// 		backgroundColor: theme.palette.action.hover,
// 	},
// 	"&:last-child td, &:last-child th": {
// 		border: 0,
// 	},
// }));

// export interface Column {
// 	id: string;
// 	label: string;
// 	align?: "left" | "center" | "right";
// }

// interface Row {
// 	[key: string]: any;
// }

// interface CustomTableProps {
// 	columns: Column[];
// 	rows: Row[];
// 	setDeleteModal: Function;
// 	setRowData: Function;
// 	setModalOpen: Function;
// 	viewModal: boolean;
// 	setViewModal: Function;
// 	deleteModal: boolean;
// 	handleStatusToggle: (id: string, currentStatus: number) => void;
// 	tableType?: string;
// }

// const CustomTable: React.FC<CustomTableProps> = ({
// 	columns,
// 	rows,
// 	setDeleteModal,
// 	deleteModal,
// 	viewModal,
// 	setRowData,
// 	setViewModal,
// 	setModalOpen,
// 	handleStatusToggle,
// 	tableType,
// }) => {
// 	const dispatch = useDispatch<AppDispatch>();
// 	const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
// 	const [selectedRow, setSelectedRow] = React.useState<Row | null>(null);

// 	const open = Boolean(anchorEl);

// 	const handleClick = (event: React.MouseEvent<HTMLElement>, row: Row) => {
// 		setAnchorEl(event.currentTarget);
// 		setSelectedRow(row); // Ensure the row data is set
// 		setRowData(row);
// 	};

// 	const handleClose = () => {
// 		setAnchorEl(null);
// 	};

// 	const isImage = (value: any) => {
// 		if (typeof value === "string") {
// 			return value.startsWith("http") || value.startsWith("data:image"); // Check for URL or base64 image
// 		}
// 		return false;
// 	};

// 	const handleDeleteButton = (id: string | undefined) => {
// 		if (!id) console.error("ID not found", id);

// 		dispatch(deleteAdmin(id || ""));
// 		setDeleteModal(false); // Close the modal only after deletion
// 		handleClose();
// 	};

// 	const handleViewButton = (id: string | undefined) => {
// 		if (!id) console.error("ID not found", id);

// 		dispatch(adminList());
// 		setViewModal(false);
// 	};

// 	const handleToggleStatus = () => {
// 		if (selectedRow) {
// 			// Toggle the opposite of current status
// 			const newStatus = selectedRow.statusValue === 1 ? 0 : 1;
// 			handleStatusToggle(selectedRow.id, newStatus);
// 		}
// 		handleClose();
// 	};

// 	return (
// 		<Box sx={{ overflowX: "auto", width: "100%" }}>
// 			<TableContainer component={Paper}>
// 				<Table
// 					sx={{
// 						minWidth: 700,
// 						width: "100%",
// 						tableLayout: "auto",
// 					}}
// 					aria-label="customized table"
// 				>
// 					<TableHead>
// 						<TableRow>
// 							{columns.map((column) => (
// 								<StyledTableCell
// 									key={column.id}
// 									align={column.align || "left"}
// 									sx={{
// 										whiteSpace: "nowrap", // Prevent wrapping
// 										// fontSize: { xs: "12px", sm: "14px" },
// 										fontSize: {
// 											xs: "10px",
// 											sm: "12px",
// 											md: "14px",
// 										}, // Adjust font size responsively
// 										padding: { xs: "8px", sm: "12px" },
// 									}}
// 								>
// 									{column.label}
// 								</StyledTableCell>
// 							))}
// 						</TableRow>
// 					</TableHead>
// 					<TableBody>
// 						{rows.map((row, rowIndex) => (
// 							<StyledTableRow key={rowIndex}>
// 								{columns.map((column) => (
// 									<StyledTableCell
// 										key={column.id}
// 										align={column.align || "left"}
// 										sx={{
// 											whiteSpace: "nowrap", // Prevent wrapping
// 											fontSize: {
// 												xs: "10px",
// 												sm: "12px",
// 												md: "14px",
// 											}, // Adjust font size responsively
// 											padding: { xs: "8px", sm: "12px" },
// 										}}
// 									>
// 										{isImage(row[column.id]) ? (
// 											<img
// 												src={row[column.id]}
// 												alt="Row "
// 												style={{
// 													width: "50px",
// 													height: "50px",
// 													objectFit: "cover",
// 												}}
// 											/>
// 										) : column.id !== "action" ? (
// 											row[column.id]
// 										) : (
// 											<IconButton
// 												onClick={(e) => {
// 													handleClick(e, row);
// 													setRowData(row); // Store the selected row
// 												}}
// 											>
// 												<MoreVertRoundedIcon />
// 											</IconButton>
// 										)}
// 									</StyledTableCell>
// 								))}
// 							</StyledTableRow>
// 						))}
// 					</TableBody>
// 				</Table>
// 			</TableContainer>

// 			{/* Menu Actions */}
// 			{open && (
// 				<Menu
// 					anchorEl={anchorEl}
// 					id="menu"
// 					open={open}
// 					onClose={handleClose}
// 					onClick={handleClose}
// 					transformOrigin={{ horizontal: "right", vertical: "top" }}
// 					anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
// 					sx={{
// 						[`& .${listClasses.root}`]: {
// 							padding: "4px",
// 						},
// 						[`& .${paperClasses.root}`]: {
// 							padding: 0,
// 						},
// 						[`& .${dividerClasses.root}`]: {
// 							margin: "4px -4px",
// 						},
// 					}}
// 				>
// 					<Box
// 						sx={{
// 							display: "flex",
// 							flexDirection: "column",
// 							justifyContent: "flex-start",
// 						}}
// 					>
// 						<Button
// 							variant="text"
// 							onClick={(e) => {
// 								e.stopPropagation();
// 								setViewModal(true);
// 							}}
// 							color="primary"
// 							sx={{
// 								justifyContent: "flex-start",
// 								py: 0,
// 								textTransform: "capitalize",
// 							}}
// 						>
// 							View
// 						</Button>
// 						{viewModal && (
// 							<ViewModal
// 								handleView={() =>
// 									handleViewButton(selectedRow?.id)
// 								}
// 								open={viewModal}
// 								setViewModal={setViewModal}
// 								id={selectedRow?.id}
// 							/>
// 						)}
// 						<Button
// 							variant="text"
// 							onClick={() => setModalOpen(true)}
// 							color="primary"
// 							sx={{
// 								justifyContent: "flex-start",
// 								py: 0,
// 								textTransform: "capitalize",
// 							}}
// 						>
// 							Edit
// 						</Button>

// 						{tableType === "roleList" && (
// 							<Button variant="text" onClick={handleToggleStatus}>
// 								{selectedRow.statusValue === 1
// 									? "Deactivate"
// 									: "Activate"}
// 							</Button>
// 						)}

// 						<Button
// 							variant="text"
// 							onClick={(e) => {
// 								e.stopPropagation();
// 								setDeleteModal(true);
// 							}}
// 							color="error"
// 							sx={{
// 								justifyContent: "flex-start",
// 								py: 0,
// 								textTransform: "capitalize",
// 							}}
// 						>
// 							Delete
// 						</Button>
// 						{deleteModal && (
// 							<DeleteModal
// 								handleDelete={() =>
// 									handleDeleteButton(selectedRow?.id)
// 								}
// 								open={deleteModal}
// 								setDeleteModal={setDeleteModal}
// 								id={selectedRow?.id}
// 							/>
// 						)}
// 					</Box>
// 				</Menu>
// 			)}
// 		</Box>
// 	);
// };

// export default CustomTable;
import * as React from "react";
import { styled } from "@mui/material/styles";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell, { tableCellClasses } from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper, { paperClasses } from "@mui/material/Paper";
import { adminList, deleteAdmin } from "../../redux/slices/adminSlice";
import { useDispatch } from "react-redux";
import {
	Box,
	Button,
	IconButton,
	InputAdornment,
	Menu,
	Pagination,
	TextField,
	Typography,
} from "@mui/material";
import MoreHorizRoundedIcon from "@mui/icons-material/MoreHorizRounded"; 
import DeleteModal from "../Modals/DeleteModal";
import { AppDispatch } from "../../redux/store/store";
import ViewModal from "../Modals/ViewModal";
import SearchIcon from "@mui/icons-material/Search";
import TuneIcon from "@mui/icons-material/Tune";

// Styled components for customization
const StyledTableCell = styled(TableCell)(({ theme }) => ({
	[`&.${tableCellClasses.head}`]: {
		backgroundColor: "#454545", // Changed to #272727 for the header
		color: theme.palette.common.white,
		borderBottom: "none", // Remove any border at the bottom of the header
	},
	[`&.${tableCellClasses.body}`]: {
		fontSize: 14,
		borderBottom: "1px solid #454545", // Adding border to body cells
	},
}));

const StyledTableRow = styled(TableRow)(({ theme }) => ({
	"&:nth-of-type(odd)": {
		backgroundColor: theme.palette.action.hover,
	},
	"& td, th": {
		borderColor: "#454545", // Applying border color to both td and th
		borderWidth: "1px", // Set border width to ensure it appears
	},
}));

export interface Column {
	id: string;
	label: string;
	align?: "left" | "center" | "right";
}

interface Row {
	[key: string]: any;
}

interface CustomTableProps {
	columns: Column[];
	rows: Row[];
	setDeleteModal: Function;
	setRowData: Function;
	setModalOpen: Function;
	viewModal: boolean;
	setViewModal: Function;
	deleteModal: boolean;
	handleStatusToggle: (id: string, currentStatus: number) => void;
	tableType: string; // Adding tableType prop to change header text dynamically
	handleClickOpen: () => void;
}

const CustomTable: React.FC<CustomTableProps> = ({
	columns,
	rows,
	setDeleteModal,
	deleteModal,
	viewModal,
	setRowData,
	setViewModal,
	setModalOpen,
	handleStatusToggle,
	tableType,
	handleClickOpen,

}) => {
	const dispatch = useDispatch<AppDispatch>();
	const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
	const [selectedRow, setSelectedRow] = React.useState<Row | null>(null);
	const [searchQuery, setSearchQuery] = React.useState("");
	const [currentPage, setCurrentPage] = React.useState(1);
	const usersPerPage = 10;

	const open = Boolean(anchorEl);

	const handleClick = (event: React.MouseEvent<HTMLElement>, row: Row) => {
		setAnchorEl(event.currentTarget);
		setSelectedRow(row); // Ensure the row data is set
		setRowData(row);
	};

	const handleClose = () => {
		setAnchorEl(null);
	};

	const isImage = (value: any) => {
		if (typeof value === "string") {
			return value.startsWith("http") || value.startsWith("data:image"); // Check for URL or base64 image
		}
		return false;
	};

	const handleDeleteButton = (id: string | undefined) => {
		if (!id) console.error("ID not found", id);

		dispatch(deleteAdmin(id || ""));
		setDeleteModal(false); // Close the modal only after deletion
		handleClose();
	};

	const handleViewButton = (id: string | undefined) => {
		if (!id) console.error("ID not found", id);

		dispatch(adminList());
		setViewModal(false);
	};

	const handleToggleStatus = () => {
		if (selectedRow) {
			// Toggle the opposite of current status
			const newStatus = selectedRow.statusValue === 1 ? 0 : 1;
			handleStatusToggle(selectedRow.id, newStatus);
		}
		handleClose();
	};

const filteredRows = rows.filter(
	(row) =>
		(row.name &&
			row.name.toLowerCase().includes(searchQuery.toLowerCase())) ||
		false
);


	const indexOfLastRow = currentPage * usersPerPage;
	const indexOfFirstRow = indexOfLastRow - usersPerPage;
	const currentRows = filteredRows.slice(indexOfFirstRow, indexOfLastRow);

	const handlePageChange = (
		event: React.ChangeEvent<unknown>,
		value: number
	) => {
		setCurrentPage(value);
	};

	return (
		<Box
			sx={{
				width: "calc(100% - 48px)",
				margin: "0 auto",
				padding: "24px",
				backgroundColor: "#1C1C1C",
				borderRadius: "12px",
			}}
		>
			<Typography
				sx={{
					color: "#FFFFFF",
					fontWeight: 500,
					fontSize: "18px",
					fontFamily: "Gilroy",
				}}
			>
				{/* Dynamic title based on the page type */}
				{tableType === "admin"
					? "Admin"
					: tableType === "role"
					? "Roles"
					: tableType === "user"
					? "Users"
					: tableType === "manager"
					? "Managers"
					: tableType === "vehicle"
					? "Vehicles"
					: "List"}
			</Typography>

			{/* Search & Buttons Section */}
			<Box
				sx={{
					display: "flex",
					gap: "16px",
					marginTop: "16px",
					alignItems: "center",
				}}
			>
				<TextField
					variant="outlined"
					placeholder="Search"
					sx={{
						width: "422px",
						borderRadius: "12px",
						input: { color: "#FFFFFF" },
						backgroundColor: "#272727",
						"& .MuiOutlinedInput-root": {
							borderRadius: "12px",
							"& fieldset": { borderColor: "#FFFFFF" },
							"&:hover fieldset": { borderColor: "#FFFFFF" },
							"&.Mui-focused fieldset": {
								borderColor: "#52ACDF",
							},
						},
					}}
					InputProps={{
						startAdornment: (
							<InputAdornment position="start">
								<SearchIcon sx={{ color: "#272727" }} />
							</InputAdornment>
						),
					}}
					value={searchQuery}
					onChange={(e) => setSearchQuery(e.target.value)}
				/>
				<Box
					sx={{
						display: "flex",
						justifyContent: "flex-end",
						width: "100%",
					}}
				>
					<Button
						sx={{
							backgroundColor: "#52ACDF",
							color: "white",
							borderRadius: "8px",
							width: "184px",
							"&:hover": { backgroundColor: "#439BC1" },
						}}
						onClick={() => handleClickOpen()}
					>
						Add{" "}
						{tableType === "admin"
							? "Admin"
							: tableType === "role"
							? "Role"
							: tableType === "user"
							? "User"
							: tableType === "manager"
							? "Manager"
							: tableType === "vehicle"
							? "Vehicle"
							: "Item"}
					</Button>
				</Box>

				<IconButton
					sx={{
						width: "44px",
						height: "44px",
						borderRadius: "8px",
						backgroundColor: "#272727",
						color: "#52ACDF",
						"&:hover": { backgroundColor: "#333333" },
					}}
				>
					<TuneIcon />
				</IconButton>
			</Box>

			{/* Table Section */}
			<TableContainer
				component={Paper}
				sx={{
					marginTop: "24px",
					backgroundColor: "#1C1C1C",
					borderRadius: "12px",
					overflow: "hidden",
				}}
			>
				<Table>
					<TableHead
						sx={{
							backgroundColor: "#272727",
							borderBottom: "none",
						}}
					>
						{" "}
						<TableRow>
							{columns.map((column) => (
								<StyledTableCell
									key={column.id}
									sx={{
										color: "#FFFFFF",
										fontWeight: "bold",
									}}
								>
									{column.label}
								</StyledTableCell>
							))}
						</TableRow>
					</TableHead>
					<TableBody>
						{currentRows.map((row, rowIndex) => (
							<StyledTableRow key={rowIndex}>
								{columns.map((column) => (
									<StyledTableCell
										key={column.id}
										sx={{
											color: "#FFFFFF",
											backgroundColor: "#272727",
										}}
									>
										{isImage(row[column.id]) ? (
											<img
												src={row[column.id]}
												alt="Row "
												style={{
													width: "50px",
													height: "50px",
													objectFit: "cover",
												}}
											/>
										) : column.id !== "action" ? (
											row[column.id]
										) : (
											<IconButton
												onClick={(e) => {
													handleClick(e, row);
													setRowData(row); // Store the selected row
												}}
												sx={{
													padding: 0,
													minWidth: 0,
													width: "auto",
													height: "auto",
													backgroundColor:
														"transparent",
													color: "#FFFFFF",
													border: "none",
													"&:hover": {
														backgroundColor:
															"transparent",
													},
												}}
											>
												<MoreHorizRoundedIcon
													sx={{ fontSize: "24px" }}
												/>
											</IconButton>
										)}
									</StyledTableCell>
								))}
							</StyledTableRow>
						))}
					</TableBody>
				</Table>
			</TableContainer>

			{/* Pagination */}
			<Box
				sx={{
					display: "flex",
					justifyContent: "flex-end",
					alignItems: "center",
					marginTop: "16px",
				}}
			>
				<Typography
					sx={{ color: "white", fontSize: "16px", fontWeight: 500 }}
				>
					Page Number :
				</Typography>
				<Pagination
					count={Math.ceil(filteredRows.length / usersPerPage)}
					page={currentPage}
					onChange={handlePageChange}
					siblingCount={0}
					boundaryCount={0}
					sx={{
						"& .MuiPaginationItem-root": {
							color: "white",
							borderRadius: "0px",
						},
						"& .MuiPaginationItem-page.Mui-selected": {
							backgroundColor: "transparent",
							fontWeight: "bold",
							color: "#FFFFFF",
						},
					}}
				/>
			</Box>

			{/* Menu Actions */}
			{open && (
				<Menu
					anchorEl={anchorEl}
					id="menu"
					open={open}
					onClose={handleClose}
					onClick={handleClose}
					transformOrigin={{ horizontal: "right", vertical: "top" }}
					anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
					sx={{
						[`& .${paperClasses.root}`]: {
							padding: 0,
						},
					}}
				>
					<Box
						sx={{
							display: "flex",
							flexDirection: "column",
							justifyContent: "flex-start",
						}}
					>
						<Button
							variant="text"
							onClick={(e) => {
								e.stopPropagation();
								setViewModal(true);
							}}
							color="primary"
							sx={{
								justifyContent: "flex-start",
								py: 0,
								fontWeight: "bold",
								color: "#52ACDF",
							}}
						>
							View
						</Button>
						{viewModal && (
							<ViewModal
								handleView={() =>
									handleViewButton(selectedRow?.id)
								}
								open={viewModal}
								setViewModal={setViewModal}
								id={selectedRow?.id}
							/>
						)}

						<Button
							variant="text"
							onClick={() => setModalOpen(true)}
							color="primary"
							sx={{
								justifyContent: "flex-start",
								py: 0,
								textTransform: "capitalize",
							}}
						>
							Edit
						</Button>
						{tableType === "role" && (
							<Button
								variant="text"
								onClick={(e) => {
									e.stopPropagation();
									handleToggleStatus();
								}}
								color="secondary"
								sx={{
									justifyContent: "flex-start",
									py: 0,
									fontWeight: "bold",
								}}
							>
								{selectedRow?.statusValue === 1
									? "Deactivate"
									: "Activate"}
							</Button>
						)}

						<Button
							variant="text"
							onClick={(e) => {
								e.stopPropagation();
								setDeleteModal(true);
							}}
							color="error"
							sx={{
								justifyContent: "flex-start",
								py: 0,
								fontWeight: "bold",
								color: "red",
							}}
						>
							Delete
						</Button>
					</Box>
				</Menu>
			)}

			{/* Modals */}
			{deleteModal && (
				<DeleteModal
					handleDelete={() => handleDeleteButton(selectedRow?.id)}
					open={deleteModal}
					setDeleteModal={setDeleteModal}
					id={selectedRow?.id}
				/>
			)}
		</Box>
	);
};

export default CustomTable;
