import React, { useEffect, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Check, Clear } from '@mui/icons-material';

import * as selectors from '../redux/selectors';
import { getDataAction } from '../redux/slices';

import CommonList from '@/modules/@common/List';
import CommonTable from '@/modules/@common/Table';
import { CircularProgress, Stack, TableCell, TableRow, Typography } from '@/mui/components';

import styles from './Permissions.module.scss';

function Permissions() {
  const dispatch = useDispatch();
  const data = useSelector(selectors.dataSelector);

  const headers = useMemo(() => data?.roles.map((role) => ({ id: role, label: role })) || [], [data?.roles]);

  // Fetch data on mount
  useEffect(() => {
    dispatch(getDataAction());
  }, [dispatch]);

  return (
    <CommonList
      title="Permissions"
      classes={{
        root: styles.CommonListRoot,
        content: styles.CommonListContent,
      }}
    >
      <div className={styles.Root}>
        {!data?.roles ? (
          <Stack justifyContent="center" alignItems="center" className={styles.LoaderRoot}>
            <CircularProgress />
          </Stack>
        ) : (
          <CommonTable
            stickyHeader
            configHeaders={[{ id: 'permission', label: 'Permission', className: styles.CellHeader }, ...headers]}
            data={data.permissions || []}
            configRenderRow={(row) => (
              <TableRow key={row.name} hover>
                <TableCell className={styles.Cell}>
                  <Typography variant="body2" color="text.primary" fontWeight={700}>
                    {row.name}
                  </Typography>
                </TableCell>
                {headers.map((header) => (
                  <TableCell key={header.id}>
                    {row.roles.includes(header.id) ? (
                      <Check fontSize="medium" htmlColor="success.main" />
                    ) : (
                      <Clear fontSize="medium" htmlColor="error.main" />
                    )}
                  </TableCell>
                ))}
              </TableRow>
            )}
          />
        )}
      </div>
    </CommonList>
  );
}

export default Permissions;
