import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import { inject } from 'mobx-react';

import { ApolloQueryResult, useApolloClient } from '@apollo/client';

import { SINGLE_SUBSCRIPTION } from 'graphql/queries/singleSubscription';

import Authentication from 'store/authentication';
import { Button, ContainerDeprecated, TextBox, FormWrapper } from '@nova-hf/ui';
import { isNationalIdValid } from 'utils/helpers';
import { SingleSubscriptionQuery } from 'typings/graphql';

import s from './Staff.module.scss';

interface IStaffProps {
  authentication: Authentication;
}

const Staff = inject('authentication')((props: IStaffProps) => {
  const [inputValue, setInputValue] = useState('');
  const [searchEnabled, setSearchEnabled] = useState(false);
  const [searching, setSearching] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const client = useApolloClient();
  const placeholderValues = ['Kennitala?', 'Símanúmer?'];
  const [placeholderText, setPlaceholderText] = useState(placeholderValues[0]);
  const router = useRouter();

  // Set placeholderText to next value from placholderValues array
  const nextPlaceholderText = (values: string[]) => {
    const length = values.length;
    const currentIndex = values.indexOf(placeholderText);

    currentIndex < length - 1
      ? setPlaceholderText(values[currentIndex + 1])
      : setPlaceholderText(values[0]);
  };

  // Change placholder text every 2 seconds
  useEffect(() => {
    const intervalId = setInterval(nextPlaceholderText, 2000, placeholderValues);
    return () => {
      clearInterval(intervalId);
    };
  });

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const notDigitRegex = /[^\d]/g;

    const input = e.target.value.replace(notDigitRegex, '');

    const inputRegex = /^([\d]{0,10})$/;
    if (input.match(inputRegex)) {
      setInputValue(input);
    }
  };

  // Set searchEnabled on inputValue change
  useEffect(() => {
    inputValue.length === 10 || inputValue.length === 7
      ? setSearchEnabled(true)
      : setSearchEnabled(false);
  }, [inputValue]);

  const searchClick = async () => {
    setSearching(true);
    setErrorMessage('');
    const inputLength = inputValue.length;

    if (inputLength === 7) {
      try {
        const { data }: ApolloQueryResult<SingleSubscriptionQuery> = await client.query({
          query: SINGLE_SUBSCRIPTION,
          variables: {
            subscriptionId: inputValue,
          },
        });

        if (data?.subscription?.ssn && data?.subscription?.ssn !== '9999999999') {
          window.location.href = `/${data.subscription.ssn}/thjonusta/${inputValue}`;
          return;
        } else if (data?.subscription?.rateplan?.typeId === 'unregistered') {
          window.location.href = `/oskrad/thjonusta/${inputValue}`;
          return;
        }

        setErrorMessage('Sláðu inn gilt símanúmer eða ossid');
      } catch (e) {
        if (e instanceof Error) setErrorMessage(e.message);
      }
    } else if (isNationalIdValid(inputValue)) {
      props.authentication.setAccountInput(inputValue);
      router.push(`/${inputValue}/thjonustur`);
      return;
    } else {
      setErrorMessage('Sláðu inn gilda kennitölu eða símanúmer');
    }

    setSearching(false);
  };

  // Search when pressing enter and search is enabled
  useEffect(() => {
    const searchInput = document.querySelector(`.${s.searchInput}`);
    const handleInputKeyup = (e: any) => {
      if (e.keyCode === 13 && searchEnabled) {
        e.preventDefault();
        searchClick();
      }
    };

    searchInput?.addEventListener('keyup', handleInputKeyup);

    return () => {
      searchInput?.removeEventListener('keyup', handleInputKeyup);
    };
  });

  return (
    <ContainerDeprecated standalone>
      <div className={s.staff}>
        <h1>Leitaðu að kennitölu eða símanúmeri!</h1>
        <div className={s.searchContainer}>
          <FormWrapper>
            <TextBox
              type="tel"
              className={s.searchInput}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleInputChange(e)}
              value={inputValue}
              placeholder={placeholderText}
              label={''}
              autoFocus={true}
              disabled={searching}
              message={errorMessage}
              status={errorMessage ? 'error' : ''}
            />
            <Button
              disabled={!searchEnabled}
              onClick={() => {
                searchClick();
              }}
              arrowRight
              fill
              big
              loading={searching}
            >
              Leita
            </Button>
          </FormWrapper>
        </div>
      </div>
    </ContainerDeprecated>
  );
});

export default Staff;
