import React, { useEffect, useState } from "react";
import { Box, Button, Typography, TextField, Chip } from "@mui/material";
import AddEditRoleModal from "../../components/AddEditRoleModal";
import PermissionsTable from "../../pages/PermissionTable";
import { useForm } from "react-hook-form";
import CustomTable, { Column } from "../../components/CustomTable";
import { useDispatch, useSelector } from "react-redux";
import {
	createRole,
	roleList,
	toggleStatus,
} from "../../redux/slices/roleSlice";
import { AppDispatch, RootState } from "../../redux/store/store";
import { useNavigate } from "react-router-dom";
import AddEditRolePage from "../AddEditRolePage";
import SearchIcon from "@mui/icons-material/Search";

export default function RoleList() {
	const [modalOpen, setModalOpen] = useState(false);
	const { reset } = useForm();

	const [deleteModal, setDeleteModal] = React.useState<boolean>(false);
	const [viewModal, setViewModal] = React.useState<boolean>(false);
	const [rowData, setRowData] = React.useState<any | null>(null);
	const [searchTerm, setSearchTerm] = useState("");
	const [showPermissions, setShowPermissions] = useState(false);

	const dispatch = useDispatch<AppDispatch>();
	const navigate = useNavigate();

	const roles = useSelector((state: RootState) => state.roleReducer.roles);

	useEffect(() => {
		dispatch(roleList());
	}, [dispatch]);

	const handleClickOpen = () => {
		navigate("/panel/permissions"); // Navigate to the correct route
	};

	const handleCloseModal = () => {
		setModalOpen(false);
		setRowData(null);
		reset();
	};

	const handleStatusToggle = (id: string, newStatus: number) => {
		dispatch(toggleStatus({ id, status: newStatus }));
	};

	const handleCreate = async (data: {
		name: string;
		resource: {
			moduleName: string;
			moduleId: string;
			permissions: string[];
		}[];
	}) => {
		try {
			await dispatch(createRole(data));
			await dispatch(roleList()); // Refresh the list after creation
			handleCloseModal();
		} catch (error) {
			console.error("Creation failed", error);
		}
	};

	const categoryColumns: Column[] = [
		{ id: "srno", label: "Sr No" },
		{ id: "name", label: "Name" },
		{ id: "status", label: "Status" },
		{ id: "action", label: "Action", align: "center" },
	];

	const filterRoles = roles?.filter((role) =>
		role.name.toLocaleLowerCase().includes(searchTerm.toLowerCase())
	);

	const categoryRows = filterRoles?.length
		? filterRoles?.map((role: Role, index: number) => ({
				id: role.id,
				srno: index + 1,
				name: role.name,
				status: (
					<Chip
						label={role.status === 1 ? "Active" : "Inactive"}
						color={role.status === 1 ? "primary" : "default"}
						variant="outlined"
						sx={{
							fontWeight: 600,
							width: "80px",
							textAlign: "center",
							borderRadius: "4px",
						}}
					/>
				),
				statusValue: role.status,
		  }))
		: [];

	return (
		<>
			<Box
				sx={{
					width: "100%",
					display: "flex",
					flexDirection: { xs: "column", sm: "row" },
					justifyContent: "space-between",
					alignItems: "center",
					mb: 2, 
				}}
			>
				<TextField
					variant="outlined"
					size="small"
					placeholder="Search..."
					value={searchTerm}
					onChange={(e) => setSearchTerm(e.target.value)}
					sx={{
						width: { xs: "100%", sm: "30%" },
						marginBottom: { xs: 2, sm: 0 },
					}}
					InputProps={{
						startAdornment: (
							<SearchIcon
								sx={{ color: "#202020", marginRight: 1 }}
							/>
						),
					}}
				/>
				<Button
					variant="contained"
					size="small"
					onClick={handleClickOpen}
					sx={{
						textAlign: "center",
						width: { xs: "100%", sm: "auto" },
					}}
				>
					Add Role
				</Button>
			</Box>

			{showPermissions ? (
				<AddEditRolePage />
			) : (
				<CustomTable
					columns={categoryColumns}
					rows={categoryRows || []}
					setDeleteModal={setDeleteModal}
					deleteModal={deleteModal}
					setViewModal={setViewModal}
					viewModal={viewModal}
					setRowData={setRowData}
					setModalOpen={setModalOpen}
					handleStatusToggle={handleStatusToggle}
					tableType="roleList"
				/>
			)}
		</>
	);
}
