import { Suspense, useEffect, useState } from 'react'
import { ErrorBoundary } from './components/ErrorBoundary'
import { Loader } from './components/Loader'

export function App() {
  const [search, setSearch] = useState<string>('')
  const [debouncedSearch, setDebouncedSearch] = useState<string>('')

  useEffect(() => {
    const timeout = setTimeout(() => {
      setDebouncedSearch(search)
    }, 500)
    return () => {
      clearTimeout(timeout)
    }
  }, [search])

  return (
    <div>
      <input
        onChange={(ev) => {
          setSearch(ev.target.value)
        }}
        type="text"
        value={search}
      />

      <Suspense fallback={<Loader />}>
        <ErrorBoundary fallback={<div>An error occurred</div>}>
          <HideList debouncedSearch={debouncedSearch} search={search}>
            <List search={debouncedSearch} />
          </HideList>
        </ErrorBoundary>
      </Suspense>
    </div>
  )
}

function HideList({
  search,
  debouncedSearch,
  children,
}: {
  search: string
  debouncedSearch: string
  children: React.ReactNode
}) {
  if (search !== debouncedSearch) {
    // we want to hide <List /> as soon as the user starts typing and show <Loader />
    // this triggers the Suspense tag above it in the tree
    throw new Promise(() => {
      //
    })
  }
  return <>{children}</>
}
