import { useEffect, useState } from 'react';
import { MuiTelInput } from 'mui-tel-input';

import { getComponentFromMap } from '@pega/react-sdk-components/lib/bridge/helpers/sdk_component_map';
import { PConnFieldProps } from '@pega/react-sdk-components/lib/types/PConnProps';
import handleEvent from '@pega/react-sdk-components/lib/components/helpers/event-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
}

// 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 {
    getPConnect,
    label,
    required,
    disabled,
    value = '',
    validatemessage,
    status,
    onChange,
    readOnly,
    testId,
    helperText,
    displayMode,
    hideLabel,
    placeholder
  } = props;

  const pConn = getPConnect();
  const actions = pConn.getActionsApi();
  const propName = (pConn.getStateProps() as any).value;

  const [inputValue, setInputValue] = useState(value);
  useEffect(() => setInputValue(value), [value]);

  const helperTextToDisplay = validatemessage || helperText;

  let testProp = {};

  testProp = {
    'data-test-id': testId
  };

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

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

  if (readOnly) {
    const disableDropdown = true;
    return (
      <div>
        <Styled{{COMPONENT_CLASS_NAME}}Wrapper>
          <MuiTelInput
            fullWidth
            helperText={helperTextToDisplay}
            placeholder={placeholder ?? ''}
            size='small'
            defaultCountry='US'
            required={required}
            disabled={disabled}
            onChange={onChange}
            error={status === 'error'}
            label={label}
            value={value}
            {{! pick new delimiters for mustache }}
            {{=<% %>=}}
            slotProps={{
              input: {
                readOnly: true,
                ...testProp,
              },
            }}
            <%={{ }}=%>     {{! revert delimiters for mustache }}
            disableDropdown={disableDropdown}
          />
        </Styled{{COMPONENT_CLASS_NAME}}Wrapper>
      </div>
    );
  }

  const handleChange = inputVal => {
    setInputValue(inputVal);
  };

  const handleBlur = event => {
    const phoneValue = event?.target?.value;
    let phoneNumber = phoneValue.split(' ').slice(1).join();
    phoneNumber = phoneNumber ? `+${phoneValue && phoneValue.replace(/\D+/g, '')}` : '';
    handleEvent(actions, 'changeNblur', propName, phoneNumber);
  };

  return (
    <Styled{{COMPONENT_CLASS_NAME}}Wrapper>
      <MuiTelInput
        fullWidth
        variant='outlined'
        helperText={helperTextToDisplay}
        placeholder={placeholder ?? ''}
        size='small'
        defaultCountry='US'
        required={required}
        disabled={disabled}
        onChange={handleChange}
        onBlur={!readOnly ? handleBlur : undefined}
        error={status === 'error'}
        label={label}
        value={inputValue}
        {{! pick new delimiters for mustache }}
        {{=<% %>=}}
        slotProps={{ input: { ...testProp } }}
        <%={{ }}=%>     {{! revert delimiters for mustache }}
      />
    </Styled{{COMPONENT_CLASS_NAME}}Wrapper>
  );
}
