import React, { FormEvent } from 'react'
import { Button, FormControl, Input, InputGroup, InputRightElement, useColorModeValue } from '@chakra-ui/react'
import { SearchIcon } from '@chakra-ui/icons'
import { GameList } from '../models/game'
import { useHookstate } from '@hookstate/core'
import { gameDashboardState } from '../stateManagement/gameState'
import {
  loadingAndSaveState,
  loadingState,
  openAndCloseSearchDialogue, searchCompletedState, showFiltersModuleState,
} from '../stateManagement/loadingState'
import { useNavigate } from 'react-router-dom'
import { adminMode } from '../stateManagement/userState'
import getWithFilters from '../componentUtils/getWithFilters'
import {ChangeActiveFilterHeader} from "../componentUtils/changeActiveFilterHeader";
import {ratingState, steamRatingState} from "../stateManagement/ratingState";

export default function Search() {
  const gamesState = useHookstate(gameDashboardState)
  const games = gamesState.get()
  const loadedState = useHookstate(loadingState)
  const submitLoadingState = useHookstate(loadingAndSaveState)
  const setShowFiltersModuleState = useHookstate(showFiltersModuleState)
  const submitLoading = submitLoadingState.get()
  const bg = useColorModeValue('gray.50', 'transparent')
  const page = games.count.currentPage
  const limit = games.count.limit
  const setIsOpen = useHookstate(openAndCloseSearchDialogue)
  const admin = useHookstate(adminMode).get()
  const history = useNavigate()
  const useRatingState = useHookstate(ratingState).get()
  const useSteamRatingState = useHookstate(steamRatingState).get()
  const searchFinished= useHookstate(searchCompletedState)
  const handleClose = () => {
    setIsOpen.set(false)
  }

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    submitLoadingState.set(true)
    await getWithFilters(gamesState, loadedState, admin, page, limit, games.searchParams, games.filters, useRatingState, useSteamRatingState)
    submitLoadingState.set(false)
    games.searchParams.length > 0 && searchFinished.set(true)
    handleClose()
    return history('/games')
  }

  const handleInputChange = <G extends keyof GameList>(name: G, value: string) => {
    gamesState.merge(() => ({ [name]: value }))
    ChangeActiveFilterHeader(games.filters, games.searchParams, setShowFiltersModuleState)
  }


  return (
      <>
        <form onSubmit={handleSubmit}>
          <FormControl mb="3">
            <InputGroup>
              <Input
                  autoFocus
                  id="searchParams"
                  name="searchParams"
                  bg={bg}
                  type="text"
                  border="1px"
                  borderColor="gray.500"
                  rounded="md"
                  placeholder="Search..."
                  value={games.searchParams}
                  onChange={(e) => {
                    handleInputChange('searchParams', e.target.value)
                  }}
              />
              <InputRightElement>
                <Button
                    isLoading={submitLoading}
                    type="submit"
                    colorScheme="blue"
                >
                  <SearchIcon/>
                </Button>
              </InputRightElement>
            </InputGroup>
          </FormControl>
        </form>
      </>
  )
}