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 Utils from '@pega/react-sdk-components/lib/components/helpers/utils';

import StyledPegaDxilMyPageCaseWidgetWrapper from './styles';

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

interface PegaDxilMyPageCaseWidgetProps 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;
  displayMode?: string;
}

const useStyles = makeStyles(myTheme => ({
  root: {
    padding: myTheme.spacing(1),
    margin: myTheme.spacing(1)
  },
  popover: {
    padding: myTheme.spacing(1),
    margin: myTheme.spacing(1)
  },
  fieldLabel: {
    fontWeight: 400,
    color: myTheme.palette.text.secondary
  },
  fieldValue: {
    color: myTheme.palette.text.primary
  }
}));

// 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 PegaDxilMyPageCaseWidget(props: PegaDxilMyPageCaseWidgetProps) {
  // 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);
      })
      .catch(e => {
        console.error(e);
      });

    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}>
        <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: 6 }}>
                  <Typography variant='caption'>{field.name}</Typography>
                </Grid2>
                <Grid2 size={{ xs: 6 }}>
                  <Typography variant='subtitle2'>{field.value}</Typography>
                </Grid2>
              </Grid2>
            </React.Fragment>
          );
        })}
      </Grid2>
    );
  }

  // End of popover-related

  const { displayMode } = props;

  if (displayMode === 'DISPLAY_ONLY') {
    return (
      <StyledPegaDxilMyPageCaseWidgetWrapper>
        <>
          <Grid2 container spacing={4} justifyContent='space-between'>
            <Grid2 size={{ xs: 4 }}>
              <Typography variant='body2' component='span' className={classes.fieldLabel}>
                {caseOpLabel}
              </Typography>
            </Grid2>
            <Grid2 size={{ xs: 8 }}>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem', alignItems: 'baseline' }}>
                <Typography variant='body2' component='span' className={classes.fieldValue} onClick={showOperatorDetails} sx={{ cursor: 'pointer' }}>
                  {caseOpName}
                </Typography>
                <Typography variant='caption' component='span' sx={{ color: 'text.secondary' }}>
                  {Utils.generateDateTime(caseTime, 'DateTime-Since')}
                </Typography>
              </div>
            </Grid2>
          </Grid2>
          <Popover
            id={popoverId}
            open={popoverOpen}
            anchorEl={popoverAnchorEl}
            onClose={handlePopoverClose}
            anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
            transformOrigin={{ vertical: 'top', horizontal: 'center' }}
            slotProps={{
              paper: { style: { maxWidth: '45ch' } }
            }}
          >
            {getPopoverGrid()}
          </Popover>
        </>
      </StyledPegaDxilMyPageCaseWidgetWrapper>
    );
  }

  return (
    <StyledPegaDxilMyPageCaseWidgetWrapper>
      <>
        <TextField
          variant='standard'
          defaultValue={caseOpName}
          label={caseOpLabel}
          onClick={showOperatorDetails}
          slotProps={{
            input: {
              readOnly: true,
              disableUnderline: true,
              inputProps: { style: { cursor: 'pointer' } }
            }
          }}
        />
        <br />
        {Utils.generateDateTime(caseTime, 'DateTime-Since')}
        <Popover
          id={popoverId}
          open={popoverOpen}
          anchorEl={popoverAnchorEl}
          onClose={handlePopoverClose}
          anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
          transformOrigin={{ vertical: 'top', horizontal: 'center' }}
          slotProps={{
            paper: { style: { maxWidth: '45ch' } }
          }}
        >
          {getPopoverGrid()}
        </Popover>
      </>
    </StyledPegaDxilMyPageCaseWidgetWrapper>
  );
}
