"use client"
import { useEffect, useState } from "react"
import { useFormContext } from "react-hook-form"
import { useIntl } from "react-intl"

import { ErrorCircleIcon } from "@/components/Icons"
import Divider from "@/components/TempDesignSystem/Divider"
import Body from "@/components/TempDesignSystem/Text/Body"
import Caption from "@/components/TempDesignSystem/Text/Caption"
import Footnote from "@/components/TempDesignSystem/Text/Footnote"

import ClearSearchButton from "./ClearSearchButton"
import Dialog from "./Dialog"
import List from "./List"

import styles from "./searchList.module.css"

import type { SearchListProps } from "@/types/components/search"

export default function SearchList({
  getItemProps,
  getMenuProps,
  handleClearSearchHistory,
  highlightedIndex,
  isOpen,
  locations,
  search,
  searchHistory,
}: SearchListProps) {
  const intl = useIntl()
  const [hasMounted, setHasMounted] = useState(false)
  const [isFormSubmitted, setIsFormSubmitted] = useState(false)
  const {
    clearErrors,
    formState: { errors, isSubmitted },
  } = useFormContext()
  const searchError = errors["search"]

  useEffect(() => {
    setIsFormSubmitted(isSubmitted)
  }, [isSubmitted])

  useEffect(() => {
    let timeoutID: ReturnType<typeof setTimeout> | null = null
    if (searchError && searchError.message === "Required") {
      timeoutID = setTimeout(() => {
        clearErrors("search")
        setIsFormSubmitted(false)
        // magic number originates from animation
        // 5000ms delay + 120ms exectuion
      }, 5120)
    }

    return () => {
      if (timeoutID) {
        clearTimeout(timeoutID)
      }
    }
  }, [clearErrors, searchError])

  useEffect(() => {
    setHasMounted(true)
  }, [setHasMounted])

  if (!hasMounted) {
    return null
  }

  if (searchError && isFormSubmitted) {
    if (typeof searchError.message === "string") {
      if (!isOpen) {
        if (searchError.message === "Required") {
          return (
            <Dialog
              className={styles.fadeOut}
              getMenuProps={getMenuProps}
              variant="error"
            >
              <Caption className={styles.heading} color="red">
                <ErrorCircleIcon color="red" />
                {intl.formatMessage({ id: "Enter destination or hotel" })}
              </Caption>
              <Body>
                {intl.formatMessage({
                  id: "A destination or hotel name is needed to be able to search for a hotel room.",
                })}
              </Body>
            </Dialog>
          )
        }
      }
    }
  }

  if (!isOpen) {
    return null
  }

  if (locations.length) {
    const cities = locations.filter((location) => location.type === "cities")
    const hotels = locations.filter((location) => location.type === "hotels")
    return (
      <Dialog getMenuProps={getMenuProps} variant="search">
        <List
          getItemProps={getItemProps}
          highlightedIndex={highlightedIndex}
          label={intl.formatMessage({ id: "Cities" })}
          locations={cities}
        />
        <List
          getItemProps={getItemProps}
          highlightedIndex={highlightedIndex}
          initialIndex={cities.length}
          label={intl.formatMessage({ id: "Hotels" })}
          locations={hotels}
        />
      </Dialog>
    )
  }

  if (!search && searchHistory?.length) {
    return (
      <Dialog getMenuProps={getMenuProps}>
        <Footnote color="uiTextPlaceholder" textTransform="uppercase">
          {intl.formatMessage({ id: "Latest searches" })}
        </Footnote>
        <List
          getItemProps={getItemProps}
          highlightedIndex={highlightedIndex}
          locations={searchHistory}
        />
        <Divider className={styles.divider} color="beige" />
        <ClearSearchButton
          getItemProps={getItemProps}
          handleClearSearchHistory={handleClearSearchHistory}
          highlightedIndex={highlightedIndex}
          index={searchHistory.length}
        />
      </Dialog>
    )
  }

  if (search) {
    return (
      <Dialog getMenuProps={getMenuProps} variant="error">
        <Body className={styles.text} textTransform="bold">
          {intl.formatMessage({ id: "No results" })}
        </Body>
        <Body className={styles.text} color="uiTextPlaceholder">
          {intl.formatMessage({
            id: "We couldn't find a matching location for your search.",
          })}
        </Body>
        {searchHistory ? (
          <>
            <Divider className={styles.noResultsDivider} color="beige" />
            <Footnote
              className={styles.text}
              color="uiTextPlaceholder"
              textTransform="uppercase"
            >
              {intl.formatMessage({ id: "Latest searches" })}
            </Footnote>
            <List
              getItemProps={getItemProps}
              highlightedIndex={highlightedIndex}
              locations={searchHistory}
            />
            <Divider className={styles.divider} color="beige" />
            <ClearSearchButton
              getItemProps={getItemProps}
              handleClearSearchHistory={handleClearSearchHistory}
              highlightedIndex={highlightedIndex}
              index={searchHistory.length}
            />
          </>
        ) : null}
      </Dialog>
    )
  }

  return null
}
