"use client"

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

import {
  TrackingChannelEnum,
  type TrackingSDKHotelInfo,
  type TrackingSDKPageData,
} from "@scandic-hotels/tracking/types"
import { SEARCH_TYPE_REDEMPTION } from "@scandic-hotels/trpc/constants/booking"

import { trackEvent } from "./base"

import type { Lang } from "@scandic-hotels/common/constants/language"

type NoAvailabilityTrackingProps = {
  lang: Lang
  shouldTrackNoAvailability: boolean
  hotelsTrackingData: TrackingSDKHotelInfo
  pageTrackingData: TrackingSDKPageData
}

export function NoAvailabilityTracking({
  lang,
  shouldTrackNoAvailability,
  hotelsTrackingData,
  pageTrackingData,
}: NoAvailabilityTrackingProps) {
  useEffect(() => {
    if (!shouldTrackNoAvailability) {
      return
    }
    const {
      searchTerm,
      searchType,
      hotelID,
      leadTime,
      noOfRooms,
      bookingCode,
      rewardNight,
      bookingTypeofDay,
      duration,
      specialRoomType,
    } = hotelsTrackingData

    trackEvent({
      event: "noRoomsAvailable",
      hotelInfo: {
        searchTerm,
        searchType,
        noRoomsAvailable: "yes",
        hotelID,
        leadTime,
        noOfRooms,
        bookingCode,
        rewardNight,
        bookingTypeofDay,
        duration,
        specialRoomType,
      },
      pageInfo: pageTrackingData,
    })
  }, [lang, hotelsTrackingData, pageTrackingData])

  return null
}

type TrackNoAvailabilityParams = {
  specialRoomType: string
  fromDate: string
  toDate: string
  hotelId: string
  noOfRooms: number
  searchType?: string
  bookingCode?: string
  searchTerm: string
  pageId: string
  pageName: string
  pageType: string
  siteSections: string
  lang: Lang
}

export function trackNoAvailability({
  specialRoomType,
  lang,
  fromDate,
  toDate,
  hotelId,
  noOfRooms,
  searchType,
  bookingCode,
  searchTerm,
  pageId,
  pageName,
  pageType,
  siteSections,
}: TrackNoAvailabilityParams) {
  const arrivalDate = new Date(fromDate)
  const departureDate = new Date(toDate)

  trackEvent({
    event: "noRoomsAvailable",
    hotelInfo: {
      searchTerm,
      searchType,
      noRoomsAvailable: "yes",
      hotelId,
      leadTime: differenceInCalendarDays(arrivalDate, new Date()),
      noOfRooms,
      bookingCode: bookingCode ?? "n/a",
      rewardNight: searchType === SEARCH_TYPE_REDEMPTION ? "yes" : "no",
      bookingTypeofDay: isWeekend(arrivalDate) ? "weekend" : "weekday",
      duration: differenceInCalendarDays(departureDate, arrivalDate),
      specialRoomType,
    },
    pageInfo: {
      channel: TrackingChannelEnum.hotelreservation,
      domain: "www.scandichotels.com",
      domainLanguage: lang,
      pageId,
      pageName,
      pageType,
      siteSections,
    },
  })
}
