import { useCallback, useMemo, useState, memo } from 'react';
import type { ChangeEvent } from 'react';
import clsx from 'clsx';

import IconButton from '@mui/material/IconButton';

import { ASSETS_URL } from '../../../consts/common';
import { CustomIcon } from '../../custom-icon';
import { TextField } from '../text-field';
import type { TextFieldProps } from '../text-field';
import createClasses from './styles';

export type SearchFieldProps = TextFieldProps & {
  /**
   * Callback fired on clicking the clear icon button.
   */
  handleClear?: () => void;
  /**
   * Callback to be fired on uncontrolled change.
   */
  handleChangeCallback?: (
    value: string | ChangeEvent<HTMLTextAreaElement | HTMLInputElement>
  ) => void;
};

const SearchField = (props: SearchFieldProps) => {
  const {
    inputProps,
    InputProps,
    handleClear,
    handleChangeCallback,
    value,
    error,
    size,
    className,
    ...otherProps
  } = props;
  const styles = createClasses();

  const [uncontrolledValue, setUncontrolledValue] = useState('');

  const handleUncontrolledClear = useCallback(() => {
    setUncontrolledValue('');
    handleChangeCallback?.('');
  }, [handleChangeCallback]);

  const handleUncontrolledChange: TextFieldProps['onChange'] = useCallback(
    e => {
      setUncontrolledValue(e.target.value);
      handleChangeCallback?.(e);
    },
    [handleChangeCallback]
  );

  const currentValue = useMemo(
    () => (typeof value === 'string' ? value : uncontrolledValue),
    [uncontrolledValue, value]
  );

  return (
    <TextField
      value={currentValue}
      autoComplete="off"
      onChange={handleUncontrolledChange}
      inputProps={{
        'data-testid': 'searchField',
        ...inputProps
      }}
      className={clsx(className, {
        [styles.error]: error,
        [styles.smallTextField]: size === 'small'
      })}
      InputProps={{
        endAdornment: currentValue ? (
          <IconButton
            data-testid="searchClear"
            size="small"
            className={styles.button}
            onClick={handleClear || handleUncontrolledClear}
          >
            <CustomIcon
              color="inherit"
              src={`${ASSETS_URL}/icons/icon_closeCircle.svg`}
              className={styles.clearIcon}
            />
          </IconButton>
        ) : (
          <CustomIcon
            color="inherit"
            src={`${ASSETS_URL}/icons/icon_search.svg`}
            className={styles.searchIcon}
          />
        ),
        ...InputProps
      }}
      {...otherProps}
    />
  );
};

const m = memo(SearchField);
export { m as SearchField };
