import { useEffect, useState } from 'react';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import dayjs, { Dayjs } from 'dayjs';

import handleEvent from '@pega/react-sdk-components/lib/components/helpers/event-utils';
import { format } from '@pega/react-sdk-components/lib/components/helpers/formatters';
import { dateFormatInfoDefault, getDateFormatInfo } from '@pega/react-sdk-components/lib/components/helpers/date-format-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';

// Will return the date string in YYYY-MM-DD format which we'll be POSTing to the server
function getFormattedDate(date) {
  return `${date.$y.toString()}-${(date.$M + 1).toString().padStart(2, '0')}-${date.$D.toString().padStart(2, '0')}`;
}

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 TextInput = getComponentFromMap('TextInput');
  const FieldValueList = getComponentFromMap('FieldValueList');

  const { getPConnect, label, required, disabled, value, validatemessage, readOnly, testId, helperText, displayMode, hideLabel, showFieldMessage, messageConfig = {} } = props;

  const [dateValue, setDateValue] = useState<Dayjs | null>(value ? dayjs(value) : null);

  const pConn = getPConnect();
  const actions = pConn.getActionsApi();
  const propName = (pConn.getStateProps() as any).value;
  const eligibleForFieldWarning = showFieldMessage && messageConfig.visibility && !readOnly;
  const helperTextToDisplay = validatemessage || (eligibleForFieldWarning ? messageConfig.content : helperText);

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

  // Start with default dateFormatInfo
  const dateFormatInfo = dateFormatInfoDefault;
  // and then update, as needed, based on locale, etc.
  const theDateFormat = getDateFormatInfo();
  dateFormatInfo.dateFormatString = theDateFormat.dateFormatString;
  dateFormatInfo.dateFormatStringLC = theDateFormat.dateFormatStringLC;
  dateFormatInfo.dateFormatMask = theDateFormat.dateFormatMask;

  useEffect(() => {
    setDateValue(dayjs(value));
  }, [value]);

  if (displayMode === 'DISPLAY_ONLY') {
    const formattedDate = format(props.value, 'date', {
      format: dateFormatInfo.dateFormatString
    });
    return <FieldValueList name={hideLabel ? '' : label} value={formattedDate} variant={props.variant} />;
  }

  if (displayMode === 'STACKED_LARGE_VAL') {
    const formattedDate = format(props.value, 'date', {
      format: dateFormatInfo.dateFormatString
    });
    return <FieldValueList name={hideLabel ? '' : label} value={formattedDate} variant='stacked' />;
  }

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

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

  const handleChange = date => {
    if (date && date.isValid()) {
      setDateValue(date);
      handleEvent(actions, 'changeNblur', propName, getFormattedDate(date));
    }
  };

  return (
    <Styled{{COMPONENT_CLASS_NAME}}Wrapper>
        <DatePicker
          label={label}
          disabled={disabled}
          format={dateFormatInfo.dateFormatString}
          value={dateValue}
{{! pick new delimiters for mustache }}
{{=<% %>=}}
          slotProps={{
            textField: {
              required,
              variant: 'outlined',
              placeholder: dateFormatInfo.dateFormatStringLC,
              error: status === 'error',
              helperText: helperTextToDisplay,
              size: 'small',
              InputProps: { ...testProps },
              sx: getFieldSx(status)
            }
          }}
<%={{ }}=%>     {{! revert delimiters for mustache }}
          onChange={handleChange}
        />
    </Styled{{COMPONENT_CLASS_NAME}}Wrapper>
  );
}
