import React, { useState, useEffect } from 'react';
import { SText } from '../s-components/typography/s-text';
import { SBox } from '../s-components/layout/s-box';
import { SInfoTitle } from '../s-components/s-info-title';
import { SH6 } from '../s-components/typography/s-h6';
import { RangeOption } from './range-option';
import { SDateRangeTitle } from '../../market/s-components/s-date-range-title';
import { TOption, TPresetDateRange } from '../../market/types';
import { SRangeItem } from '../../market/s-components/s-range-item';
import { SRangeButtonContainer } from '../../market/s-components/s-range-button-container';
import { datepickerOptionSelected } from '../../analytics';
import { findLabelByValue } from '../../market/transducers';
import { Touchable } from './touchable';

type TProps = {
  options: TOption[];
  onRange: TPresetDateRange;
  confirmRange: () => void;
  source?: string;
  value: number;
  rangeTitle: string;
};

export const DateRange: React.FC<TProps> = props => {
  const {
    confirmRange,
    onRange,
    options,
    value: propsValue,
    source,
    rangeTitle,
  } = props;
  const [value, setValue] = useState(propsValue);
  const [pressed, setPressed] = useState(false);
  const btnColor = pressed ? 'malibu2' : 'azureRadiance';

  useEffect(() => {
    setValue(propsValue);
  }, [propsValue]);

  return (
    <SBox px={16} pb={12} pt={5}>
      <SDateRangeTitle>
        <SInfoTitle mt={4}>Filtering</SInfoTitle>
        <Touchable
          testID="date-range-confirm-button"
          // @ts-ignore
          activeOpacity={1}
          onPress={() => {
            if (value !== propsValue) {
              onRange(value);
            }
            confirmRange();

            const selectedOptionLabel = findLabelByValue(options, value);
            datepickerOptionSelected({
              datepicker_source: source!,
              datepicker_value: selectedOptionLabel,
            });
          }}
          onPressIn={() => {
            setPressed(true);
          }}
          onPressOut={() => {
            setPressed(false);
          }}
        >
          <SRangeButtonContainer>
            <SText semibold color={btnColor}>
              Done
            </SText>
          </SRangeButtonContainer>
        </Touchable>
      </SDateRangeTitle>
      <SRangeItem>
        <SBox py={8}>
          <SH6 color="romanPurple">{rangeTitle}</SH6>
        </SBox>
      </SRangeItem>
      {options.map(({ value: optionValue, label }) => (
        <RangeOption
          key={optionValue}
          label={label}
          selected={optionValue === value}
          onRangePress={() => {
            setValue(optionValue);
          }}
        />
      ))}
    </SBox>
  );
};

DateRange.defaultProps = {
  source: undefined,
};
