import React, { useState } from 'react';
import {
  Box,
  MainButton,
  NumberInput,
  PackageOption,
  PackageOptionWrapper,
  SecondaryButton,
  Text,
} from '@nova-hf/ui';
import { IContext } from 'beta/typings/context';
import Wrapper from 'components/app-layout/Wrapper';
import { Segment } from 'components/segment/Segment';
import { inject } from 'mobx-react';

import {
  useCustomerHasFiberLazyQuery,
  useCustomerIdByNationalIdLazyQuery,
  useIsEligibleForNetNetLazyQuery,
  useSubscriptionSsnLazyQuery,
} from '../../typings/graphql';
import { useTranslation } from '../../utils/i18n';

const POSTPAID_MOBILE = 'R2088';

const ELIGABLE_DATA_RATEPLANS = [
  'R1706',
  'R1948',
  'R1709',
  'R1701',
  'R1710',
  'R1707',
  'R1949',
  'R1367',
];

const PREPAID_RATEPLAN = 'R1221';

const NetNet = () => {
  const { t } = useTranslation('service');
  const [number, setNumber] = useState('');
  const [hasFiber, setHasFiber] = useState(false);
  const [hasNewFiber, setHasNewFiber] = useState(false);
  const [hasBeenChecked, setHasBeenChecked] = useState(false);
  const [notNova, setNotNova] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [showSsnField, setShowSsnField] = useState(false);
  const [selectedSignupType, setSelectedSignupType] = useState('');
  const [ssn, setSsn] = useState('');
  const [ssnError, setSsnError] = useState(false);
  const [flow, setFlow] = useState('');

  const [getSubscription, { data }] = useSubscriptionSsnLazyQuery();

  const [getCustomerId] = useCustomerIdByNationalIdLazyQuery({
    variables: {
      input: {
        nationalId: data?.subscription?.accountSsn,
      },
    },
  });

  const [getCustomerHasNewFiber] = useIsEligibleForNetNetLazyQuery({
    onCompleted: (data) => {
      setHasNewFiber(data.isEligibleForNetNet ?? false);
    },
  });

  const [customerHasFiber] = useCustomerHasFiberLazyQuery({
    onCompleted(data) {
      setHasFiber(data?.isPayerOrUserOfFiber ?? false);
    },
  });

  const check = async () => {
    setIsLoading(true);

    if (number.length === 7) {
      const res = await getSubscription({
        variables: {
          input: {
            subscriptionId: number,
          },
        },
      });

      if (res.data?.subscription?.accountSsn) {
        await customerHasFiber({
          variables: {
            input: {
              ssn: res.data?.subscription?.accountSsn,
            },
          },
        });

        const { data } = await getCustomerId({
          variables: {
            input: {
              nationalId: res.data?.subscription?.accountSsn,
            },
          },
        });

        await getCustomerHasNewFiber({
          variables: {
            input: {
              id: data?.customerByNationalId?.id,
            },
          },
        });
      }
    } else {
      setNotNova(true);
    }
    setHasBeenChecked(true);
    setIsLoading(false);
  };

  const changePayerLink = `https://innri.nova.is/breyta/greidandi/${number}`;

  const handleLinkClick = (link: string, payerLink: boolean) => {
    if (payerLink) {
      window.open(link, '_blank');
    } else {
      if (link) {
        window.location.href = link;
      }
    }
  };

  const onSelectMobile = () => {
    setShowSsnField(true);
    setSelectedSignupType('mobile');
  };

  const onSelectInternet = () => {
    setShowSsnField(true);
    setSelectedSignupType('internet');
  };

  const checkSsn = async () => {
    setSsnError(false);
    setIsLoading(true);
    const { data: hasOldFiberData } = await customerHasFiber({
      variables: {
        input: {
          ssn,
        },
      },
    });

    const { data } = await getCustomerId({
      variables: {
        input: {
          nationalId: ssn,
        },
      },
    });

    const { data: hasNewFiberData } = await getCustomerHasNewFiber({
      variables: {
        input: {
          id: data?.customerByNationalId?.id,
        },
      },
    });

    if (hasNewFiberData?.isEligibleForNetNet || hasOldFiberData?.isPayerOrUserOfFiber) {
      if (selectedSignupType === 'mobile') {
        window.location.href = `http://innri.nova.is/barinn/thjonusta?netnet=${ssn}`;
      } else if (selectedSignupType === 'internet') {
        window.location.href = `http://innri.nova.is/barinn/4g-netbunadur/komdu?netnet=${ssn}`;
      }
    } else {
      setSsnError(true);
    }
    setIsLoading(false);
  };

  return (
    <Wrapper header="dark">
      <Segment>
        <Box display="flex" flexDirection="column" gap={5}>
          <Text variant="h4">{t('netNet.unlimited')}</Text>
          <Text>
            Hér geturðu nýskráð eða breytt núverandi Nova númeri í Ótakmarkað net með ljósleiðara.
          </Text>
          <PackageOptionWrapper>
            <PackageOption
              color="purple"
              big
              title="Nýskráning"
              onSelect={() => setFlow('signup')}
              selected={flow == 'signup'}
            />
            <PackageOption
              color="purple"
              big
              title="Þjónustuleiðabreyting"
              onSelect={() => setFlow('change')}
              selected={flow == 'change'}
            />
          </PackageOptionWrapper>
          {flow === 'signup' && (
            <Box>
              <Box marginBottom={3}>
                <Text variant="h6">Nýskráning</Text>
              </Box>
              <PackageOptionWrapper>
                <PackageOption
                  color="pink"
                  big
                  title="Farsími - Áskrift"
                  copy="Ótakmarkað net með ljósleiðara á 2.990 kr."
                  onSelect={onSelectMobile}
                  selected={selectedSignupType == 'mobile'}
                />
                <PackageOption
                  color="green"
                  big
                  title="Flakknet"
                  copy="Ótakmarkað net með ljósleiðara á 2.990 kr."
                  onSelect={onSelectInternet}
                  selected={selectedSignupType == 'internet'}
                />
              </PackageOptionWrapper>
              {showSsnField && (
                <Box marginTop={5}>
                  <Text>
                    Sláðu inn kennitölu greiðanda nýs númers til og við flettum upp hvort viðkomandi
                    sé skráður fyrir ljósleiðara og geti fengið Ótakmarkaðan net með ljósleiðara.
                    Við flytjum þig svo yfir í hefðbundið nýskráningarflæði þar sem hægt er að velja
                    Ótakmarkað net á 2.990 kr.
                  </Text>
                  <Box display="flex" flexDirection="row">
                    <Box width="6/12">
                      <NumberInput
                        id="ssnInputId"
                        label="Kennitala"
                        name="ssnInput"
                        numberType="nationalId"
                        required
                        disabled={false}
                        onChange={(value) => setSsn(value)}
                      />
                    </Box>
                    <Box width="6/12">
                      <MainButton
                        text={t('netNet.check')}
                        isDisabled={ssn.length !== 10}
                        onClick={() => checkSsn()}
                        colorScheme="purple"
                        dottedShadow="small"
                        isLoading={isLoading}
                      />
                    </Box>
                  </Box>
                  {ssnError && (
                    <Text>Þessi kennitala getur ekki fengið Ótakmarkað net með Ljósleiðara</Text>
                  )}
                </Box>
              )}
            </Box>
          )}
          {flow === 'change' && (
            <>
              <Text variant="h6">Breyta þjónustuleið</Text>
              <Box>
                <Box>
                  <Text>
                    Sláðu inn símanúmer sem þú vilt færa í Ótakmarkað net með Ljósleiðara. Notandi
                    eða greiðandi númers þarf að vera notandi eða greiðandi af ljósleiðara hjá Nova.
                    Sé annars greiðandi skráður fyrir númerinu þarf að brytja á því að gera
                    greiðendabreytingu.
                  </Text>
                </Box>
                <Box display="flex" flexDirection="row">
                  <Box width="3/12">
                    <NumberInput
                      id="telInputId"
                      label={t('netNet.phoneNumber')}
                      name="telInput"
                      numberType="tel"
                      required
                      disabled={false}
                      onChange={(value) => setNumber(value)}
                    />
                  </Box>
                  <Box width="3/12">
                    <MainButton
                      text={t('netNet.check')}
                      isDisabled={number.length !== 7}
                      onClick={() => check()}
                      colorScheme="purple"
                      dottedShadow="small"
                      isLoading={isLoading}
                    />
                  </Box>
                </Box>
              </Box>
              {hasBeenChecked && (
                <Box>
                  {!hasFiber && !hasNewFiber && (
                    <Box>
                      {notNova && (
                        <Text color="warning" variant="pMediumBold">
                          Þetta númer er ekki virkt hjá Nova. Vinsamlegast skoðið stöðu númers áður
                          en breytt verður í Ótakmarkað Net með ljósleiðara.
                        </Text>
                      )}
                      {!notNova && (
                        <Box>
                          <Text color="warning" variant="pMediumBold">
                            Þetta númer getur ekki fengið Ótakmarkað net með ljósleiðara þar sem
                            greiðandi þess er hvorki greiðandi né notandi af ljósleiðara tengingu.
                          </Text>
                          <SecondaryButton
                            colorScheme="purple"
                            icon="arrowRight"
                            text={t('netNet.changePayer')}
                            onClick={() => handleLinkClick(changePayerLink, true)}
                          />
                        </Box>
                      )}
                    </Box>
                  )}
                  {(hasFiber || hasNewFiber) && (
                    <Box>
                      {data?.subscription?.rateplan?.id &&
                        ELIGABLE_DATA_RATEPLANS.includes(data?.subscription?.rateplan?.id) && (
                          <Box>
                            <Text>
                              Þetta númer er netþjónusta. Smelltu hér til þess að breyta
                              Þjónustuleið í Ótakmarkað Net með ljósleiðara
                            </Text>
                            <MainButton
                              colorScheme="purple"
                              icon="arrowRight"
                              text={t('netNet.getOffer')}
                              onClick={() =>
                                handleLinkClick(
                                  `/${data.subscription?.accountSsn}/thjonusta/${number}/stillingar/thjonustuleid`,
                                  true,
                                )
                              }
                            />
                          </Box>
                        )}
                      {data?.subscription?.rateplan?.id &&
                        PREPAID_RATEPLAN == data?.subscription?.rateplan?.id && (
                          <Box>
                            <Text>
                              Þetta númer er í Frelsi. Smelltu hér til þess að fara á
                              áfyllingasíðuna og Ótakmarkað net með ljósleiðara sem skrá sjálfvirka
                              áfyllingu fyrir þetta númer
                            </Text>
                            <MainButton
                              colorScheme="purple"
                              icon="arrowRight"
                              text={t('netNet.getOffer')}
                              onClick={() =>
                                handleLinkClick(`https://www.nova.is/fylltann/${number}`, true)
                              }
                            />
                          </Box>
                        )}
                      {data?.subscription?.rateplan?.id &&
                        POSTPAID_MOBILE == data?.subscription?.rateplan?.id && (
                          <Box>
                            <Text>
                              Þetta númer er í Áskrift. Smelltu hér til þess að breyta netpakkanum í
                              Ótakmarkað net með ljósleiðara
                            </Text>
                            <MainButton
                              colorScheme="purple"
                              icon="arrowRight"
                              text={t('netNet.getOffer')}
                              onClick={() =>
                                handleLinkClick(
                                  `/${data.subscription?.accountSsn}/thjonusta/${number}/kaupa?step=1`,
                                  true,
                                )
                              }
                            />
                          </Box>
                        )}
                    </Box>
                  )}
                </Box>
              )}
            </>
          )}
        </Box>
      </Segment>
    </Wrapper>
  );
};

NetNet.getInitialProps = ({ pathname }: IContext) => {
  return {
    pathname,
    namespacesRequired: ['service'],
  };
};

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