import * as React from 'react';
import { Confirmation, ContainerDeprecated, Container, MainButton, Box } from '@nova-hf/ui';
import { withRouter, NextRouter } from 'next/router';
import { uniq, capitalize } from 'lodash';
import { startOfMonth, endOfMonth } from 'date-fns';
import { inject } from 'mobx-react';

import { formatPrice, formatDate, getMonths, getMonth, profileColor } from 'utils/helpers';
import { WithTranslation, withTranslation } from 'utils/i18n';
import { replaceQuery } from 'utils/routing';

import { DropDown } from 'containers/dropdown/Dropdown';
import ReportQuery from 'graphql/queries/report';
import DateSVG from 'assets/svg/date.svg';

import { ReportList } from './components/report-list/ReportList';
import { ReportHTML } from './components/report-list/ReportHTML';
import { IRateplan } from 'typings';
import Authentication from 'store/authentication';

interface IReportProps extends WithTranslation {
  router: NextRouter;
  color?: string;
  subscriptionId: string;
  date?: string;
  authentication: Authentication;
}

class Report extends React.Component<IReportProps> {
  onSelectMonth = (dateTime: string) => {
    const { router } = this.props;

    replaceQuery({ router, params: { date: dateTime } });
  };

  get dateTime() {
    return this.props.date ? new Date(this.props.date) : new Date();
  }

  get months() {
    const { t } = this.props;
    const currDate = this.dateTime || new Date();
    const dateNow = new Date();

    return uniq(
      getMonths(new Date(), 5)
        .reverse()
        .map(({ month, date }: { month: string; date: Date }) => ({
          name:
            dateNow.getMonth() === date.getMonth()
              ? `${t('report.current')} (${capitalize(month)})`
              : capitalize(month),
          value: startOfMonth(date).toISOString(),
          selected: currDate.getMonth() === date.getMonth(),
        })),
    );
  }

  renderDatePicker = (color?: string) => (
    <DropDown
      array={this.months}
      dropDirection="down"
      color={color}
      size="large"
      icon={<DateSVG />}
      onSelect={this.onSelectMonth}
    />
  );

  render() {
    const { subscriptionId, t, color, authentication } = this.props;
    const dateFrom = startOfMonth(this.dateTime).toISOString();
    const dateTo = endOfMonth(this.dateTime).toISOString();

    return (
      <ReportQuery variables={{ subscriptionId, input: { dateFrom, dateTo } }}>
        {({ data, loading, error }) => {
          if (loading) {
            return (
              <ContainerDeprecated underBar>
                <Confirmation title={t('report.loadingHeading')} icon={<DateSVG />} />
              </ContainerDeprecated>
            );
          }

          if (error || !data || !data.me) {
            return (
              <ContainerDeprecated underBar>
                {authentication.isStaff ? (
                  <>
                    <Confirmation
                      title={t('report.staffAlertHeading')}
                      description={t('report.staffAlertBody')}
                      icon={<DateSVG />}
                    >
                      <Box width={30}>
                        <MainButton
                          renderAs="a"
                          colorScheme={'pink'}
                          text="Áfram"
                          icon="arrowRight"
                          href={`https://innri.nova.is/stollinnweb?msisdn=${subscriptionId}`}
                          target="_blank"
                        />
                      </Box>
                    </Confirmation>
                  </>
                ) : (
                  <Confirmation
                    title={t('report.errorHeading')}
                    description={t('report.errorDescription')}
                    icon={<DateSVG />}
                  />
                )}
              </ContainerDeprecated>
            );
          }

          const {
            me: { profiles },
          } = data;

          const { report, rateplan } = profiles[0];
          const rateplanColor = profileColor(rateplan as IRateplan) || color;

          if (!report) {
            return (
              <ContainerDeprecated underBar>
                <Confirmation
                  title={t('report.notFoundHeading')}
                  description={t('report.notFoundDescription', {
                    subscriptionId,
                    month: getMonth(this.dateTime),
                  })}
                  icon={<DateSVG />}
                />
              </ContainerDeprecated>
            );
          }

          const { htmlString } = report;

          if (rateplan.typeId === 'fiber') {
            return (
              <Container>
                <ReportList
                  title={`${t('report.reportFor')} ${formatDate(this.dateTime, 'MMMM yyyy')}`}
                  label={t('report.total')}
                  amount={formatPrice(123213, { showZero: true })}
                  DatePicker={this.renderDatePicker(rateplanColor)}
                >
                  <ReportHTML html={htmlString} color={rateplanColor} />
                </ReportList>
              </Container>
            );
          }

          return (
            <ContainerDeprecated underBar>
              <ReportList
                title={`${t('report.reportFor')} ${formatDate(this.dateTime, 'MMMM yyyy')}`}
                label={t('report.total')}
                amount={formatPrice(123213, { showZero: true })}
                DatePicker={this.renderDatePicker(rateplanColor)}
              >
                <ReportHTML html={htmlString} color={rateplanColor} />
              </ReportList>
            </ContainerDeprecated>
          );
        }}
      </ReportQuery>
    );
  }
}

export default withTranslation('subscription')(withRouter(inject('authentication')(Report)));
