import React, { useState } from 'react';
import { useQuery } from '@apollo/client';
import { ContainerDeprecated, ServicePacks, StepTitle } from '@nova-hf/ui';
import { SUBSCRIPTION } from 'graphql/queries/subscription';
import { inject, observer } from 'mobx-react';
import { useRouter } from 'next/router';
import Authentication from 'store/authentication';
import { IUserData } from 'typings';

import {
  useCustomerIdByNationalIdQuery,
  useIsEligibleForNetNetLazyQuery,
} from '../../../typings/graphql';

type IAddServicePackProps = {
  color: string;
  onNext: () => void;
  change?: any;
  authentication?: Authentication;
};

const AddServicePack = ({ color, onNext, change, authentication }: IAddServicePackProps) => {
  const onSelect = (item: any) => {
    change.selectedServicepack = item;
    change.checkEffectTime = true;
    onNext();
  };

  const router = useRouter();
  const [hasNewFiber, setHasNewFiber] = useState(false);
  const accountInput = authentication?.accountInput;
  const subscriptionId = router?.query?.subscriptionId;
  const { data: subscriptionData } = useQuery<IUserData>(SUBSCRIPTION, {
    variables: { subscriptionId, accountInput },
  });

  const {
    me: { profiles },
  } = subscriptionData ?? { me: { profiles: [] } };
  const accountSsn = profiles?.[0]?.accountSsn;
  const selected = change.selectedServicepack;
  const { error } = useCustomerIdByNationalIdQuery({
    variables: {
      input: {
        nationalId: accountSsn,
      },
    },
    skip: !accountSsn,
    onCompleted: (data) => {
      const userId = data?.customerByNationalId?.id;
      if (userId) {
        fiberInfo({
          variables: {
            input: {
              id: userId,
            },
          },
        });
      }
    },
  });
  const [fiberInfo] = useIsEligibleForNetNetLazyQuery({
    onCompleted(data) {
      if (data?.isEligibleForNetNet) {
        setHasNewFiber(data.isEligibleForNetNet);
      }
    },
  });

  const { servicepacks, name, description } = change.servicepackType;

  if (hasNewFiber && !error) {
    const hasExtraPack = servicepacks?.find((item) => item?.id === 'S3009');

    if (!hasExtraPack && name.includes('Netið')) {
      servicepacks.push({
        billingunit: undefined,
        dataAmountinMb: 5000000,
        dataInEurope: 'EES: 25 GB á 0 kr. og umfram það 0,28 kr./MB',
        description: 'Með ljósleiðara',
        forSale: true,
        id: 'S3009',
        offerPrice: 3190,
        price: 3190,
        shortTitle: '∞ GB',
        title: '∞ GB',
        typeId: 'phonedata',
      });
    }
  }

  return (
    <ContainerDeprecated>
      <StepTitle title={name} subtitle={description} color={color} />

      <ServicePacks color={color} list={servicepacks} selected={selected} onSelect={onSelect} big />
    </ContainerDeprecated>
  );
};

export default inject('change', 'authentication')(observer(AddServicePack));
