"use client"

import { useRef } from "react"
import { useIntl } from "react-intl"

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

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

import DestinationFilterAndSort from "@/components/DestinationFilterAndSort"
import Alert from "@/components/TempDesignSystem/Alert"
import { BackToTopButton } from "@/components/TempDesignSystem/BackToTopButton"
import { useScrollToTop } from "@/hooks/useScrollToTop"

import CityListingItem from "./CityListingItem"
import CityListingSkeleton from "./CityListingSkeleton"

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

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

export default function CityListing() {
  const intl = useIntl()
  const scrollRef = useRef<HTMLElement>(null)
  const { showBackToTop, scrollToTop } = useScrollToTop({
    threshold: 300,
    elementRef: scrollRef,
  })
  const { activeCities, isLoading } = useDestinationDataStore((state) => ({
    activeCities: state.activeCities,
    isLoading: state.isLoading,
  }))

  return isLoading ? (
    <CityListingSkeleton />
  ) : (
    <section className={styles.container} ref={scrollRef}>
      <div className={styles.listHeader}>
        <Typography variant="Title/Subtitle/md">
          <h2>
            {intl.formatMessage(
              {
                defaultMessage:
                  "{count, plural, one {# destination} other {# destinations}}",
              },
              { count: activeCities.length }
            )}
          </h2>
        </Typography>
        <DestinationFilterAndSort listType="city" />
      </div>
      {activeCities.length === 0 ? (
        <Alert
          type={AlertTypeEnum.Info}
          heading={intl.formatMessage({
            defaultMessage: "No matching locations found",
          })}
          text={intl.formatMessage({
            defaultMessage:
              "It looks like no location match your filters. Try adjusting your search to find the perfect stay.",
          })}
        />
      ) : (
        <>
          <ul className={styles.cityList}>
            {activeCities.map((city) => (
              <li key={city.system.uid}>
                <CityListingItem city={city} />
              </li>
            ))}
          </ul>
          {showBackToTop ? (
            <BackToTopButton position="right" onClick={scrollToTop} />
          ) : null}
        </>
      )}
    </section>
  )
}
