
import React, { useCallback, useState, useMemo } from 'react';
import { Box, Button } from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import { useDispatch, useSelector } from 'react-redux';
import { makeStyles } from 'tss-react/mui';

import { CmdbItem, deleteItem, getItems, getPolicyConfigurationsIds } from '../store/cmdbSlice/thunks';
import { selectIdentifier, selectPagination } from '../store/cmdbSlice/selectors';
import { CMDB_ITEM_TYPES } from '../store/itemTypes';
import ClassView from './types/class/View';
import VariableView from './types/variable/View';
import InventoryView from './types/inventory/View';
import PolicyView from './types/policy/View';
import ModuleInputView from './types/moduleInput/View';
import ConfirmationDialog from '../../common/ConfirmationDialog';
import { selectPermissions } from '../../../store/usersSlice/selectors';
import { getItemTypeName, isDeleteAllowed, resolveItemType } from '../utils';

interface CmdbItemViewProps {
  item: CmdbItem;
  onValueClick?: () => void;
}

type ViewComponentType = keyof typeof VIEW_COMPONENTS;

interface ViewComponentProps {
  item: CmdbItem;
  onValueClick: () => void;
  classes: Record<string, string>;
}

const VIEW_COMPONENTS = {
  [CMDB_ITEM_TYPES.CLASS]: ClassView,
  [CMDB_ITEM_TYPES.VARIABLE]: VariableView,
  [CMDB_ITEM_TYPES.INVENTORY]: InventoryView,
  [CMDB_ITEM_TYPES.POLICY_CONFIGURATION]: PolicyView,
  [CMDB_ITEM_TYPES.MODULE_INPUT]: ModuleInputView,
};

const useStyles = makeStyles()((theme) => ({
  viewRoot: {
    display: 'flex',
    justifyContent: 'space-between',
  },
  deleteBtn: {
    maxHeight: 32,
    minWidth: 90,
    color: theme.palette.text.primary,
    borderColor: theme.palette.border.main,
    fontWeight: 500
  },
  container: {
    display: 'flex',
    alignItems: 'baseline',
    marginBottom: 6
  },
  key: {
    color: "#757575",
    fontWeight: 500,
    minWidth: 140,
    paddingTop: 6
  },
  value: {
    fontWeight: 500,
    padding: "6px 12px",
    borderRadius: 4,
    border: `1px solid transparent`,
    ':hover': {
      borderColor: theme.palette.primary.border
    }
  },
  nameValue: {
    fontStyle: 'italic',
    color: theme.palette.gray[500],
    ':hover': {
      borderColor: 'transparent'
    }
  },
  readOnlyValue: {
    fontWeight: 500,
    padding: '6px 12px',
    borderRadius: 4,
    border: `1px solid transparent`
  }
}));

const CmdbItemView: React.FC<CmdbItemViewProps> = ({ item, onValueClick = () => {} }) => {
  const [deleteDialogOpen, setDeleteDialogOpen] = useState<boolean>(false);
  const dispatch = useDispatch();
  const identifier = useSelector(selectIdentifier);
  const pagination = useSelector(selectPagination);
  const permissions = useSelector(selectPermissions);
  const { classes } = useStyles();

  const ViewComponent = useMemo(() => {
    const Component = VIEW_COMPONENTS[resolveItemType(item) as ViewComponentType];
    return Component || null;
  }, [item]);

  const onDelete = useCallback(async () => {
    await dispatch(deleteItem({ id: item.id }));
    dispatch(getItems({ identifier, page: pagination.page || 1 }));
    dispatch(getPolicyConfigurationsIds({ identifier }));
    setDeleteDialogOpen(false);
  }, [item.id, identifier, pagination.page, dispatch]);


  const handleDeleteClick = () => setDeleteDialogOpen(true);
  const handleDeleteDialogClose = () => setDeleteDialogOpen(false);

  if (!item) {
    return null;
  }


  // Render view component or fallback
  const renderViewContent = () => {
    if (!ViewComponent) {
      return <></>;
    }

    return (
      <ViewComponent 
        item={item} 
        onValueClick={onValueClick} 
        classes={classes} 
      />
    );
  };

  const itemTypeName = getItemTypeName(item);
  const confirmationMessage = `Are you sure you want to delete the "${item.name}" ${itemTypeName.toLowerCase()}?`;

  return (
    <>
      <Box className={classes.viewRoot}>
        <Box>
          {renderViewContent()}
        </Box>
        { isDeleteAllowed(permissions) && <Button 
          className={classes.deleteBtn} 
          onClick={handleDeleteClick} 
          variant="outlined" 
          size="small"
        >
          <DeleteIcon /> Delete
        </Button>}
      </Box>
      <ConfirmationDialog
        confirmColor="error"
        open={deleteDialogOpen}
        onClose={handleDeleteDialogClose}
        onConfirm={onDelete}
        title="Delete host data"
        message={confirmationMessage}
        confirmText="Delete"
        cancelText="Cancel"
        size="xs"
      />
    </>
  );
};

export default React.memo(CmdbItemView);
