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/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";


export default function RoleList() {
	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 [modalOpen, setModalOpen] = 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 (
		<>
			{showPermissions ? (
				<AddEditRolePage />
			) : (
				<CustomTable
					columns={categoryColumns}
					rows={categoryRows || []}
					setDeleteModal={setDeleteModal}
					deleteModal={deleteModal}
					setViewModal={setViewModal}
					viewModal={viewModal}
					setRowData={setRowData}
					setModalOpen={setModalOpen}
					handleStatusToggle={handleStatusToggle}
					tableType="role"
					handleClickOpen={handleClickOpen}
				/>
			)}
		</>
	);
}


