"use client"

import {
  usePathname,
  useSearchParams,
} from "next/dist/client/components/navigation"
import { useCallback, useState } from "react"
import {
  Dialog as AriaDialog,
  DialogTrigger,
  Modal,
  ModalOverlay,
} from "react-aria-components"
import { useIntl } from "react-intl"

import { MaterialIcon } from "@scandic-hotels/design-system/Icons/MaterialIcon"

import { useHotelFilterStore } from "@/stores/hotel-filters"

import Button from "@/components/TempDesignSystem/Button"
import Divider from "@/components/TempDesignSystem/Divider"
import Select from "@/components/TempDesignSystem/Select"
import Footnote from "@/components/TempDesignSystem/Text/Footnote"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"
import useInitializeFiltersFromUrl from "@/hooks/useInitializeFiltersFromUrl"

import HotelFilter from "../HotelFilter"
import { DEFAULT_SORT } from "../HotelSorter"

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

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

export default function FilterAndSortModal({
  filters,
  setShowSkeleton,
}: FilterAndSortModalProps) {
  const intl = useIntl()
  useInitializeFiltersFromUrl()
  const searchParams = useSearchParams()
  const pathname = usePathname()
  const resultCount = useHotelFilterStore((state) => state.resultCount)
  const setFilters = useHotelFilterStore((state) => state.setFilters)
  const activeFilters = useHotelFilterStore((state) => state.activeFilters)
  const [sort, setSort] = useState(searchParams.get("sort") ?? DEFAULT_SORT)

  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,
    },
  ]

  const handleSortSelect = useCallback((value: string | number) => {
    setSort(value.toString())
  }, [])

  const handleApplyFiltersAndSorting = useCallback(
    (close: () => void) => {
      if (setShowSkeleton) {
        setShowSkeleton(true)
      }
      if (sort === searchParams.get("sort")) {
        close()
      }

      const newSearchParams = new URLSearchParams(searchParams)
      newSearchParams.set("sort", sort)

      window.history.replaceState(
        null,
        "",
        `${pathname}?${newSearchParams.toString()}`
      )
      close()
      if (setShowSkeleton) {
        setTimeout(() => {
          setShowSkeleton(false)
        }, 500)
      }
    },
    [pathname, searchParams, sort, setShowSkeleton]
  )

  return (
    <>
      <DialogTrigger>
        <Button intent="secondary" size="small" theme="base" variant="icon">
          <MaterialIcon icon="filter_alt" color="Icon/Intense" />
          {intl.formatMessage({
            defaultMessage: "Filter and sort",
          })}
          {activeFilters.length > 0 && (
            <Footnote className={styles.badge}>{activeFilters.length}</Footnote>
          )}
        </Button>
        <ModalOverlay className={styles.overlay} isDismissable>
          <Modal className={styles.modal}>
            <AriaDialog role="alertdialog" className={styles.content}>
              {({ close }) => (
                <>
                  <header className={styles.header}>
                    <button
                      onClick={close}
                      type="button"
                      className={styles.close}
                    >
                      <MaterialIcon icon="close" />
                    </button>
                    <Subtitle
                      type="two"
                      textAlign="center"
                      className={styles.title}
                    >
                      {intl.formatMessage({
                        defaultMessage: "Filter and sort",
                      })}
                    </Subtitle>
                  </header>
                  <div className={styles.sorter}>
                    <Select
                      items={sortItems}
                      defaultSelectedKey={
                        searchParams.get("sort") ?? DEFAULT_SORT
                      }
                      label={intl.formatMessage({
                        defaultMessage: "Sort by",
                      })}
                      name="sort"
                      showRadioButton
                      onSelect={handleSortSelect}
                    />
                  </div>
                  <div className={styles.divider}>
                    <Divider color="subtle" />
                  </div>
                  <div className={styles.filters}>
                    <HotelFilter filters={filters} />
                  </div>
                  <footer className={styles.footer}>
                    <Button
                      intent="primary"
                      size="medium"
                      theme="base"
                      onClick={() => handleApplyFiltersAndSorting(close)}
                    >
                      {intl.formatMessage(
                        {
                          defaultMessage: "See results ({ count })",
                        },
                        {
                          count: resultCount,
                        }
                      )}
                    </Button>
                    <Button
                      onClick={() => setFilters([])}
                      intent="text"
                      size="medium"
                      theme="base"
                    >
                      {intl.formatMessage({
                        defaultMessage: "Clear all filters",
                      })}
                    </Button>
                  </footer>
                </>
              )}
            </AriaDialog>
          </Modal>
        </ModalOverlay>
      </DialogTrigger>
    </>
  )
}
