import { Box, makeStyles, Theme, useTheme } from '@material-ui/core';
import { FC } from 'react';
import { TemplateRegistry } from 'mystique/registry/TemplateRegistry';
import { FieldRegistry } from 'mystique/registry/FieldRegistry';
import {
  QuantitySelectorProps,
  QuantitySelectorValidation,
} from 'mystique/components/QuantityList';
import {
  InnerTextOptions,
  PaletteColorKey,
  QuantitySelectorComponentProps,
} from 'mystique/components/QuantitySelectorComponent';
import { useTemplateRender } from '../../hooks/useTemplateRender';

const defaultLabelOptions = (theme: Theme): InnerTextOptions => ({
  color: {
    all: theme.palette.text.primary,
    some: theme.palette.text.primary,
    none: theme.palette.text.primary,
  },
});

export const QuantitySelectorComponent: FC<QuantitySelectorComponentProps> = (
  props,
) => {
  const { data, itemValidation, innerText } = props;
  const theme = useTheme();
  const classes = useStyles(innerText?.options || defaultLabelOptions(theme));
  const templateRenderer = useTemplateRender(data);

  const id = templateRenderer(props.value?.id);
  const parentOnChange = props.onChange;
  const onChange = parentOnChange
    ? (value: number) => {
      parentOnChange({ value: value, id: id });
    }
    : () => null;

  if (itemValidation) {
    const { condition, messageOnInvalid } = itemValidation;
    if (templateRenderer(condition) !== 'true') {
      const message = templateRenderer(messageOnInvalid) ?? 'Invalid Item';
      return (
        <Box data-testid="QuantitySelectorComponent_invalidError">
          {message}
        </Box>
      );
    }
  }

  const _value = props.value?.value;
  const value =
    typeof _value === 'string'
      ? Number(TemplateRegistry.render(_value, data))
      : _value;

  const _defaultValue = props.defaultValue?.value;
  const defaultValue =
    typeof _defaultValue === 'string'
      ? Number(TemplateRegistry.render(_defaultValue, data))
      : _defaultValue;

  let validation: QuantitySelectorValidation | undefined;
  if (props.validation) {
    const _validation = props.validation;
    validation = {
      min:
        typeof _validation.min === 'string'
          ? Number(TemplateRegistry.render(_validation.min, data))
          : _validation.min,
      max:
        typeof _validation.max === 'string'
          ? Number(TemplateRegistry.render(_validation.max, data))
          : _validation.max,
      id: TemplateRegistry.render(_validation.id, data),
    } as QuantitySelectorValidation;
  }
  const onBlur = props.onBlur ? props.onBlur : () => null;
  const actualProps: QuantitySelectorProps = {
    ...props,
    value: value,
    defaultValue: defaultValue,
    validation: validation,
    onChange: onChange,
    onBlur: onBlur,
    data: data,
  };

  const QuantitySelector = FieldRegistry.get(
    'int',
  ) as FC<QuantitySelectorProps>;

  return (
    <Box className={classes.container}>
      <QuantitySelector {...actualProps}></QuantitySelector>
    </Box>
  );
};

const isMystiqueColor = (color: any): color is PaletteColorKey => {
  return [
    'primary',
    'secondary',
    'error',
    'warning',
    'info',
    'success',
  ].includes(color);
};

const getColor = (theme: Theme, color: string | PaletteColorKey): string => {
  return isMystiqueColor(color) ? theme.palette[color].main : color;
};

const useStyles = makeStyles((theme) => {
  return {
    container: {
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
    },
    pickerLabel: (props: InnerTextOptions) => ({
      textAlign: 'center',
      fontSize: '0.9em',
      paddingTop: '1px',
      fontWeight: 'bold',
      color: getColor(theme, props.color.all),
      '&.some': {
        color: getColor(theme, props.color.some),
      },
      '&.none': {
        color: getColor(theme, props.color.none),
      },
    }),
  };
});
