import React, { useEffect, useState } from 'react';
import { Box, Container, makeToast, Text } from '@nova-hf/ui';
import Layout from 'beta/components/layouts/Layout';
import UI from 'beta/store/ui';
import { IContext } from 'beta/typings/context';
import { inject, observer } from 'mobx-react';
import { useRouter } from 'next/router';
import {
  SearchHit,
  useAddCustomerMutation,
  useCustomerIdByNationalIdLazyQuery,
  useSearchLazyQuery,
} from 'typings/graphql';
import { useTranslation } from 'utils/i18n';

import { Panel } from './components/Panel';
import { SearchLoading } from './components/SearchLoading';
import { maybeStrippedQueryString, SearchContainer } from './containers/SearchContainer';

type LeitProps = {
  ui?: UI;
};

const Leit = ({ ui }: LeitProps) => {
  const { t } = useTranslation('common');
  const router = useRouter();
  const [customerClicked, setCustomerClicked] = useState('');
  const [isSearching, setIsSearching] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [getResults, { data, loading }] = useSearchLazyQuery();
  const [getCustomerId] = useCustomerIdByNationalIdLazyQuery({
    onCompleted(data) {
      if (data?.customerByNationalId?.id) handleRedirectToCustomerId(data.customerByNationalId?.id);
    },
    onError(error) {
      if (error) handleRedirectToNewCustomer();
    },
  });
  const [addCustomer] = useAddCustomerMutation();

  const searchResultsLen =
    data?.search?.results.map((result) => result.hits.length).reduce((a, b) => a + b, 0) ?? 0;

  useEffect(() => {
    if (ui) {
      ui.setIsHeaderInverted(false);
    }
  }, []);

  useEffect(() => {
    const searchQuery = maybeStrippedQueryString(searchTerm);
    if (searchQuery) {
      getResults({ variables: { input: { query: searchQuery } } });
    }
  }, [searchTerm]);

  const handleRedirectToCustomerId = (customerId: string) => {
    if (customerId) {
      router.push(`/beta/${customerId}/yfirlit/`);
    }
  };

  const handleRedirectToNewCustomer = async () => {
    if (customerClicked) {
      try {
        const { data: addCustomerData } = await addCustomer({
          variables: {
            input: {
              nationalId: customerClicked,
            },
          },
        });
        if (addCustomerData?.addCustomer.customer.id) {
          const id = addCustomerData.addCustomer.customer.id;
          if (id) router.push(`/beta/${id}/yfirlit/`);
        } else if (addCustomerData?.addCustomer.error) {
          if (addCustomerData?.addCustomer.error instanceof Error) {
            makeToast.danger('Eitthvað fór úrskeiðis', addCustomerData?.addCustomer.error.message);
          }
        }
      } catch (error) {
        if (error instanceof Error) {
          makeToast.danger('Eitthvað fór úrskeiðis', error.message);
        }
      }
    }
  };

  const handleSearchHitClick = (nationalId: string) => {
    if (nationalId) {
      if (nationalId !== '9999999999') {
        setCustomerClicked(nationalId);
        getCustomerId({
          variables: { input: { nationalId: nationalId } },
        });
      } else {
        makeToast.warning('Oops', 'Ekki fannst kennitala á leitarniðurstöðu');
      }
    }
  };

  return (
    <Layout hasSideMenu={false}>
      <Container position="relative" paddingTop={20}>
        <SearchContainer onIsSearching={setIsSearching} onDataComplete={setSearchTerm} />
        {(loading || isSearching) && !data?.search?.results.length && <SearchLoading />}

        {!!data?.search?.results.length && !!searchTerm && (
          <>
            <>
              {!searchResultsLen && (
                <Box display="inline-flex" marginTop={8}>
                  <Text variant="pMediumRegular">{t('search.noResultsFor')}</Text>
                  &nbsp;
                  <Text variant="pMediumBold" color="pink">{`"${searchTerm}"`}</Text>
                </Box>
              )}
              {data?.search.results.map((s) => {
                if (!s.hits.length) return null;
                return (
                  <Box key={s.index} marginY={8}>
                    <Box marginBottom={8}>
                      <Box display="flex" justifyContent="space-between" alignItems="center">
                        <Text variant="h6">{t(`search.${s.index.toString().toLowerCase()}`)}</Text>
                      </Box>
                    </Box>
                    {s.hits.length && (
                      <>
                        <Panel onClick={handleSearchHitClick} hits={s.hits as SearchHit[]} />
                      </>
                    )}
                    <Box
                      borderBottomStyle="solid"
                      borderColor="grey200"
                      borderWidth="1px"
                      paddingTop={8}
                    />
                  </Box>
                );
              })}
            </>
            <Box
              display={{ sm: 'none', md: 'none', lg: 'inline-flex' }}
              position="absolute"
              top={25}
              right={0}
            >
              <Text variant="pMediumRegular">{t('search.showing')}</Text>&nbsp;
              <Text variant="pMediumBold" color="pink">
                {searchResultsLen}
              </Text>
              &nbsp;
              <Text variant="pMediumRegular">{t('search.resultsFor')}</Text>&nbsp;
              <Text variant="pMediumBold" color="pink">{`"${searchTerm}"`}</Text>
            </Box>
          </>
        )}
      </Container>
    </Layout>
  );
};

Leit.getInitialProps = ({ pathname, query }: IContext) => {
  return {
    pathname,
    customerId: query.customerId,
    namespacesRequired: ['common'],
  };
};

export default inject('ui')(observer(Leit));
