import { TimePicker } from '@mui/x-date-pickers/TimePicker';
// import AccessTimeIcon from '@mui/icons-material/AccessTime';
import dayjs from 'dayjs';

import handleEvent from '@pega/react-sdk-components/lib/components/helpers/event-utils';
import { getComponentFromMap } from '@pega/react-sdk-components/lib/bridge/helpers/sdk_component_map';
import { PConnFieldProps } from '@pega/react-sdk-components/lib/types/PConnProps';
import useStatus from '@pega/react-sdk-components/lib/hooks/useStatus';
import { getFieldSx } from '@pega/react-sdk-components/lib/components/helpers/field-utils';

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

interface {{COMPONENT_CLASS_NAME}}Props extends PConnFieldProps {
  // If any, enter additional props that only exist on this componentName
  showFieldMessage?: boolean;
  messageConfig?: {
    content?: string;
    visibility?: boolean;
  };
  variant?: string;
}

// Duplicated runtime code from React SDK

// 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) {
  // Get emitted components from map (so we can get any override that may exist)
  const FieldValueList = getComponentFromMap('FieldValueList');
  const TextInput = getComponentFromMap('TextInput');

  const { getPConnect, label, required, disabled, value = '', validatemessage, readOnly, helperText, displayMode, hideLabel, testId, showFieldMessage, messageConfig = {} } = props;
  const eligibleForFieldWarning = showFieldMessage && messageConfig.visibility && !readOnly;
  const helperTextToDisplay = validatemessage || (eligibleForFieldWarning ? messageConfig.content : helperText);
  const pConn = getPConnect();
  const actions = pConn.getActionsApi();
  const propName = (pConn.getStateProps() as any).value;

  const status = useStatus({
    showFieldMessage,
    messageVisibility: messageConfig.visibility,
    validatemessage,
    readOnly
  });

  if (displayMode === 'DISPLAY_ONLY') {
    return <FieldValueList name={hideLabel ? '' : label} value={value} variant={props.variant} />;
  }

  if (readOnly) {
    return <TextInput {...props} />;
  }

  const testProps: any = { 'data-test-id': testId };

  const handleChange = date => {
    const theValue = date && date.isValid() ? date.format('HH:mm:ss') : null;
    handleEvent(actions, 'changeNblur', propName, theValue);
  };

  let timeValue: any = null;
  if (value && Object.keys(value).length) {
    const timeArray = value.split(':').map(itm => Number(itm));
    timeValue = dayjs().hour(timeArray[0]).minute(timeArray[1]);
  }

  //
  // TODO: Keyboard doesn't work in the minute field, it updates one digit then jump to am/pm field
  //       try an older version of the lib or use DateTimePicker
  //

  return (
    <Styled{{COMPONENT_CLASS_NAME}}Wrapper>
        <TimePicker
          // keyboardIcon={<AccessTimeIcon />}
          // fullWidth

          disabled={disabled}
          minutesStep={5}
          label={label}
          // autoOk
          // mask='__:__ _m'
          format='hh:mm a'
          value={timeValue}
          onChange={handleChange}
    {{! pick new delimiters for mustache }}
    {{=<% %>=}}
          slotProps={{
            textField: {
              variant: 'outlined',
              placeholder: 'hh:mm am',
              required,
              error: status === 'error',
              helperText: helperTextToDisplay,
              size: 'small',
              InputProps: { ...testProps },
              sx: getFieldSx(status)
            }
          }}
    <%={{ }}=%>     {{! revert delimiters for mustache }}
        />
    </Styled{{COMPONENT_CLASS_NAME}}Wrapper>
  );
}
