import * as React from 'react';
import { useRouter } from 'next/router';
import { inject } from 'mobx-react';
import { EmptyMessage, Container, ContainerDeprecated } from '@nova-hf/ui';
import { useTranslation } from 'utils/i18n';
import { formatPrice, formatTel, formatDate, getMonths, profileColor } from 'utils/helpers';
import { replaceQuery } from 'utils/routing';
import { uniq, capitalize } from 'lodash';
import { startOfMonth } from 'date-fns';

import DateSVG from 'assets/svg/date.svg';

import { DropDown } from '../dropdown/Dropdown';

import { SummaryList } from './components/summary-list/SummaryList';
import { SummaryListItem } from './components/summary-list/SummaryListItem';
import { SummaryListItemLoading } from './components/summary-list/SummaryListItemLoading';
import { Rateplan, useSummaryQuery } from 'typings/graphql';
import Authentication from 'store/authentication';
import { ISummaryItem } from 'typings';

interface ISummaryProps {
  color?: string;
  subscriptionId: string;
  date: Date;
  authentication: Authentication;
}

interface IEmptyProps {
  subscription: string;
  month: string;
  color?: string;
  renderDatePicker: (color?: string) => React.ReactElement;
}

const ErrorComponent = ({ subscription, month, renderDatePicker, color }: IEmptyProps) => {
  const { t } = useTranslation('subscriptions');

  return (
    <ContainerDeprecated underBar row>
      <SummaryList
        title={`${t('summary.summaryFor')} ${month}`}
        loading
        DatePicker={renderDatePicker(color)}
      >
        <EmptyMessage
          title={t('summary.noSummary')}
          description={t('summary.nothingToPay', { subscription, month })}
        />
      </SummaryList>
    </ContainerDeprecated>
  );
};

const LoadingComponent = ({ date }: Omit<ISummaryProps, 'authentication'>) => {
  const { t } = useTranslation('subscriptions');

  return (
    <ContainerDeprecated underBar row>
      <SummaryList title={`${t('summary.summaryFor')} ${formatDate(date, 'MMMM yyyy')}`} loading>
        <SummaryListItemLoading />
        <SummaryListItemLoading />
      </SummaryList>
    </ContainerDeprecated>
  );
};

const Summary = ({ subscriptionId, date, color, authentication, ...rest }: ISummaryProps) => {
  const { t } = useTranslation('subscriptions');
  const router = useRouter();

  const onSelectMonth = (dateTime: string) => {
    replaceQuery({
      router,
      params: {
        date: dateTime,
      },
    });
  };

  const months = () => {
    const dateTime = date ? new Date(date) : new Date();
    const currDate = 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('filterBar.current')} (${capitalize(month)})`
              : capitalize(month),
          value: startOfMonth(date).toISOString(),
          selected: currDate.getMonth() === date.getMonth(),
        })),
    );
  };

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

  const { loading, error, data } = useSummaryQuery({
    variables: {
      accountInput: authentication.accountInput,
      date,
      subscriptionId,
    },
  });

  if (loading) {
    return <LoadingComponent date={date} subscriptionId={subscriptionId} {...rest} />;
  }

  const errorProps = {
    subscription: formatTel(subscriptionId),
    month: formatDate(date, 'MMMM'),
    color,
    renderDatePicker,
    ...rest,
  };

  if (error || !data || !data.me) {
    return <ErrorComponent {...errorProps} />;
  }

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

  const currentProfile = profiles?.find((p) => p.subscriptionId === subscriptionId);

  if (!currentProfile) {
    return <ErrorComponent {...errorProps} />;
  }

  const { summary, rateplan } = currentProfile;

  const rateplanColor = rateplan ? profileColor(rateplan as Rateplan) : 'ocean';

  errorProps.color = rateplanColor;

  if (!summary || !summary.usage) {
    return <ErrorComponent {...errorProps} />;
  }

  const { usage, totalSum } = summary;

  if (rateplan?.typeId === 'fiber') {
    return (
      <Container marginTop={5}>
        <SummaryList
          title={`${t('summary.summaryFor')} ${formatDate(date, 'MMMM yyyy')}`}
          label={t('summary.total')}
          amount={formatPrice(totalSum, { showZero: true })}
          DatePicker={renderDatePicker(rateplanColor)}
        >
          {usage.map((item, i) => (
            <SummaryListItem item={item as ISummaryItem} key={`${item.amount}-${i}`} />
          ))}
        </SummaryList>
      </Container>
    );
  }

  return (
    <ContainerDeprecated underBar row>
      <SummaryList
        title={`${t('summary.summaryFor')} ${formatDate(date, 'MMMM yyyy')}`}
        label={t('summary.total')}
        amount={formatPrice(totalSum, { showZero: true })}
        DatePicker={renderDatePicker(rateplanColor)}
      >
        {usage.map((item, i) => (
          <SummaryListItem item={item as ISummaryItem} key={`${item.amount}-${i}`} />
        ))}
      </SummaryList>
    </ContainerDeprecated>
  );
};

export default inject('authentication')(Summary);
