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, find } from 'lodash';

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

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

class GetTimeSlots extends React.Component<IGetTimeSlotsProps> {
  getTimeSlots = (slots: ISlot[]) => {
    const { change } = this.props;
    const groupedSlots = groupBy(slots, (slot) => slot.startTime.substring(0, 10));
    const timeSlots = groupedSlots[change.workDate];

    return timeSlots.map(({ slotId, startTime, endTime }: ISlot) => ({
      slotId,
      title: `${formatDate(new Date(startTime), 'HH:mm')} - ${formatDate(
        new Date(endTime),
        'HH:mm',
      )}`,
    }));
  };

  onSelectTime = (visitDay: { title: string; slotId: number }, slots: ISlot[]) => () => {
    const { change, onNext } = this.props;
    const { slotId } = visitDay;
    const groupedSlots = groupBy(slots, (slot) => slot.startTime.substring(0, 10));

    change.slot = find(groupedSlots[change.workDate], { slotId });
    onNext();
  };

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

    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?.profiles[0]) {
            return null;
          }

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

          return (
            <ContainerDeprecated>
              <StepTitle
                title={t('steps.getTimeSlots.title')}
                subtitle={t('steps.getTimeSlots.subtitle')}
                color={color}
              />
              <PackageOptionWrapper>
                {this.getTimeSlots(visitSlots as ISlot[]).map((time) => (
                  <PackageOption
                    color={color}
                    key={time.slotId}
                    title={time.title}
                    selected={slot?.slotId === time.slotId}
                    onSelect={this.onSelectTime(time, visitSlots as ISlot[])}
                    // smallTitle
                  />
                ))}
              </PackageOptionWrapper>
            </ContainerDeprecated>
          );
        }}
      </SlotsQuery>
    );
  }
}
export default withTranslation('change')(inject('change')(observer(GetTimeSlots)));
