// Copyright 2022 Northern.tech AS
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
import { useCallback, useEffect, useRef } from 'react';
import { Controller, FormProvider, useForm, useFormContext } from 'react-hook-form';

import { Clear as ClearIcon, Search as SearchIcon } from '@mui/icons-material';
import { IconButton, InputAdornment, TextField } from '@mui/material';
import { makeStyles } from 'tss-react/mui';

import { TIMEOUTS } from '@northern.tech/store/constants';
import { useDebounce } from '@northern.tech/utils/debouncehook';

const startAdornment = (
  <InputAdornment position="start">
    <SearchIcon color="disabled" fontSize="small" />
  </InputAdornment>
);

// due to search not working reliably for single letter searches, only start at 2
const MINIMUM_SEARCH_LENGTH = 2;
const useStyles = makeStyles()(() => ({
  adornment: {
    visibility: 'hidden',
    opacity: 0,
    transition: 'opacity 0.3s ease-in-out'
  },
  textFieldRoot: {
    '& .MuiOutlinedInput-root:hover, & .Mui-focused': {
      '& .MuiInputAdornment-root': {
        visibility: 'visible',
        opacity: 1
      }
    }
  }
}));
export const ControlledSearch = ({
  className = '',
  showSearchIcon = true,
  asFormField = false,
  name = 'search',
  onSearch,
  placeholder = 'Search devices',
  style = {},
  clearButtonOnHover = false
}) => {
  const { control, watch, resetField } = useFormContext();
  const inputRef = useRef();
  const focusLockRef = useRef(true);
  const timer = useRef(); // this + the above focusLock are needed to work around the focus being reassigned to the input field which would cause runaway search triggers
  const triggerDebounceRef = useRef(false); // this is needed to reject the search triggered through the recreation of the onSearch callback
  const { classes } = useStyles();
  const searchValue = watch(name, '');

  const debouncedSearchTerm = useDebounce(searchValue, TIMEOUTS.debounceDefault);
  const shouldTriggerSearch = !asFormField && !!onSearch;

  const focusAndLock = () => {
    focusLockRef.current = false;
    inputRef.current.focus();
    clearTimeout(timer.current);
    triggerDebounceRef.current = false;
    timer.current = setTimeout(() => (focusLockRef.current = true), TIMEOUTS.oneSecond);
  };

  useEffect(
    () => () => {
      clearTimeout(timer.current);
    },
    []
  );

  useEffect(() => {
    if (!shouldTriggerSearch || debouncedSearchTerm.length < MINIMUM_SEARCH_LENGTH || triggerDebounceRef.current) {
      return;
    }
    triggerDebounceRef.current = true;
    onSearch(debouncedSearchTerm).then(focusAndLock);
  }, [debouncedSearchTerm, onSearch, shouldTriggerSearch]);

  const onTriggerSearch = useCallback(
    ({ key }) => {
      if (shouldTriggerSearch && key === 'Enter' && (!debouncedSearchTerm || debouncedSearchTerm.length >= MINIMUM_SEARCH_LENGTH)) {
        onSearch(debouncedSearchTerm).then(focusAndLock);
      }
    },
    [debouncedSearchTerm, onSearch, shouldTriggerSearch]
  );

  const onFocus = useCallback(() => {
    if (shouldTriggerSearch && focusLockRef.current && debouncedSearchTerm.length >= MINIMUM_SEARCH_LENGTH) {
      onSearch(debouncedSearchTerm).then(focusAndLock);
    }
  }, [debouncedSearchTerm, onSearch, shouldTriggerSearch]);

  const resetSearchAdornment = searchValue ? (
    <InputAdornment position="end" className={clearButtonOnHover ? classes.adornment : ''}>
      <IconButton
        size="small"
        onMouseDown={e => e.preventDefault()}
        onClick={() => {
          resetField(name);
          inputRef.current?.focus();
        }}
      >
        <ClearIcon />
      </IconButton>
    </InputAdornment>
  ) : null;

  const adornments = { ...(showSearchIcon ? { startAdornment } : {}), endAdornment: resetSearchAdornment };
  return (
    <Controller
      name={name}
      control={control}
      render={({ field: { ref, ...restField } }) => (
        <TextField
          className={`${className} ${classes.textFieldRoot}`}
          slotProps={{ input: adornments }}
          onKeyUp={onTriggerSearch}
          onFocus={onFocus}
          placeholder={placeholder}
          size="small"
          style={style}
          {...restField}
          inputRef={el => {
            ref(el);
            inputRef.current = el;
          }}
        />
      )}
    />
  );
};

ControlledSearch.displayName = 'ConnectedSearch';

const Search = props => {
  const { className = '', searchTerm, onSearch, trigger } = props;
  const methods = useForm({ mode: 'onChange', defaultValues: { search: searchTerm ?? '' } });
  const { handleSubmit } = methods;
  const onSubmit = useCallback(search => onSearch(search, !trigger), [onSearch, trigger]);
  return (
    <FormProvider {...methods}>
      <form className={className} noValidate onSubmit={handleSubmit(({ search }) => onSearch(search, !trigger))}>
        <ControlledSearch {...props} onSearch={onSubmit} />
        <input className="hidden" type="submit" />
      </form>
    </FormProvider>
  );
};

export default Search;
