"use client"

import { useRouter, useSearchParams } from "next/navigation"
import { useState, useTransition } from "react"

import { ErrorBoundary } from "@/components/ErrorBoundary/ErrorBoundary"
import { useSelectRateContext } from "@/contexts/SelectRate/SelectRateContext"

import { DesktopSummary } from "./DesktopSummary"
import { MobileSummary } from "./MobileSummary"

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

export function RateSummary() {
  return (
    // eslint-disable-next-line formatjs/no-literal-string-in-jsx
    <ErrorBoundary fallback={<div>Unable to render summary</div>}>
      <InnerRateSummary />
    </ErrorBoundary>
  )
}

function InnerRateSummary() {
  const { selectedRates, input } = useSelectRateContext()

  const [isSubmitting, setIsSubmitting] = useState(false)
  const router = useRouter()
  const params = useSearchParams()
  const [_, startTransition] = useTransition()

  if (selectedRates.state === "NONE_SELECTED") {
    return null
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setIsSubmitting(true)
    startTransition(() => {
      router.push(`details?${params}`)
    })
  }

  const totalPriceToShow = selectedRates.totalPrice

  if (
    !totalPriceToShow ||
    !selectedRates.rates.some((room) => room?.isSelected ?? false)
  ) {
    return null
  }

  // attribute data-footer-spacing used to add spacing
  // beneath footer to be able to show entire footer upon
  // scrolling down to the bottom of the page
  return (
    <form
      data-footer-spacing
      action={`details?${params}`}
      method="GET"
      onSubmit={handleSubmit}
    >
      <div className={styles.summary}>
        <div className={styles.content}>
          {/* eslint-disable-next-line formatjs/no-literal-string-in-jsx */}
          <ErrorBoundary fallback={<div>Unable to render desktop summary</div>}>
            <DesktopSummary
              isSubmitting={isSubmitting}
              input={input}
              selectedRates={selectedRates}
              bookingCode={input.data?.booking.bookingCode || ""}
            />
          </ErrorBoundary>
        </div>
        <div className={styles.mobileSummary}>
          {/* eslint-disable-next-line formatjs/no-literal-string-in-jsx */}
          <ErrorBoundary fallback={<div>Unable to render mobile summary</div>}>
            <MobileSummary />
          </ErrorBoundary>
        </div>
      </div>
    </form>
  )
}
