import React, { FormEventHandler, RefObject } from 'react';
import { Box, Text, Icon, Icons, Spinner, Chip, color, config, toRem } from 'folds';
import { useTranslation } from 'react-i18next';

// Dawn hairline divider (the canon's rgba(255,255,255,0.06–0.08) row line).
const HAIRLINE = '1px solid rgba(255, 255, 255, 0.08)';

type SearchProps = {
  active?: boolean;
  loading?: boolean;
  searchInputRef: RefObject<HTMLInputElement>;
  onSearch: (term: string) => void;
  onReset: () => void;
};
export function SearchInput({ active, loading, searchInputRef, onSearch, onReset }: SearchProps) {
  const { t } = useTranslation();
  const handleSearchSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
    evt.preventDefault();
    const { searchInput } = evt.target as HTMLFormElement & {
      searchInput: HTMLInputElement;
    };

    const searchTerm = searchInput.value.trim() || undefined;
    if (searchTerm) {
      onSearch(searchTerm);
    }
  };

  return (
    <Box as="form" direction="Column" onSubmit={handleSearchSubmit}>
      {/* Integrated hairline search row — shares the panel material instead of
          a boxed folds Input under a floating «Поиск» label. */}
      <Box
        alignItems="Center"
        gap="200"
        style={{
          paddingTop: config.space.S200,
          paddingBottom: config.space.S200,
          borderBottom: HAIRLINE,
        }}
      >
        {active && loading ? (
          <Spinner variant="Secondary" size="200" />
        ) : (
          <Icon size="200" src={Icons.Search} />
        )}
        <input
          ref={searchInputRef}
          name="searchInput"
          type="text"
          // eslint-disable-next-line jsx-a11y/no-autofocus
          autoFocus
          placeholder={t('Search.search_for_keyword')}
          autoComplete="off"
          style={{
            flex: 1,
            appearance: 'none',
            border: 'none',
            outline: 'none',
            background: 'transparent',
            font: 'inherit',
            fontSize: toRem(15),
            color: color.Surface.OnContainer,
            minWidth: 0,
          }}
        />
        {active ? (
          <Chip
            key="resetButton"
            type="reset"
            variant="SurfaceVariant"
            size="400"
            radii="Pill"
            after={<Icon size="50" src={Icons.Cross} />}
            onClick={onReset}
          >
            <Text size="B300">{t('Search.clear')}</Text>
          </Chip>
        ) : (
          <Chip type="submit" variant="Primary" size="400" radii="Pill">
            <Text size="B300">{t('Search.enter')}</Text>
          </Chip>
        )}
      </Box>
    </Box>
  );
}
