import React, { useState } from 'react';
import TextField from '@mui/material/TextField';
import Popover from '@mui/material/Popover';
import Grid2 from '@mui/material/Grid2';
import Typography from '@mui/material/Typography';
import makeStyles from '@mui/styles/makeStyles';
import { Theme as MuiTheme } from "@mui/material/styles";

import Utils from '@pega/react-sdk-components/lib/components/helpers/utils';

import Styled{{COMPONENT_CLASS_NAME}}Wrapper from './styles';

import { PConnProps } from '@pega/react-sdk-components/lib/types/PConnProps';

declare module "@mui/private-theming" {
  interface DefaultTheme extends MuiTheme {
    spacing: (spacing: number) => string;
  }
}

interface {{COMPONENT_CLASS_NAME}}Props extends PConnProps {
  // If any, enter additional props that only exist on this component
  label: string;
  createDateTime: string;
  createLabel: string;
  createOperator: { userName: string; userId: string };
  updateDateTime: string;
  updateLabel: string;
  updateOperator: { userName: string; userId: string };
  displayLabel?: any;
}

const useStyles = makeStyles(myTheme => ({
  root: {
    padding: myTheme.spacing(1),
    margin: myTheme.spacing(1)
  },
  popover: {
    padding: myTheme.spacing(1),
    margin: myTheme.spacing(1)
  }
}));

// Duplicated runtime code from React SDK

// Page Case Widget example

