import * as React from 'react';
import { observer, inject } from 'mobx-react';
import { withTranslation, WithTranslation } from 'utils/i18n';
import { ContainerDeprecated, StepTitle, PackageOptionWrapper, PackageOption } from '@nova-hf/ui';
import { groupBy } from 'lodash';

import SlotsQuery from 'graphql/queries/slots';
import { formatDate, capitalize } from 'utils/helpers';
import { ISlot } from 'typings';

interface IGetSlotsProps extends WithTranslation {
  change?: any;
  color: string;
  onNext(): void;
  subscriptionId: string;
}

class GetSlots extends React.Component<IGetSlotsProps> {
  getDaySlots = (slots: ISlot[]) => {
    const groupedSlots = groupBy(slots, (slot) => slot.startTime.substring(0, 10));

    return Object.keys(groupedSlots).map((slot: string) => ({
      id: slot,
      title: formatDate(new Date(slot), 'd. MMM'),
      subtitle: capitalize(formatDate(new Date(slot), 'eeee')),
    }));
  };

  onSelectDay = (visitDay: { id: string; title: string; subtitle: string }) => {
    const { change, onNext } = this.props;

    change.workDate = visitDay.id;
    onNext();
  };

  render() {
    const {
      color,
      change: { workDate },
      t,
      subscriptionId,
    } = this.props;

    return (
      <SlotsQuery variables={{ subscriptionId }}>
        {(props) => {
          const { loading, error, data } = props;

          if (error) {
            return null;
          }

          if (loading) {
            return <div>Sæki upplýsingar...</div>;
          }

          if (!data || !data.me) {
            return null;
          }

          const {
            me: { profiles },
          } = data;
          const { visitSlots } = profiles[0];

          return (
            <ContainerDeprecated>
              <StepTitle
                title={t('steps.getSlots.title')}
                subtitle={t('steps.getSlots.subtitle')}
                color={color}
              />
              <PackageOptionWrapper>
                {this.getDaySlots(visitSlots as ISlot[]).map((day) => (
                  <PackageOption
                    color={color}
                    key={day.id}
                    title={day.title}
                    subtitle={day.subtitle}
                    selected={workDate === day.id}
                    onSelect={() => this.onSelectDay(day)}
                    smallTitle
                  />
                ))}
              </PackageOptionWrapper>
            </ContainerDeprecated>
          );
        }}
      </SlotsQuery>
    );
  }
}
export default withTranslation('change')(inject('change')(observer(GetSlots)));
