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;
