import { Alert, Box, Typography } from '@mui/material';

import { useGroupsConfig } from '../GroupsConfigContext';
import type { GroupType } from '../types';

interface GroupDataTabProps {
  groupId: string;
  type: GroupType;
}

// Shared groups render the CMDB mount node (`#cmdb-root`): cmdb.bundle.js is already
// loaded, spots the node via its MutationObserver and mounts itself with the JSON in
// `data-props` as its props. Personal groups show guidance instead.
export const GroupDataTab = ({ groupId, type }: GroupDataTabProps) => {
  const { canCreateShared, canViewData, isSuperHub } = useGroupsConfig();
  const shared = type === 'shared';

  if (!shared) {
    return (
      <Box sx={{ mt: 2 }}>
        <Typography gutterBottom>
          Group data can be used to make changes to the hosts in the group. This functionality is only available in shared groups and to users with the
          appropriate access rights.
        </Typography>
        {canCreateShared ? (
          <Typography color="text.secondary">
            Click the toggle button for &ldquo;Shared group&rdquo; in the top right to make this a shared group and enable data.
          </Typography>
        ) : (
          <Alert severity="info" sx={{ mt: 1 }}>
            You don&rsquo;t have access to create shared groups, ask an administrator for assistance.
          </Alert>
        )}
        {!canViewData && (
          <Alert severity="info" sx={{ mt: 1 }}>
            You don&rsquo;t have access to view the group data, ask an administrator for assistance.
          </Alert>
        )}
      </Box>
    );
  }

  // Data tab is not available on super-hub setups.
  if (isSuperHub) return null;

  return (
    <Box sx={{ mt: 2 }}>
      <div
        id="cmdb-root"
        data-props={JSON.stringify({
          displayShowJson: false,
          identifier: Number(groupId),
          cmdbServiceUrl: '/groups_app/SharedGroupsCmdb'
        })}
      />
    </Box>
  );
};
