import { FC, useEffect, useState } from 'react';
import OpenInBrowserIcon from '@material-ui/icons/OpenInBrowser';
import {
  createStyles,
  Dialog,
  DialogContent,
  DialogTitle,
  IconButton,
  makeStyles,
  Table,
  TableBody,
  TableCell,
  TableRow,
  Typography,
} from '@material-ui/core';
import {
  DynamicAttribute,
  DynamicValue,
} from 'mystique/components/DynamicValue';
import _ from 'lodash';
import { useTemplateRender } from '../../hooks/useTemplateRender';

type ShowAttributesButtonProps = {
  title: string;
  data: any;
  fields?: DynamicAttribute[];
  attributes?: Attributes[];
};

type Attributes = {
  dataSource: string;
  exclude?: string[];
};

interface Attribute {
  name: string;
  type: string;
  value: unknown;
}

const ShowAttributesButton: FC<ShowAttributesButtonProps> = ({
  title,
  data,
  fields = [],
  attributes = [],
}) => {
  const [showModal, setShowModal] = useState(false);
  const classes = useStyles();
  const templateRender = useTemplateRender(data);
  const [displayFields, setDisplayFields] = useState<DynamicAttribute[]>([]);

  useEffect(() => {
    const displayFields: DynamicAttribute[] = [];
    fields.forEach((field) => {
      displayFields.push(field);
    });
    attributes.forEach((attribute) => {
      (_.get(data, attribute.dataSource) as Attribute[])?.forEach((a) => {
        if (
          !attribute.exclude ||
          (attribute.exclude.indexOf(a.name) < 0 &&
            !a.name.startsWith('INVENTORY_COVERAGE_UPDATE'))
        ) {
          displayFields.push({
            label: a.name,
            value: String(a.value),
          } as DynamicAttribute);
        }
      });
    });

    setDisplayFields(displayFields);
  }, []);

  const handleShow = () => {
    setShowModal(true);
  };

  const handleClose = () => {
    setShowModal(false);
  };

  return (
    <>
      <IconButton onClick={handleShow} disabled={!displayFields.length}>
        <OpenInBrowserIcon />
      </IconButton>
      <Dialog open={showModal} onClose={handleClose}>
        <DialogTitle>
          <Typography variant="h3" className={classes.dialogTitle}>
            {templateRender(title)}
          </Typography>
        </DialogTitle>
        <DialogContent className={classes.container}>
          <Table>
            <TableBody>
              {displayFields.map((a, i) => (
                <TableRow key={i}>
                  <TableCell className={classes.cell}>
                    <Typography className={classes.label}>
                      {templateRender(a.label)}
                    </Typography>
                  </TableCell>
                  <TableCell className={classes.cell}>
                    <DynamicValue
                      attribute={a}
                      context={data}
                      defaultValue={<span>-</span>}
                    />
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </DialogContent>
      </Dialog>
    </>
  );
};

const useStyles = makeStyles((theme) =>
  createStyles({
    container: {
      paddingBottom: '20px',
    },
    cell: {
      color: '#000000',
      padding: '5px 10px 5px 0px',
    },
    attributeRow: {
      paddingTop: theme.spacing(1),
    },
    attributeValue: {
      '& span': {
        whiteSpace: 'normal',
      },
    },
    attributeKey: {
      paddingRight: theme.spacing(0.5),
    },
    label: {
      fontSize: '12px',
      lineHeight: '16px',
      fontWeight: 400,
      color: theme.palette.text.hint,
    },
    dialogTitle: {
      color: '#000',
    },
  }),
);

export default ShowAttributesButton;
