import React from 'react';
import { useQuery } from '@apollo/client';
import { TvChannel } from '@nova-hf/ui';
import gql from 'graphql-tag';
import { inject } from 'mobx-react';
import Router from 'next/router';
import Authentication from 'store/authentication';
import {
  NovaSubscription,
  Plan_CfService as Plan,
  useProductsQuery,
  useSubscriptionsQuery,
  Variant,
} from 'typings/graphql';
import { formatDate, formatPrice, serializeObject } from 'utils/helpers';
import { useTranslation } from 'utils/i18n';

import TvChannelGrid from './components/TvChannelGrid';

interface INovaTvSubscriptionProfileProps {
  authentication: Authentication;
  subscriptionId: string;
}

const NOVATV_CHANNELS = gql`
  query planCollectionQuery {
    planCollection(where: { planGroup: { type_contains: "tv" } }) {
      items {
        id
        amount
        interval
        trial {
          title
        }
        product {
          ... on Service_cfService {
            id
            title
            description
            image {
              url
            }
          }
        }
      }
    }
  }
`;

const NovaTvSubscriptionProfile = ({
  authentication,
  subscriptionId,
}: INovaTvSubscriptionProfileProps) => {
  const { t } = useTranslation('subscription');
  const { data, loading } = useQuery(NOVATV_CHANNELS);
  const { data: subscriptionsData, loading: loadingSubscriptions } = useSubscriptionsQuery({
    variables: {
      accountInput: authentication.accountInput,
      subscriptionsInput: { perPage: null, page: null },
    },
  });
  const { data: channelData, loading: channelLoading } = useProductsQuery({
    variables: {
      input: {
        category: 'PayPerView',
      },
    },
  });
  const PPVEvents = channelData?.products?.products;

  if (loading || loadingSubscriptions || channelLoading) {
    return <div>Sæki...</div>;
  }

  if (data && subscriptionsData) {
    const subscriptions = subscriptionsData?.me?.subscriptions?.subscriptions
      ?.find((sub) => sub?.rateplan?.typeId === 'tv_content_channel')
      ?.subscriptions?.filter((s) => s.status !== 'Cancelled');

    // Move the NovaTV subscription to first place
    const sortedSubscriptions = subscriptions
      ? Object.values(subscriptions).sort((a, b) => {
          if (b.plan.product.id === 'B0017') return 1;
          if (a.plan.product.id === 'B0017') return -1;
          return 0;
        })
      : [];

    const allAvailablePlans = data?.planCollection?.items;

    // Filter out current subscriptions from all available subscriptions
    const availablePlans = ((subs, allAvailable) => {
      // Make array of current subscriptions product ids
      const currentSubscriptionProductIds = subs?.map((sub: NovaSubscription) => {
        return sub?.plan?.id;
      });

      // Filter out currentSubscriptionProductIds from allAvailablecriptions
      return allAvailable.filter(
        (item: { id: string }) => !currentSubscriptionProductIds?.includes(item?.id),
      );
    })(subscriptions, allAvailablePlans);

    const filterOutSiminnSport = availablePlans?.filter((sub: Plan) => sub?.id !== 'P0008');

    const seeMoreSub = (childSubscriptionId: string) => {
      const ssn = authentication.accountInput.ssn;
      Router.push(`/${ssn}/thjonusta/${subscriptionId}/askrift/${childSubscriptionId}`);
    };

    const watchSiminn = () => {
      window.open('https://sjonvarp.siminn.is', '_blank');
    };

    return (
      <>
        <TvChannelGrid title={t('novaTv.yourSubscriptions')}>
          {sortedSubscriptions?.map((sub) => {
            const hasBeenCancelled = sub.cancelAtPeriodEnd;
            return (
              <TvChannel
                key={sub.plan.product.id}
                title={sub.plan.product.title}
                price={sub.nextChargeAmount ? formatPrice(sub.nextChargeAmount) : ''}
                activeUntil={`${
                  hasBeenCancelled ? t('novaTv.activeUntil') : t('novaTv.nextRenewal')
                }:`}
                activeUntilDate={
                  sub?.currentPeriodEnd && formatDate(sub?.currentPeriodEnd, 'd. MMMM yyyy')
                }
                buttonText={t('novaTv.seeMore')}
                imageSrc={sub?.plan?.product?.image?.url}
                background="white"
                border
                borderColor="grey100"
                showDotShadow
                onSelect={() => seeMoreSub(sub.id)}
                {...(sub?.planId === 'P0019' && {
                  secondaryButton: {
                    onClick: () => watchSiminn(),
                    text: 'Horfa í vafra',
                    icon: 'arrowRight',
                    colorScheme: 'black100',
                  },
                })}
              />
            );
          })}
        </TvChannelGrid>

        {!!PPVEvents?.length && (
          <TvChannelGrid title={t('novaTv.ppvEvent')}>
            {PPVEvents?.map(({ name, description, variants }) => {
              if (!!variants?.length && variants[0].__typename === 'Variant') {
                const firstVariant: Variant = variants[0] as Variant;
                const { isStaff } = authentication;

                const query: string = serializeObject({
                  ssn: isStaff ? authentication.accountInput.ssn : '',
                  ppv: firstVariant?.id || '',
                });
                const price: number = firstVariant?.price;

                return (
                  <TvChannel
                    key={firstVariant?.id}
                    pill={t('novaTv.ppvEvent')}
                    title={name}
                    price={
                      firstVariant?.price
                        ? formatPrice(price, {
                            showZero: true,
                            showDecimals: false,
                            monthly: false,
                          })
                        : ''
                    }
                    buttonText={t('novaTv.buyEvent')}
                    description={description}
                    imageSrc={
                      firstVariant?.imageUrl ||
                      'https://images.ctfassets.net/j5d5y4z9f7ki/6gQqO3Qy6AKEk8yQeWmkGy/ddf7f1e15a798598b7bbf9696d638aab/NOVA_TV_2.jpg'
                    }
                    background="white"
                    border
                    borderColor="grey100"
                    showDotShadow
                    onSelect={() =>
                      (window.location.href = `https://www.nova.is/nova-tv/kaupa${query}`)
                    }
                  />
                );
              }
            })}
          </TvChannelGrid>
        )}

        <TvChannelGrid title={t('novaTv.addSubscription')}>
          {filterOutSiminnSport.map((sub: Plan) => {
            const { isStaff } = authentication;
            const query: string = serializeObject({
              ssn: isStaff ? authentication.accountInput.ssn : '',
              channel: sub.id || '',
            });
            return (
              <TvChannel
                key={sub.id}
                title={sub.product?.title || ''}
                pill={sub?.product?.metadata?.pill || null}
                description={sub.product?.description || ''}
                price={sub.amount ? formatPrice(sub.amount) : ''}
                priceUnit={sub?.interval ? t(`novaTv.pricePer.${sub.interval}`) : ''}
                buttonText={t('novaTv.buySubscription')}
                activeUntil={sub.trial?.title ?? ''}
                imageSrc={sub.product?.image?.url ?? ''}
                background="white"
                border
                borderColor="grey100"
                showDotShadow
                onSelect={() =>
                  (window.location.href = `https://www.nova.is/nova-tv/kaupa${query}`)
                }
              />
            );
          })}
        </TvChannelGrid>
      </>
    );
  }
  return null;
};

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