import { useRef, useEffect } from 'react'

import { useRouteMatch } from 'react-router-dom'

import isEmpty from 'lodash/isEmpty'

import { PAGES, ProfileTypes } from 'config'

import {
  Input,
  TabsGroup,
  Tab,
} from 'features/Common'
import { ItemsList } from 'features/ItemsList'
import { OutsideClick } from 'features/OutsideClick'
import { Loader } from 'features/Loader'
import { T9n } from 'features/T9n'

import { useSearch } from './hooks'
import {
  Wrapper,
  Form,
  ListWrapper,
  LoaderWrapper,
  Results,
  ClearButton,
} from './styled'

export const Search = () => {
  const {
    clearQuery,
    close,
    isFetching,
    isOpen,
    onChange,
    onSubmit,
    onTabClick,
    query,
    searchItems,
    selectedTab,
    showResults,
  } = useSearch()

  const listRef = useRef<null | HTMLDivElement>(null)

  useEffect(() => {
    listRef.current?.scrollTo(0, 0)
  }, [selectedTab])

  const isMatch = useRouteMatch(`/:sportName${PAGES.match}/:pageId`)?.isExact || false
  return (
    <OutsideClick onClick={close}>
      <Wrapper>
        <Form
          role='search'
          isMatch={isMatch}
          onSubmit={onSubmit}
          expand={isOpen}
        >
          <Input
            autoComplete='off'
            type='search'
            value={query}
            onChange={onChange}
          />
          {(query || isOpen) && <ClearButton onClick={clearQuery} />}
          {isFetching && (
            <LoaderWrapper>
              <Loader color='#363636' />
            </LoaderWrapper>
          )}
        </Form>
        {(showResults && query !== '') && (
          <Results>
            <TabsGroup>
              <Tab
                disabled={isEmpty(searchItems[ProfileTypes.TOURNAMENTS])}
                selected={selectedTab === ProfileTypes.TOURNAMENTS}
                onClick={() => onTabClick(ProfileTypes.TOURNAMENTS)}
              >
                <T9n t='tournament' />
              </Tab>
              <Tab
                disabled={isEmpty(searchItems[ProfileTypes.TEAMS])}
                selected={selectedTab === ProfileTypes.TEAMS}
                onClick={() => onTabClick(ProfileTypes.TEAMS)}
              >
                <T9n t='team' />
              </Tab>
              <Tab
                disabled={isEmpty(searchItems[ProfileTypes.PLAYERS])}
                selected={selectedTab === ProfileTypes.PLAYERS}
                onClick={() => onTabClick(ProfileTypes.PLAYERS)}
              >
                <T9n t='player' />
              </Tab>
            </TabsGroup>
            <ListWrapper ref={listRef}>
              <ItemsList
                list={searchItems[selectedTab]}
                close={close}
              />
            </ListWrapper>
          </Results>
        )}
      </Wrapper>
    </OutsideClick>
  )
}
