import { useState, useEffect } from "react";

import "./Search.css";
import { getCN, randomId, usePadding, renderProps } from "../utils";

import { IconButton } from "../../index";

import { IconSearch } from "../../svg_icons/IconSearch";
import { IconClear } from "../../svg_icons/IconClear";

import FormField from "../../componentsDefault/FormField/FormField";

function Search({
  before,
  after,
  placeholder = `Поиск`,
  value,
  onChange,
  label,
  ...props
}: {
  [x: string]: any;
}) {
  const [props_id, setPropsId] = useState(randomId(props.id, `input_search`));

  const [afterOpen, setAfterOpen] = useState(false);
  const [beforeOpen, setBeforeOpen] = useState(true);

  const [_value, _setValue] = useState(``);

  useEffect(() => {
    if (_value) {
      if (_value.length >= 1) {
        setAfterOpen(true);
      } else setAfterOpen(false);
    } else setAfterOpen(false);
  }, [_value]);

  useEffect(() => {
    if (value && value.length >= 1) {
      if (_value.length < value.length) _setValue(value);
    }
  }, [value]);

  const onChangeClear = (e: any) => {
    e.target.value = ``;
    _setValue(``);
    onActive(false)
    if (onChange) onChange(e);
  };

  const _onChange = (e: any) => {
    _setValue(e.target.value);
    if (onChange) onChange(e);
  };

  const onActive = (e: any) => {
    setBeforeOpen(Boolean(e));
  };

  return (
    <FormField
      before={
        beforeOpen && (before ? before : <IconSearch width={16} height={16} />)
      }
      className={getCN([
        "MYUI-Search",
        !beforeOpen && "MYUI-Search--active",
        afterOpen && "MYUI-FormField__in--before_after",
        !afterOpen && "MYUI-FormField__in--before",
      ])}
      after={
        afterOpen &&
        (after ? (
          after
        ) : (
          <IconButton stopPropagation={true} onClick={onChangeClear}>
            <IconClear width={16} height={16} />
          </IconButton>
        ))
      }
      onActive={onActive}
    >
      <input
        placeholder={placeholder}
        aria-label={props_id}
        id={props_id}
        value={_value}
        onChange={_onChange}
        {...renderProps(props)}
        type={`search`}
      />
    </FormField>
  );
}

export default Search;
