"use client"

import { useIntl } from "react-intl"

import { dt } from "@/lib/dt"
import { trpc } from "@/lib/trpc/client"
import { useEnterDetailsStore } from "@/stores/enter-details"

import { ArrowRightIcon } from "@/components/Icons"
import LoadingSpinner from "@/components/LoadingSpinner"
import Divider from "@/components/TempDesignSystem/Divider"
import Link from "@/components/TempDesignSystem/Link"
import Body from "@/components/TempDesignSystem/Text/Body"
import Caption from "@/components/TempDesignSystem/Text/Caption"
import Subtitle from "@/components/TempDesignSystem/Text/Subtitle"
import useLang from "@/hooks/useLang"
import { formatNumber } from "@/utils/format"

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

import { RoomsData } from "@/types/components/hotelReservation/enterDetails/bookingData"

export default function Summary({ isMember }: { isMember: boolean }) {
  const intl = useIntl()
  const lang = useLang()
  const { fromDate, toDate, rooms, hotel, bedType, breakfast } =
    useEnterDetailsStore((state) => ({
      fromDate: state.roomData.fromdate,
      toDate: state.roomData.todate,
      rooms: state.roomData.room,
      hotel: state.roomData.hotel,
      bedType: state.userData.bedType,
      breakfast: state.userData.breakfast,
    }))

  const totalAdults = rooms.reduce((total, room) => total + room.adults, 0)

  const {
    data: availabilityData,
    isLoading,
    error,
  } = trpc.hotel.availability.rooms.useQuery(
    {
      hotelId: parseInt(hotel),
      adults: totalAdults,
      roomStayStartDate: dt(fromDate).format("YYYY-MM-DD"),
      roomStayEndDate: dt(toDate).format("YYYY-MM-DD"),
    },
    { enabled: !!hotel && !!fromDate && !!toDate }
  )

  const diff = dt(toDate).diff(fromDate, "days")

  const nights = intl.formatMessage(
    { id: "booking.nights" },
    { totalNights: diff }
  )

  if (isLoading) {
    return <LoadingSpinner />
  }
  const populatedRooms = rooms
    .map((room) => {
      const chosenRoom = availabilityData?.roomConfigurations.find(
        (availRoom) => room.roomtypecode === availRoom.roomTypeCode
      )
      const cancellationText = availabilityData?.rateDefinitions.find(
        (rate) => rate.rateCode === room.ratecode
      )?.cancellationText

      if (chosenRoom) {
        const memberPrice = chosenRoom.products.find(
          (rate) => rate.productType.member?.rateCode === room.ratecode
        )?.productType.member?.localPrice.pricePerStay
        const publicPrice = chosenRoom.products.find(
          (rate) => rate.productType.public?.rateCode === room.ratecode
        )?.productType.public?.localPrice.pricePerStay

        return {
          roomType: chosenRoom.roomType,
          memberPrice: memberPrice && formatNumber(parseInt(memberPrice)),
          publicPrice: publicPrice && formatNumber(parseInt(publicPrice)),
          adults: room.adults,
          children: room.child,
          cancellationText,
        }
      }
    })
    .filter((room): room is RoomsData => room !== undefined)

  return (
    <section className={styles.summary}>
      <header>
        <Subtitle type="two">{intl.formatMessage({ id: "Summary" })}</Subtitle>
        <Body className={styles.date} color="baseTextMediumContrast">
          {dt(fromDate).locale(lang).format("ddd, D MMM")}
          <ArrowRightIcon color="peach80" height={15} width={15} />
          {dt(toDate).locale(lang).format("ddd, D MMM")} ({nights})
        </Body>
      </header>
      <Divider color="primaryLightSubtle" />
      <div className={styles.addOns}>
        {populatedRooms.map((room, idx) => (
          <RoomBreakdown key={idx} room={room} isMember={isMember} />
        ))}

        {bedType ? (
          <div className={styles.entry}>
            <Body color="textHighContrast">{bedType}</Body>
            <Caption color="red">
              {intl.formatMessage(
                { id: "{amount} {currency}" },
                { amount: "0", currency: "SEK" }
              )}
            </Caption>
          </div>
        ) : null}
        {breakfast ? (
          <div className={styles.entry}>
            <Body color="textHighContrast">{breakfast}</Body>
            <Caption color="red">
              {intl.formatMessage(
                { id: "{amount} {currency}" },
                { amount: "0", currency: "SEK" }
              )}
            </Caption>
          </div>
        ) : null}
      </div>
      <Divider color="primaryLightSubtle" />
      <div className={styles.total}>
        <div className={styles.entry}>
          <Body textTransform="bold">
            {intl.formatMessage({ id: "Total price (incl VAT)" })}
          </Body>
          <Body textTransform="bold">
            {intl.formatMessage(
              { id: "{amount} {currency}" },
              { amount: "4686", currency: "SEK" }
            )}
          </Body>
        </div>
        <div className={styles.entry}>
          <Caption color="uiTextMediumContrast">
            {intl.formatMessage({ id: "Approx." })}
          </Caption>
          <Caption color="uiTextMediumContrast">
            {intl.formatMessage(
              { id: "{amount} {currency}" },
              { amount: "455", currency: "EUR" }
            )}
          </Caption>
        </div>
      </div>
    </section>
  )
}

function RoomBreakdown({
  room,
  isMember,
}: {
  room: RoomsData
  isMember: boolean
}) {
  const intl = useIntl()

  let color: "uiTextHighContrast" | "red" = "uiTextHighContrast"
  let price = room.publicPrice
  if (isMember) {
    color = "red"
    price = room.memberPrice
  }

  return (
    <div>
      <div className={styles.entry}>
        <Body color="textHighContrast">{room.roomType}</Body>
        <Caption color={color}>
          {intl.formatMessage(
            { id: "{amount} {currency}" },
            { amount: price, currency: "SEK" }
          )}
        </Caption>
      </div>
      <Caption color="uiTextMediumContrast">
        {intl.formatMessage(
          { id: "booking.adults" },
          { totalAdults: room.adults }
        )}
      </Caption>
      {room.children?.length ? (
        <Caption color="uiTextMediumContrast">
          {intl.formatMessage(
            { id: "booking.children" },
            { totalChildren: room.children.length }
          )}
        </Caption>
      ) : null}
      <Caption color="uiTextMediumContrast">{room.cancellationText}</Caption>
      <Link color="burgundy" href="#" variant="underscored" size="small">
        {intl.formatMessage({ id: "Rate details" })}
      </Link>
    </div>
  )
}
