import React from 'react';
import { useTranslation } from 'react-i18next';
import { Box, LoadingPlaceholder, ThemeColorType, UsageCard, UsageCardSimple } from '@nova-hf/ui';
import { MainColorType } from '@nova-hf/ui/umd/ts/src/styles/vars.css';
import Authentication from 'store/authentication';
import { UsageType, useUsageItemsQuery } from 'typings/graphql';

type UsageSummaryProps = {
  subscriptionId: string;
  authentication?: Authentication;
  color: ThemeColorType;
  statusCode: string;
};
export const UsageSummary = ({
  subscriptionId,
  authentication,
  color,
  statusCode,
}: UsageSummaryProps) => {
  const { t } = useTranslation('subscriptions');
  const ssn = authentication?.accountInput.ssn ?? '';
  const fetchStatusCodes = ['active', 'b1w', 'b2w', 'porting_out'];
  const { data, error, loading } = useUsageItemsQuery({
    variables: { accountInput: { ssn }, subscriptionId },
    skip: !authentication || !fetchStatusCodes.includes(statusCode),
  });

  if (
    error ||
    !data?.me?.subscriptions?.subscriptions?.length ||
    !data.me.subscriptions.subscriptions[0] ||
    !data.me.subscriptions.subscriptions[0].usageItems
  ) {
    return null;
  }

  if (loading) {
    return (
      <Box
        width="100%"
        borderColor="grey200"
        borderStyle="solid"
        borderWidth="1px"
        dottedShadow="small"
        boxShadow="normal"
        backgroundColor="white"
        marginBottom={4}
      >
        <Box padding={4}>
          <Box marginBottom={1}>
            <LoadingPlaceholder height={2} width="1/12" />
          </Box>
          <Box marginBottom={2}>
            <LoadingPlaceholder height={5} width="3/12" />
          </Box>
          <Box paddingBottom={8}>
            <LoadingPlaceholder height={2} width="11/12" />
          </Box>
        </Box>
      </Box>
    );
  }
  const usageItems = data.me.subscriptions.subscriptions[0].usageItems;

  const dataItem = usageItems.find((item) => item.type === UsageType.Data);
  const otherItems = usageItems.filter((item) => item.type !== UsageType.Data);

  const remainingPercentage = () => {
    if (dataItem?.infinite) return 100;
    if (dataItem?.usage?.amount && dataItem.included?.amount) {
      return Math.round((1 - dataItem?.usage?.amount / dataItem.included?.amount) * 100);
    } else return 0;
  };

  const priceAmount = t('usageSummary.priceAmountLabel');

  return (
    <Box width="100%" marginBottom={8}>
      <Box marginBottom={4}>
        <UsageCard
          color={color as MainColorType}
          price={{
            amount: priceAmount,
          }}
          progressBar={{
            percentage: remainingPercentage(),
            thickness: 2,
          }}
          title={dataItem?.title ?? ''}
          usage={{
            remaning: {
              amount: dataItem?.remaining?.amount ?? '',
              description: t('usageSummary.remainingDescription'),
              unit: dataItem?.remaining?.unit ?? '',
            },
            total: {
              amount: dataItem?.included?.amount ?? '',
              description: dataItem?.included?.text ?? '',
              unit: dataItem?.included?.unit ?? '',
            },
            used: {
              amount: dataItem?.usage?.amount ?? '',
              description: t('usageSummary.usedDescription'),
              unit: dataItem?.usage?.unit ?? '',
            },
          }}
          withBorder
        />
      </Box>
      <Box display="flex" gap={3}>
        {otherItems &&
          otherItems.map((item, i) => {
            const usageDescription = () => {
              const hasRemainingData = !item.infinite && !!item.remaining;

              if (item.type === UsageType.Sms) return t('usageSummary.smsDescription');
              if (item.type === UsageType.Balance) return t('usageSummary.balanceDescription');
              else {
                return hasRemainingData
                  ? t('usageSummary.otherDescription')
                  : t('usageSummary.usedDescription');
              }
            };

            const usageAmount = () => {
              const isInfinite = !!item.infinite;
              const hasRemainingData = !!item.remaining;

              if (!isInfinite && hasRemainingData) {
                return { amount: item.remaining?.amount ?? 0, unit: item.remaining?.unit ?? '' };
              } else {
                return { amount: item.usage?.amount ?? 0, unit: item.usage?.unit ?? '' };
              }
            };
            return (
              <UsageCardSimple
                key={`__${i}__${item.title}_${item.remaining?.amount}`}
                title={item.title ?? '-'}
                color={color as MainColorType}
                description={usageDescription()}
                usage={usageAmount()}
              />
            );
          })}
      </Box>
    </Box>
  );
};
