"use client"

import { usePathname, useSearchParams } from "next/navigation"
import { useCallback } from "react"
import { useIntl } from "react-intl"

import Select from "@/components/TempDesignSystem/Select"
import { trackEvent } from "@/utils/tracking/base"

import {
  type HotelSorterProps,
  type SortItem,
  SortOrder,
} from "@/types/components/hotelReservation/selectHotel/hotelSorter"

export const DEFAULT_SORT = SortOrder.Distance

export default function HotelSorter({ discreet }: HotelSorterProps) {
  const searchParams = useSearchParams()
  const pathname = usePathname()
  const intl = useIntl()

  const onSelect = useCallback(
    (value: string | number) => {
      const newSort = value.toString()
      if (newSort === searchParams.get("sort")) {
        return
      }

      const newSearchParams = new URLSearchParams(searchParams)
      newSearchParams.set("sort", newSort)
      trackEvent({
        event: "sortOptionClick",
        filter: {
          sortOptions: newSort,
        },
      })
      window.history.replaceState(
        null,
        "",
        `${pathname}?${newSearchParams.toString()}`
      )
    },
    [pathname, searchParams]
  )
  const sortItems: SortItem[] = [
    {
      label: intl.formatMessage({
        defaultMessage: "Distance to city center",
      }),
      value: SortOrder.Distance,
    },
    {
      label: intl.formatMessage({
        defaultMessage: "Name",
      }),
      value: SortOrder.Name,
    },
    {
      label: intl.formatMessage({
        defaultMessage: "Price",
      }),
      value: SortOrder.Price,
    },
    {
      label: intl.formatMessage({
        defaultMessage: "TripAdvisor rating",
      }),
      value: SortOrder.TripAdvisorRating,
    },
  ]

  return (
    <Select
      items={sortItems}
      defaultSelectedKey={searchParams.get("sort") ?? DEFAULT_SORT}
      label={intl.formatMessage({
        defaultMessage: "Sort by",
      })}
      aria-label={intl.formatMessage({
        defaultMessage: "Sort by",
      })}
      name="sort"
      showRadioButton
      discreet={discreet}
      onSelect={onSelect}
    />
  )
}
