import React, { useState } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { Box, Text, useDebounce } from '@nova-hf/ui';
import { useSearchLazyQuery } from 'typings/graphql';
import { useTranslation } from 'utils/i18n';

import { SearchInput } from '../components/SearchInput';

export const maybeStrippedQueryString = (queryString: string): string => {
  const trimmedSting = queryString.trim();
  const strippedString = trimmedSting.replaceAll('-', '').replaceAll(' ', '').replaceAll('.', '');

  const parsed = Number(strippedString);

  const shouldStripDash =
    !isNaN(parsed) && (strippedString.length === 7 || strippedString.length === 10);

  if (trimmedSting.length >= 3) {
    return shouldStripDash ? strippedString : trimmedSting;
  }
  return '';
};

type SearchContainerProps = {
  onIsSearching: (isSearching: boolean) => void;
  onDataComplete: (searchTerm: string) => void;
};

export const SearchContainer = React.memo(
  ({ onIsSearching, onDataComplete }: SearchContainerProps) => {
    const { t } = useTranslation('common');
    const [searchString, setSearchString] = useState('');
    const [getResults, { error }] = useSearchLazyQuery({
      onCompleted(data) {
        onIsSearching(false);
        if (data.search?.results.length) {
          onDataComplete(searchInputValue);
        }
      },
      onError() {
        onIsSearching(false);
      },
    });

    useDebounce(
      () => {
        if (searchString) {
          getResults({
            variables: { input: { query: searchString } },
          });
        }
      },
      500,
      [searchString],
    );

    const { control, watch } = useForm<{ searchInputValue: string }>({
      defaultValues: {
        searchInputValue: '',
      },
    });

    const { searchInputValue } = watch();

    return (
      <>
        <Controller
          name="searchInputValue"
          control={control}
          render={({ field }) => {
            const { name, value, onChange } = field;
            return (
              <SearchInput
                id="name"
                name={name}
                value={value}
                type="search"
                autoComplete="off"
                placeholder={t('search.placeholder')}
                autoFocus
                {...(!value && { message: t('search.inputMessage') })}
                onChange={(e) => {
                  onChange(e.target.value);
                  if (!e.target.value) {
                    onDataComplete('');
                  } else {
                    onIsSearching(true);
                    setSearchString(maybeStrippedQueryString(e.target.value));
                  }
                }}
              />
            );
          }}
        />

        {!!error?.message && (
          <Box display="inline-flex">
            <Text variant="pMediumBold" color="warning">
              {t('search.error')}
            </Text>
            &nbsp;
            {JSON.stringify(error)}
          </Box>
        )}
      </>
    );
  },
);
