import React, { Fragment } from 'react'

import isEmpty from 'lodash/isEmpty'

import { Input } from 'features/Common'
import { ItemsList } from 'features/ItemsList'
import { OutsideClick } from 'features/OutsideClick'

import { useSearch } from './hooks'
import { Header } from './components/Header'
import {
  Wrapper,
  Form,
  Results,
} from './styled'

export const Search = () => {
  const {
    close,
    normalizedItems: {
      players,
      teams,
      tournaments,
    },
    onChange,
    onFocus,
    onSubmit,
    showResults,
  } = useSearch()

  return (
    <OutsideClick onClick={close}>
      <Wrapper>
        <Form role='search' onSubmit={onSubmit}>
          <Input
            id='searchInput'
            type='search'
            onChange={onChange}
            onFocus={onFocus}
          />
        </Form>
        {showResults && (
          <Results>
            {!isEmpty(tournaments) && (
              <Fragment>
                <Header title='tournament' image='tournament' />
                <ItemsList list={tournaments} />
              </Fragment>
            )}

            {!isEmpty(teams) && (
              <Fragment>
                <Header title='team' image='team' />
                <ItemsList list={teams} />
              </Fragment>
            )}

            {!isEmpty(players) && (
              <Fragment>
                <Header title='player' image='player' />
                <ItemsList list={players} />
              </Fragment>
            )}
          </Results>
        )}
      </Wrapper>
    </OutsideClick>
  )
}