// props passed in combination of props from property panel (config.json) and run time props from Constellation
export default function {{COMPONENT_CLASS_NAME}}(props: {{COMPONENT_CLASS_NAME}}Props) {
  // const componentName = "Operator";
  const classes = useStyles();

  const fieldLabel = props?.label?.toLowerCase();
  const displayLabel = props?.displayLabel?.toLowerCase();
  let caseOpLabel = '---';
  let caseOpName = '---';
  let caseOpId = '';
  let caseTime = '';

  if (fieldLabel === 'create operator' || displayLabel === 'create operator') {
    caseOpLabel = props.createLabel;
    caseOpName = props.createOperator.userName;
    caseTime = props.createDateTime;
    caseOpId = props.createOperator.userId;
  } else if (fieldLabel === 'update operator' || displayLabel === 'update operator') {
    caseOpLabel = props.updateLabel;
    caseOpName = props.updateOperator.userName;
    caseTime = props.updateDateTime;
    caseOpId = props.updateOperator.userId;
  }

  // Popover-related
  const [popoverAnchorEl, setPopoverAnchorEl] = useState(null);
  const [popoverFields, setPopoverFields] = useState<any[]>([]);

  const popoverOpen = Boolean(popoverAnchorEl);
  const popoverId = popoverOpen ? 'operator-details-popover' : undefined;

  const handlePopoverClose = () => {
    setPopoverAnchorEl(null);
  };

  function showOperatorDetails(event) {
    const operatorPreviewPromise = PCore.getUserApi().getOperatorDetails(caseOpId);
    const localizedVal = PCore.getLocaleUtils().getLocaleValue;
    const localeCategory = 'Operator';

    operatorPreviewPromise.then((res: any) => {
      const fillerString = '---';
      let fields: any = [];
      if (res.data && res.data.pyOperatorInfo && res.data.pyOperatorInfo.pyUserName) {
        fields = [
          {
            id: 'pyPosition',
            name: localizedVal('Position', localeCategory),
            value: res.data.pyOperatorInfo.pyPosition ? res.data.pyOperatorInfo.pyPosition : fillerString
          },
          {
            id: 'pyOrganization',
            name: localizedVal('Organization', localeCategory),
            value: res.data.pyOperatorInfo.pyOrganization ? res.data.pyOperatorInfo.pyOrganization : fillerString
          },
          {
            id: 'ReportToUserName',
            name: localizedVal('Reports to', localeCategory),
            value: res.data.pyOperatorInfo.pyReportToUserName ? res.data.pyOperatorInfo.pyReportToUserName : fillerString
          },
          {
            id: 'pyTelephone',
            name: localizedVal('Telephone', localeCategory),
            value: res.data.pyOperatorInfo.pyTelephone ? (
              <a href={`tel:${res.data.pyOperatorInfo.pyTelephone}`}>{res.data.pyOperatorInfo.pyTelephone}</a>
            ) : (
              fillerString
            )
          },
          {
            id: 'pyEmailAddress',
            name: localizedVal('Email address', localeCategory),
            value: res.data.pyOperatorInfo.pyEmailAddress ? (
              <a href={`mailto:${res.data.pyOperatorInfo.pyEmailAddress}`}>{res.data.pyOperatorInfo.pyEmailAddress}</a>
            ) : (
              fillerString
            )
          }
        ];
      } else {
        console.log(
          `Operator: PCore.getUserApi().getOperatorDetails(${caseOpId}); returned empty res.data.pyOperatorInfo.pyUserName - adding default`
        );
        fields = [
          {
            id: 'pyPosition',
            name: localizedVal('Position', localeCategory),
            value: fillerString
          },
          {
            id: 'pyOrganization',
            name: localizedVal('Organization', localeCategory),
            value: fillerString
          },
          {
            id: 'ReportToUserName',
            name: localizedVal('Reports to', localeCategory),
            value: fillerString
          },
          {
            id: 'pyTelephone',
            name: localizedVal('Telephone', localeCategory),
            value: fillerString
          },
          {
            id: 'pyEmailAddress',
            name: localizedVal('Email address', localeCategory),
            value: fillerString
          }
        ];
      }
      // Whatever the fields are, update the component's popoverFields
      setPopoverFields(fields);
    });

    setPopoverAnchorEl(event.currentTarget);
  }

  function getPopoverGrid() {
    // return popoverFields.map((field) => {
    //   return <div className={classes.popover}>{field.name}: {field.value}</div>
    // })

    if (popoverFields.length === 0) {
      return;
    }

    // There are fields, so build the grid.
    return (
      <Grid2 container className={classes.popover} spacing={1}>
        {{! pick new delimiters for mustache }}
        {{=<% %>=}}
        <Grid2 size={{ xs: 12 }}>
          <Typography variant='h6'>{caseOpName}</Typography>
        </Grid2>
        {popoverFields.map(field => {
          return (
            <React.Fragment key={field.id}>
              <Grid2 container size={{ xs: 12 }} spacing={1}>
                <Grid2 size={{ xs: 12 }}>
                  <Typography variant='caption'>{field.name}</Typography>
                </Grid2>
                <Grid2 size={{ xs: 6 }}>
                  <Typography variant='subtitle2'>{field.value}</Typography>
                </Grid2>
              </Grid2>
            </React.Fragment>
          );
        })}
        <%={{ }}=%>     {{! revert delimiters for mustache }}
      </Grid2>
    );
  }

  // End of popover-related

  return (
    <Styled{{COMPONENT_CLASS_NAME}}Wrapper>
      <>
        {{! pick new delimiters for mustache }}
        {{=<% %>=}}
        <TextField
          defaultValue={caseOpName}
          label={caseOpLabel}
          onClick={showOperatorDetails}
          InputProps={{
            readOnly: true,
            disableUnderline: true,
            inputProps: { style: { cursor: 'pointer' } }
          }}
        />
        <br />
        {Utils.generateDateTime(caseTime, 'DateTime-Since')}
        <%={{ }}=%>     {{! revert delimiters for mustache }}
        <Popover
          id={popoverId}
          open={popoverOpen}
          anchorEl={popoverAnchorEl}
          onClose={handlePopoverClose}
          {{! pick new delimiters for mustache }}
          {{=<% %>=}}
          anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
          transformOrigin={{ vertical: 'top', horizontal: 'center' }}
          PaperProps={{ style: { maxWidth: '45ch' } }}
          <%={{ }}=%>     {{! revert delimiters for mustache }}
        >
          {getPopoverGrid()}
        </Popover>
      </>
    </Styled{{COMPONENT_CLASS_NAME}}Wrapper>
  );
}
