import { differenceInCalendarDays, format, isWeekend } from "date-fns"
import { Suspense } from "react"

import {
  selectHotel,
  selectHotelMap,
} from "@/constants/routes/hotelReservation"

import {
  fetchAvailableHotels,
  getFiltersFromHotels,
} from "@/app/[lang]/(live)/(public)/hotelreservation/(standard)/select-hotel/utils"
import { ChevronRightIcon } from "@/components/Icons"
import StaticMap from "@/components/Maps/StaticMap"
import Alert from "@/components/TempDesignSystem/Alert"
import Breadcrumbs from "@/components/TempDesignSystem/Breadcrumbs"
import Button from "@/components/TempDesignSystem/Button"
import Link from "@/components/TempDesignSystem/Link"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"
import TrackingSDK from "@/components/TrackingSDK"
import { getIntl } from "@/i18n"
import { safeTry } from "@/utils/safeTry"

import HotelCardListing from "../HotelCardListing"
import HotelCount from "./HotelCount"
import HotelFilter from "./HotelFilter"
import HotelSorter from "./HotelSorter"
import MobileMapButtonContainer from "./MobileMapButtonContainer"

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

import { ChildBedMapEnum } from "@/types/components/bookingWidget/enums"
import type { HotelData } from "@/types/components/hotelReservation/selectHotel/hotelCardListingProps"
import type { SelectHotelProps } from "@/types/components/hotelReservation/selectHotel/selectHotel"
import {
  TrackingChannelEnum,
  TrackingSDKHotelInfo,
  TrackingSDKPageData,
} from "@/types/components/tracking"
import { AlertTypeEnum } from "@/types/enums/alert"
import type { Lang } from "@/constants/languages"

export default async function SelectHotel({
  city,
  params,
  reservationParams,
}: SelectHotelProps) {
  const {
    selectHotelParams,
    searchParams,
    adultsParams,
    childrenParams,
    child,
  } = reservationParams

  const intl = await getIntl()

  const hotelsPromise = safeTry(
    fetchAvailableHotels({
      cityId: city.id,
      roomStayStartDate: searchParams.fromDate,
      roomStayEndDate: searchParams.toDate,
      adults: adultsParams,
      children: childrenParams?.toString(),
    })
  )

  const [hotels] = await hotelsPromise

  const arrivalDate = new Date(searchParams.fromDate)
  const departureDate = new Date(searchParams.toDate)

  const isCityWithCountry = (city: any): city is { country: string } =>
    "country" in city

  const validHotels =
    hotels?.filter((hotel): hotel is HotelData => hotel !== null) || []

  const filterList = getFiltersFromHotels(validHotels)
  const breadcrumbs = [
    {
      title: intl.formatMessage({ id: "Home" }),
      href: `/${params.lang}`,
      uid: "home-page",
    },
    {
      title: intl.formatMessage({ id: "Hotel reservation" }),
      href: `/${params.lang}/hotelreservation`,
      uid: "hotel-reservation",
    },
    {
      title: intl.formatMessage({ id: "Select hotel" }),
      href: `${selectHotel(params.lang)}/?${selectHotelParams}`,
      uid: "select-hotel",
    },
    {
      title: city.name,
      uid: city.id,
    },
  ]

  const isAllUnavailable = hotels?.every((hotel) => hotel.price === undefined)

  const pageTrackingData: TrackingSDKPageData = {
    pageId: "select-hotel",
    domainLanguage: params.lang as Lang,
    channel: TrackingChannelEnum["hotelreservation"],
    pageName: "hotelreservation|select-hotel",
    siteSections: "hotelreservation|select-hotel",
    pageType: "bookinghotelspage",
    siteVersion: "new-web",
  }

  const hotelsTrackingData: TrackingSDKHotelInfo = {
    availableResults: validHotels.length,
    searchTerm: searchParams.city,
    arrivalDate: format(arrivalDate, "yyyy-MM-dd"),
    departureDate: format(departureDate, "yyyy-MM-dd"),
    noOfAdults: adultsParams,
    noOfChildren: child?.length,
    ageOfChildren: child?.map((c) => c.age).join(","),
    childBedPreference: child?.map((c) => ChildBedMapEnum[c.bed]).join("|"),
    noOfRooms: 1, // // TODO: Handle multiple rooms
    duration: differenceInCalendarDays(departureDate, arrivalDate),
    leadTime: differenceInCalendarDays(arrivalDate, new Date()),
    searchType: "destination",
    bookingTypeofDay: isWeekend(arrivalDate) ? "weekend" : "weekday",
    country: validHotels?.[0].hotelData.address.country,
    region: validHotels?.[0].hotelData.address.city,
  }

  return (
    <>
      <header className={styles.header}>
        <Breadcrumbs breadcrumbs={breadcrumbs} />
        <div className={styles.title}>
          <div className={styles.cityInformation}>
            <Subtitle>{city.name}</Subtitle>
            <HotelCount />
          </div>
          <div className={styles.sorter}>
            <HotelSorter discreet />
          </div>
        </div>
        <MobileMapButtonContainer filters={filterList} />
      </header>
      <main className={styles.main}>
        <div className={styles.sideBar}>
          {hotels && hotels.length > 0 ? ( // TODO: Temp fix until API returns hotels that are not available
            <Link
              className={styles.link}
              color="burgundy"
              href={selectHotelMap(params.lang)}
              keepSearchParams
            >
              <div className={styles.mapContainer}>
                <StaticMap
                  city={searchParams.city}
                  country={isCityWithCountry(city) ? city.country : undefined}
                  width={340}
                  height={180}
                  zoomLevel={11}
                  mapType="roadmap"
                  altText={`Map of ${searchParams.city} city center`}
                />
                <Button wrapping size="medium" intent="text" theme="base">
                  {intl.formatMessage({ id: "See map" })}
                  <ChevronRightIcon
                    color="baseButtonTextOnFillNormal"
                    width={20}
                    height={20}
                  />
                </Button>
              </div>
            </Link>
          ) : (
            <div className={styles.mapContainer}>
              <StaticMap
                city={searchParams.city}
                width={340}
                height={180}
                zoomLevel={11}
                mapType="roadmap"
                altText={`Map of ${searchParams.city} city center`}
              />
            </div>
          )}
          <HotelFilter filters={filterList} className={styles.filter} />
        </div>
        <div className={styles.hotelList}>
          {isAllUnavailable && (
            <Alert
              type={AlertTypeEnum.Info}
              heading={intl.formatMessage({ id: "No availability" })}
              text={intl.formatMessage({
                id: "There are no rooms available that match your request.",
              })}
            />
          )}
          <HotelCardListing hotelData={validHotels} />
        </div>
      </main>
      <Suspense fallback={null}>
        <TrackingSDK
          pageData={pageTrackingData}
          hotelInfo={hotelsTrackingData}
        />
      </Suspense>
    </>
  )
}
