import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Edit } from '@mui/icons-material';

import * as selectors from '../../../redux/selectors';
import { setAction, updatePermissionsMetadataAction, updateRoleModuleMetadataAction } from '../../../redux/slices';

import { FormRow, useFormSettings } from '@/modules/@common/Form';
import UpdatePermissionDialog from '../../UpdatePermissionDialog/UpdatePermissionDialog';
import UpdateRoleModuleDialog from '../../UpdateRoleModuleDialog/UpdateRoleModuleDialog';
import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  Checkbox,
  FormControlLabel,
  IconButton,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableRow,
  Typography,
} from '@/mui/components';

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

const TYPE_PERMISSION_GET = 'GET';
const TYPE_PERMISSION_POST = 'POST';
const TYPE_PERMISSION_PUT = 'PUT';
const TYPE_PERMISSION_DELETE = 'DELETE';

function PermissionsTab() {
  const dispatch = useDispatch();
  const { size } = useFormSettings();
  const [expandedPermission, setExpandedPermission] = useState(null);
  const [updateRoleModuleMetadataDialog, setUpdateRoleModuleMetadataDialog] = useState(null);
  const [updatePermissionMetadataDialog, setUpdatePermissionMetadataDialog] = useState(null);

  const permissionsModules = useSelector(selectors.permissionsModulesSelector);
  const permissions = useSelector(selectors.permissionsSelector);

  const handleSetExpandedPermission = (permissionId) =>
    setExpandedPermission((prev) => (prev === permissionId ? null : permissionId));

  const handleSetPermission = (permissionName) => {
    dispatch(
      setAction({
        permissions: {
          ...permissions,
          [permissionName]: !permissions[permissionName],
        },
      }),
    );
  };

  const handleUpdateRoleMetadataModule = (data) => {
    dispatch(updateRoleModuleMetadataAction(data));
  };

  const handleUpdatePermissionMetadata = (data) => {
    dispatch(updatePermissionsMetadataAction(data));
  };

  return (
    <>
      {permissionsModules.map((permission) => {
        const crudPermissions = permission.permissions.reduce((acc, per) => {
          if (
            [TYPE_PERMISSION_GET, TYPE_PERMISSION_POST, TYPE_PERMISSION_DELETE, TYPE_PERMISSION_PUT].includes(per.type)
          ) {
            acc[per.type] = per;
          }
          return acc;
        }, {});

        const innerPermissions = permission.permissions.filter(
          (per) =>
            ![TYPE_PERMISSION_GET, TYPE_PERMISSION_POST, TYPE_PERMISSION_DELETE, TYPE_PERMISSION_PUT].includes(
              per.type,
            ),
        );
        return (
          <FormRow key={permission.id} fullWidth>
            <Accordion
              expanded={expandedPermission === permission.id}
              onChange={() => handleSetExpandedPermission(permission.id)}
            >
              <AccordionSummary>
                <Stack fullWidth direction="row" justifyContent="space-between">
                  <Stack direction="row" alignItems="center" gap={1}>
                    <Typography variant="subtitle1" color="text.info" fontWeight={700}>
                      {permission.displayName}
                    </Typography>
                    <IconButton
                      size={size}
                      color="info"
                      onClick={(e) => {
                        e.stopPropagation();
                        setUpdateRoleModuleMetadataDialog({
                          id: permission.id,
                          displayName: permission.displayName,
                          description: permission.description,
                          crudPermissions: [
                            crudPermissions[TYPE_PERMISSION_GET],
                            crudPermissions[TYPE_PERMISSION_POST],
                            crudPermissions[TYPE_PERMISSION_PUT],
                            crudPermissions[TYPE_PERMISSION_DELETE],
                          ],
                        });
                      }}
                    >
                      <Edit />
                    </IconButton>
                  </Stack>
                  <Stack direction="row" alignItems="center" gap={1}>
                    <Stack className={styles.PermissionContainer} alignItems="center">
                      {crudPermissions[TYPE_PERMISSION_GET]?.name && (
                        <FormControlLabel
                          label="Read"
                          control={
                            <Checkbox
                              size={size}
                              checked={!!permissions[crudPermissions[TYPE_PERMISSION_GET]?.name]}
                              onChange={() => {
                                handleSetPermission(crudPermissions[TYPE_PERMISSION_GET]?.name);
                              }}
                            />
                          }
                          onClick={(e) => {
                            e.stopPropagation();
                          }}
                        />
                      )}
                    </Stack>

                    <Stack className={styles.PermissionContainer} alignItems="center">
                      {crudPermissions[TYPE_PERMISSION_POST]?.name && (
                        <FormControlLabel
                          label="Create"
                          control={
                            <Checkbox
                              size={size}
                              checked={!!permissions[crudPermissions[TYPE_PERMISSION_POST]?.name]}
                              onChange={() => {
                                handleSetPermission(crudPermissions[TYPE_PERMISSION_POST]?.name);
                              }}
                            />
                          }
                          onClick={(e) => {
                            e.stopPropagation();
                          }}
                        />
                      )}
                    </Stack>
                    <Stack className={styles.PermissionContainer} alignItems="center">
                      {crudPermissions[TYPE_PERMISSION_PUT]?.name && (
                        <FormControlLabel
                          label="Edit"
                          control={
                            <Checkbox
                              size={size}
                              checked={!!permissions[crudPermissions[TYPE_PERMISSION_PUT]?.name]}
                              onChange={() => {
                                handleSetPermission(crudPermissions[TYPE_PERMISSION_PUT]?.name);
                              }}
                            />
                          }
                          onClick={(e) => {
                            e.stopPropagation();
                          }}
                        />
                      )}
                    </Stack>
                    <Stack className={styles.PermissionContainer} alignItems="center">
                      {crudPermissions[TYPE_PERMISSION_DELETE]?.name && (
                        <FormControlLabel
                          label="Delete"
                          control={
                            <Checkbox
                              size={size}
                              checked={!!permissions[crudPermissions[TYPE_PERMISSION_DELETE]?.name]}
                              onChange={() => {
                                handleSetPermission(crudPermissions[TYPE_PERMISSION_DELETE]?.name);
                              }}
                            />
                          }
                          onClick={(e) => {
                            e.stopPropagation();
                          }}
                        />
                      )}
                    </Stack>
                  </Stack>
                </Stack>
              </AccordionSummary>
              <AccordionDetails>
                <TableContainer className={styles.TableContent}>
                  <Table>
                    <TableBody>
                      {innerPermissions.map((innerPermission) => (
                        <TableRow key={innerPermission.id}>
                          <TableCell>
                            <Typography
                              className={styles.Pointer}
                              variant="body2"
                              color="text.primary"
                              fontWeight={700}
                              onClick={() =>
                                setUpdatePermissionMetadataDialog({
                                  id: innerPermission.id,
                                  displayName: innerPermission.displayName,
                                  description: innerPermission.description,
                                  name: innerPermission.name,
                                  moduleId: permission.id,
                                })
                              }
                            >
                              {innerPermission.displayName}
                            </Typography>
                          </TableCell>
                          <TableCell>
                            <Typography variant="body2" color="text.primary" fontWeight={400}>
                              {innerPermission.description}
                            </Typography>
                          </TableCell>
                          <TableCell>
                            <Typography variant="body2" color="text.primary" fontWeight={400}>
                              {innerPermission.name}
                            </Typography>
                          </TableCell>
                          <TableCell>
                            <Checkbox
                              size={size}
                              checked={!!permissions[innerPermission.name]}
                              onChange={() => handleSetPermission(innerPermission.name)}
                            />
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </TableContainer>
              </AccordionDetails>
            </Accordion>
          </FormRow>
        );
      })}

      {updateRoleModuleMetadataDialog && (
        <UpdateRoleModuleDialog
          data={updateRoleModuleMetadataDialog}
          onClose={() => setUpdateRoleModuleMetadataDialog(null)}
          onApply={handleUpdateRoleMetadataModule}
        />
      )}

      {updatePermissionMetadataDialog && (
        <UpdatePermissionDialog
          data={updatePermissionMetadataDialog}
          onClose={() => setUpdatePermissionMetadataDialog(null)}
          onApply={handleUpdatePermissionMetadata}
        />
      )}
    </>
  );
}

export default PermissionsTab;
