import { Add, ExpandMore } from "@mui/icons-material";
import { Accordion, AccordionDetails, AccordionSummary, Box, Button, Grid2, IconButton, List, ListItem, ListSubheader, Typography } from "@mui/material";
import { Component } from "models";
import { describeMeasurement } from "pbHelpers/MeasurementDescriber";
import { pond, quack } from "protobuf-ts/pond";
import React, { useState } from "react";
import NewObjectInteraction from "./NewObjectInteraction";
import { Option } from "common/SearchSelect";

export interface Alert {
  conditions: pond.InteractionCondition[];
  sourceComponents: Component[];
}

interface Props {
  alerts: Alert[]
  permissions: pond.Permission[]
  addNew?: () => void
}

export default function Alerts(props: Props){
  const {alerts, addNew, permissions} = props
  // const [openNewAlert, setOpenNewAlert] = useState(false)

  const readableCondition = (condition: pond.InteractionCondition) => {
    let describer = describeMeasurement(condition.measurementType);
    let type = describer.label();
    let comparison =
      condition.comparison === quack.RelationalOperator.RELATIONAL_OPERATOR_EQUAL_TO
        ? "Exactly"
        : condition.comparison === quack.RelationalOperator.RELATIONAL_OPERATOR_GREATER_THAN
        ? "Above"
        : "Below";
    let value = describer.toDisplay(condition.value);
    return (
      <Box>
        <Typography>{type + " " + comparison + " " + value + describer.GetUnit()}</Typography>
      </Box>
    );
  };

  const alertAccordion = (alert: Alert) => {
    return (
      <Accordion style={{ width: "100%" }}>
        <AccordionSummary expandIcon={<ExpandMore />}>
          <Grid2 container direction="column">
            {alert.conditions.map((condition, i) => (
              <Grid2 key={i}>
                {readableCondition(condition)}
              </Grid2>
            ))}
          </Grid2>
        </AccordionSummary>
        <AccordionDetails>
          <List>
            <ListSubheader>Reporting Components</ListSubheader>
            {alert.sourceComponents.map((comp, i) => (
              <ListItem key={i}>{comp.name()}</ListItem>
            ))}
          </List>
        </AccordionDetails>
      </Accordion>
    );
  };

  return (
    <React.Fragment>
      <List style={{ margin: 5 }}>
        <ListSubheader sx={{paddingY: 1, display: "flex", justifyContent: "space-between", alignItems: "center"}}>
          <Typography>
            Alerts
          </Typography>
          {addNew &&
            <Button 
              disabled={!permissions.includes(pond.Permission.PERMISSION_WRITE)} 
              onClick={()=>{addNew()}}
              variant="contained" 
              color="primary">
                <Add /> Alert
            </Button>
          }
        </ListSubheader>
        {alerts.map((alert, i) => (
          <ListItem key={i}>{alertAccordion(alert)}</ListItem>
        ))}
      </List>
    </React.Fragment>
  );
}