"use client"

import Link from "next/link"
import { useRouter } from "next/navigation"
import {
  Dialog,
  DialogTrigger,
  Modal,
  ModalOverlay,
} from "react-aria-components"
import { useIntl } from "react-intl"

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

import { useDestinationDataStore } from "@/stores/destination-data"

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

import Alert from "../TempDesignSystem/Alert"
import Filter from "./Filter"
import Sort from "./Sort"

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

import { AlertTypeEnum } from "@/types/enums/alert"

interface HotelFilterAndSortProps {
  listType: "city" | "hotel"
}

export default function DestinationFilterAndSort({
  listType,
}: HotelFilterAndSortProps) {
  const intl = useIntl()
  const router = useRouter()
  const {
    filters,
    sortItems,
    pendingFilters,
    pendingSort,
    defaultSort,
    basePath,
    pendingCount,
    activeFilters,
    clearPendingFilters,
    resetPendingValues,
    setIsLoading,
  } = useDestinationDataStore((state) => ({
    filters: state.allFilters,
    sortItems: state.sortItems,
    pendingFilters: state.pendingFilters,
    pendingSort: state.pendingSort,
    basePath: state.basePathnameWithoutFilters,
    defaultSort: state.defaultSort,
    pendingCount:
      listType === "city" ? state.pendingCityCount : state.pendingHotelCount,
    activeFilters: state.activeFilters,
    clearPendingFilters: state.actions.clearPendingFilters,
    resetPendingValues: state.actions.resetPendingValues,
    setIsLoading: state.actions.setIsLoading,
  }))
  const { facilityFilters, surroundingsFilters } = filters
  const alertHeading =
    listType === "city"
      ? intl.formatMessage({
          defaultMessage: "No matching locations found",
        })
      : intl.formatMessage({
          defaultMessage: "No matching hotels found",
        })

  const alertText =
    listType === "city"
      ? intl.formatMessage({
          defaultMessage:
            "It looks like no location match your filters. Try adjusting your search to find the perfect stay.",
        })
      : intl.formatMessage({
          defaultMessage:
            "It looks like no hotels match your filters. Try adjusting your search to find the perfect stay.",
        })

  function submitAndClose(close: () => void) {
    setIsLoading(true)
    const sort = pendingSort
    const filters = pendingFilters
    const parsedUrl = new URL(window.location.href)
    const searchParams = parsedUrl.searchParams
    if (sort === defaultSort && searchParams.has("sort")) {
      searchParams.delete("sort")
    } else if (sort !== defaultSort) {
      searchParams.set("sort", sort)
    }
    const [firstFilter, ...remainingFilters] = filters

    parsedUrl.pathname = basePath
    if (firstFilter) {
      parsedUrl.pathname += `/${firstFilter}`
    }
    if (remainingFilters.length > 0) {
      parsedUrl.hash = `#${remainingFilters.join("&")}`
    } else {
      parsedUrl.hash = ""
    }

    router.push(parsedUrl.toString(), { scroll: false })
    close()
  }

  function handleClose(isOpen: boolean) {
    if (isOpen) {
      resetPendingValues()
    }
  }

  return (
    <>
      <DialogTrigger onOpenChange={handleClose}>
        <div className={styles.buttonWrapper}>
          <Button intent="text" theme="base" variant="icon">
            <MaterialIcon icon="filter_alt" color="CurrentColor" />
            {intl.formatMessage({
              defaultMessage: "Filter and sort",
            })}
          </Button>
          {activeFilters.length > 0 && (
            <Footnote className={styles.badge} asChild>
              <span>{activeFilters.length}</span>
            </Footnote>
          )}
        </div>
        <ModalOverlay isDismissable className={styles.overlay}>
          <Modal>
            <Dialog
              className={styles.dialog}
              aria-label={intl.formatMessage({
                defaultMessage: "Filter and sort",
              })}
            >
              {({ close }) => (
                <>
                  <header className={styles.header}>
                    <Subtitle
                      type="two"
                      textAlign="center"
                      className={styles.title}
                      asChild
                    >
                      <h3>
                        {intl.formatMessage({
                          defaultMessage: "Filter and sort",
                        })}
                      </h3>
                    </Subtitle>
                    <button
                      onClick={close}
                      type="button"
                      className={styles.close}
                    >
                      <MaterialIcon icon="close" />
                    </button>
                  </header>
                  <div className={styles.content}>
                    <Sort sortItems={sortItems} />
                    <Divider color="subtle" className={styles.divider} />
                    <Filter filters={filters} />
                  </div>
                  {pendingCount === 0 && (
                    <div className={styles.alertWrapper}>
                      <Alert
                        type={AlertTypeEnum.Warning}
                        heading={alertHeading}
                        text={alertText}
                        ariaRole="status"
                      />
                    </div>
                  )}
                  <footer className={styles.footer}>
                    <Button
                      onClick={clearPendingFilters}
                      intent="text"
                      size="medium"
                      theme="base"
                    >
                      {intl.formatMessage({
                        defaultMessage: "Clear all filters",
                      })}
                    </Button>
                    <Button
                      intent="primary"
                      size="large"
                      theme="base"
                      disabled={pendingCount === 0}
                      onClick={() => submitAndClose(close)}
                    >
                      {intl.formatMessage(
                        {
                          defaultMessage: "See results ({ count })",
                        },
                        { count: pendingCount }
                      )}
                    </Button>
                  </footer>
                </>
              )}
            </Dialog>
          </Modal>
        </ModalOverlay>
      </DialogTrigger>

      {/* This section is added to the DOM for SEO purposes. The filters are linkable and should be indexable */}
      <nav className="sr-only">
        <ul>
          {facilityFilters.map((filter) => (
            <li key={`filter-${filter.slug}`}>
              <Link href={`${basePath}/${filter.slug}`}>{filter.name}</Link>
            </li>
          ))}
          {surroundingsFilters.map((filter) => (
            <li key={`filter-${filter.slug}`}>
              <Link href={`${basePath}/${filter.slug}`}>{filter.name}</Link>
            </li>
          ))}
        </ul>
      </nav>
    </>
  )
}
