import React, { useEffect, useState } from 'react';
import { Box, FormStatusMessage, Input, MainButton } from '@nova-hf/ui';
import { inject, observer } from 'mobx-react';
import { throwErrorWithMessage } from 'store/mobileSignup';
import {
  PortabilityStatus,
  useCustomerNameByNationalIdQuery,
  useMobileCartQuery,
  usePortabilityStatusLazyQuery,
} from 'typings/graphql';

import { useSignupScroll } from '../hooks/useSignupScroll';
import { MobileChildrenProps } from '../kaupa/StepSetup';

type TransferNumberProps = Pick<
  MobileChildrenProps,
  'authentication' | 'mobileSignup' | 'cart' | 'id'
>;

const TransferNumber = ({ authentication, mobileSignup, cart, id }: TransferNumberProps) => {
  if (!mobileSignup) return null;
  const [portabilityStatus, setPortabilityStatus] = useState<PortabilityStatus>();
  const [email, setEmail] = useState('');
  const [nationalIdByStaff, setNationalIdByStaff] = useState('');
  const [phoneNumber, setPhoneNumber] = useState<string>(() => {
    if (mobileSignup.isUpdatingSubscription) {
      return mobileSignup.servicePurchaseInfo.service.phoneNumber ?? '';
    } else {
      return '';
    }
  });
  const [isSuccess, setIsSuccess] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [hasError, setHasError] = useState('');
  const [needEmail, setNeedEmail] = useState(false);
  const [nationalIdTamperedWith, setNationalIdTamperedWith] = useState(false);
  const { onComplete } = useSignupScroll({
    id,
  });
  const { data: customerData } = useCustomerNameByNationalIdQuery({
    variables: { input: { nationalId: cart?.nationalId } },
  });
  const [portabilityQuery] = usePortabilityStatusLazyQuery();

  const handleNationalIdChange = (nationalId: string) => {
    setNationalIdByStaff(nationalId);
    setNationalIdTamperedWith(true);
  };

  const { data: cartData } = useMobileCartQuery({
    skip: !cart?.activeCartId,
    variables: {
      input: {
        cartId: cart?.activeCartId ?? '',
      },
    },
  });

  const itemsThatHavePhoneNumbers = cartData?.cart?.items.filter((item) => {
    if (
      item.purchaseInfo?.service?.__typename === 'MobileServiceRequest' &&
      item.purchaseInfo.service.phoneNumber
    ) {
      return item;
    }
  });
  const hasPortedCurrentNumber = () => {
    const numberIsInCart = !!itemsThatHavePhoneNumbers?.find((item) => {
      if (item.purchaseInfo?.service?.__typename === 'MobileServiceRequest') {
        return item.purchaseInfo.service.phoneNumber === phoneNumber;
      }
    });
    return numberIsInCart && !mobileSignup.isUpdatingSubscription;
  };

  const checkPortabilityStatus = async (): Promise<PortabilityStatus | undefined> => {
    try {
      const nationalId = authentication?.isStaff
        ? nationalIdByStaff
        : authentication?.loggedInUserSsn;
      setIsLoading(true);
      const { data, error } = await portabilityQuery({
        variables: {
          input: {
            phoneNumber,
            nationalId: nationalId || '',
          },
        },
      });
      if (error) setHasError('Error fetching portability status');
      if (data?.portabilityStatus) {
        setIsLoading(false);
        if (authentication?.isStaff) {
          const rightHolder = {
            nationalId: nationalId,
            email: needEmail ? email : customerData?.customerByNationalId?.email,
          };
          mobileSignup?.setRightHolder(rightHolder);
        }
        return data?.portabilityStatus;
      }
      setIsLoading(false);
      return undefined;
    } catch (e) {
      setIsLoading(false);
      throwErrorWithMessage(e, 'Failed to connect to HÍN');
      return undefined;
    }
  };

  const handleTransfer = async () => {
    setHasError('');
    if (phoneNumber.length === 7 && isSuccess) {
      if (!authentication?.isStaff) {
        const rightHolder = {
          nationalId: cart?.nationalId,
          email: customerData?.customerByNationalId?.email,
        };
        mobileSignup?.setRightHolder(rightHolder);
      }
      onComplete();
    } else {
      if (phoneNumber.length === 7) {
        const phoneNumberAlreadyInCart = hasPortedCurrentNumber();
        const canTransfer = await checkPortabilityStatus();
        setPortabilityStatus(canTransfer);
        const hasEmailIfNeeded = (needEmail && !!email) || !needEmail;
        if (canTransfer?.isPortInAllowed && hasEmailIfNeeded && !phoneNumberAlreadyInCart) {
          setIsSuccess(true);
          mobileSignup?.setPortingNumber(phoneNumber);
          setTimeout(() => {
            onComplete();
          }, 1000);
          onComplete();
        } else {
          setIsSuccess(false);
          mobileSignup?.setPortingNumber('');
        }
      }
    }
  };

  useEffect(() => {
    if (cart?.nationalId) {
      setNationalIdByStaff(cart.nationalId);
    }
  }, [cart?.nationalId]);

  useEffect(() => {
    if (nationalIdByStaff !== cart?.nationalId) {
      setNeedEmail(true);
    } else {
      setNeedEmail(false);
    }
  }, [nationalIdByStaff]);

  const textForNotRightHolder = authentication?.isStaff
    ? 'Greiðandi er ekki rétthafi númersins. Sláðu inn kt. rétthafa svo hann geti samþykkt flutninginn.'
    : 'Greiðandi er ekki rétthafi númers';
  const emailError = needEmail && email.length <= 1 && nationalIdByStaff.length > 9;

  const errorText = () => {
    if (hasPortedCurrentNumber()) {
      return 'Núverandi númer nú þegar í körfu';
    }
    if (portabilityStatus?.isNovaNumber) {
      return 'Númer er nú þegar hjá Nova';
    }
    if (!portabilityStatus?.isOwner) {
      return textForNotRightHolder;
    }
    if (!portabilityStatus?.isPortInAllowed && portabilityStatus?.isOwner) {
      return 'Virkur flutningur er nú þegar í gangi';
    }
    if (emailError) {
      return 'Vinsamlegast skráðu netfang rétthafa';
    }
    if (!portabilityStatus) {
      return 'Ekki er hægt að flytja númer';
    }
    return '';
  };

  const shouldShowError =
    (portabilityStatus?.isPortInAllowed !== undefined && !portabilityStatus.isPortInAllowed) ||
    (emailError && email.length > 3) ||
    hasPortedCurrentNumber();

  return (
    <Box display="flex" flexDirection="column" width="100%" marginTop={1}>
      <Input
        id={'input'}
        name="input"
        onChange={(e) => setPhoneNumber(e?.target.value)}
        onClick={() => handleTransfer()}
        disabled={isLoading || mobileSignup.isUpdatingSubscription}
        placeholder="Símanúmer"
        value={phoneNumber}
        trailingElement={
          <MainButton
            buttonHeight={6}
            isDisabled={phoneNumber.length !== 7 || mobileSignup.isUpdatingSubscription}
            text={!portabilityStatus?.isPortInAllowed || emailError ? 'Skoða' : 'Áfram'}
            isLoading={isLoading}
            onClick={() => handleTransfer()}
          />
        }
      />
      {(isSuccess || shouldShowError || !!hasError) && (
        <FormStatusMessage
          status={isSuccess ? 'success' : 'error'}
          message={isSuccess ? 'Hægt að færa númerið yfir' : hasError ? hasError : errorText()}
        />
      )}

      {authentication?.isStaff && (
        <Box display="flex" flexDirection="column" gap={2} marginTop={2}>
          {((portabilityStatus && !portabilityStatus?.isOwner && phoneNumber.length === 7) ||
            nationalIdTamperedWith) && (
            <Input
              id={'kennitala'}
              name={'kennitala'}
              onChange={(e) => handleNationalIdChange(e?.target.value ?? '')}
              label="Kennitala"
              value={nationalIdByStaff}
              backgroundColor="grey100"
            />
          )}

          {(needEmail || nationalIdTamperedWith) && (
            <Input
              id={'email'}
              name={'email'}
              onChange={(e) => setEmail(e?.target.value ?? '')}
              label="Netfang"
              value={email}
              backgroundColor="grey100"
            />
          )}
        </Box>
      )}
    </Box>
  );
};
export default inject('authentication', 'mobileSignup', 'cart')(observer(TransferNumber));
