"use client";

import Link from "next/link";
import { useState } from "react";
import { useSearchParams } from "next/navigation";
import { Dot } from "lucide-react";

import type { ResponseHotelData } from "@/types/hotel";
import { boardTypeMapping } from "@/components/hotel-details/constants";
import { formatCancellationPolicy, isFreeCancellationOpen } from "@/utils/formatter";
import type { HotelMetaForRequest, HotelRequestSelection } from "@/components/hotel-review/types";
import { nightsBetween } from "@/components/hotel-review/types";
import { encodeHotelSelection } from "@/components/hotel-review/selection-codec";
import { HotelRatePolicyBadge } from "@/components/hotels/HotelPolicyBadge";

interface OfferDetailsBusinessProps {
  offer: ResponseHotelData["rooms"][number]["offers"][number];
  roomName: string;
  hotelMeta: HotelMetaForRequest;
  isLast: boolean;
}

/**
 * LEIS-987/988 — a Business-mode fork of leisure-ui's OfferDetails.
 *
 * Same rate-card markup and cancellation-policy formatting; "Book Now" is
 * the one real difference, and it does NOT send hotelId/offerId for
 * /hotel-request to re-fetch and look up — search-service hands back a
 * different `offer.id` on every call to the hotel-details endpoint, even for
 * byte-identical params, so that lookup would fail unpredictably (confirmed
 * live). Instead the exact selection is built here, where the real data
 * already is, and carried to /hotel-request already-encoded in the URL. See
 * selection-codec.ts.
 *
 * Each rate carries its own travel-policy verdict (LEIS-993). This file used
 * to say it deliberately had none, which was right only while there was no
 * hotel policy to badge against — PRD §7 wants the result visible before the
 * traveller picks a room, and a rate is the thing a nightly limit judges. The
 * badge never hides or disables a rate.
 */
export function OfferDetailsBusiness({ offer, roomName, hotelMeta, isLast }: OfferDetailsBusinessProps) {
  const [isNavigating, setIsNavigating] = useState(false);
  const searchParams = useSearchParams();

  const cancellationPoliciesText =
    offer.cancellationPolicies && offer.cancellationPolicies.length > 0
      ? [formatCancellationPolicy(offer.cancellationPolicies[0], "$")]
      : ["Non-refundable"];

  const bookingHref = (() => {
    const checkIn = searchParams.get("checkinDate") ?? "";
    const checkOut = searchParams.get("checkoutDate") ?? "";
    const firstPolicy = offer.cancellationPolicies?.[0];
    // Same "adults" param app/hotel-details/page.tsx reads server-side
    // (defaulting to "1") — this is the same browser URL, so the
    // client-side useSearchParams() above sees it too. Parsed defensively:
    // a non-numeric or missing value reads as 1 rather than NaN/0.
    const parsedAdults = Number.parseInt(searchParams.get("adults") ?? "1", 10);
    const adults = Number.isFinite(parsedAdults) && parsedAdults > 0 ? parsedAdults : 1;

    const selection: HotelRequestSelection = {
      hotelId: hotelMeta.hotelId,
      property: hotelMeta.property,
      propertyCode: hotelMeta.hotelId,
      imageUrl: hotelMeta.imageUrl,
      starRating: hotelMeta.starRating,
      location: hotelMeta.location,
      fullAddress: hotelMeta.fullAddress,
      countryCode: hotelMeta.countryCode,
      checkIn,
      checkOut,
      checkInTime: hotelMeta.checkInTime,
      checkOutTime: hotelMeta.checkOutTime,
      nights: nightsBetween(checkIn, checkOut),
      adults,
      roomType: roomName,
      rateType: offer.rateName || boardTypeMapping[offer.boardType]?.label || null,
      cancellationTerms: firstPolicy ? formatCancellationPolicy(firstPolicy, "$") : "Non-refundable",
      isRefundable: isFreeCancellationOpen(offer.cancellationPolicies),
      freeCancellationUntil: firstPolicy?.toDate ?? null,
      nightlyRate: offer.pricePerNight?.basePricePerNight ?? 0,
      taxesAndFeesPerNight: offer.pricePerNight?.taxesAndFeesPerNight ?? 0,
      currency: offer.pricePerNight?.currency ?? "USD",
      // Policy facts, carried through so the evaluator can judge the
      // "Apartments and hostels" and "Specific hotels or chains" flags
      // (LEIS-993). Nothing on this card renders them.
      propertyType: hotelMeta.propertyType,
      chainCode: hotelMeta.chainCode,
      offerSnapshot: {
        offerId: offer.id,
        boardType: offer.boardType,
        rateName: offer.rateName ?? null,
        // The real policy, so a later cancellation can work out the refund from the
        // deadline and fee (as leisure.com does) instead of a yes/no flag. Fees are USD.
        cancellationPolicies: offer.cancellationPolicies ?? null,
      },
    };

    const params = new URLSearchParams(searchParams.toString());
    params.set("selection", encodeHotelSelection(selection));
    return `/hotel-request?${params.toString()}`;
  })();

  return (
    <div className="row">
      <div className="col-12">
        <div className={`room-types-list ${isLast ? "" : "border-bottom"} p-4`}>
          <div className="row">
            <div className="col-xxl-8 col-xl-8 col-lg-8 mb-3 mb-lg-0 col-12 px-0">
              <h5
                className="fw-bold smallHeading d-flex align-items-center"
                style={{ textTransform: "none" }}
              >
                {boardTypeMapping[offer.boardType]?.icon}
                {offer.rateName || boardTypeMapping[offer.boardType]?.label}
              </h5>
              <ul className="p-0">
                {cancellationPoliciesText.map((policy, index) => (
                  <li key={index} className="text-md mb-1">
                    <Dot size={30} />
                    {policy}
                  </li>
                ))}
              </ul>
              {offer.room_components && offer.room_components.length > 0 && (
                <ul className="d-flex flex-wrap justify-content-start align-items-center column-gap-2 row-gap-1 p-0 mb-2 amenities-list">
                  {offer.room_components.map((component, index) => (
                    <li key={index} className="text-sm mb-1">
                      {component}
                    </li>
                  ))}
                </ul>
              )}
            </div>
            <div className="col-xxl-4 col-xl-4 col-lg-4 mb-3 mb-lg-0 col-12 px-0">
              {offer.pricePerNight?.originalPricePerNight != null &&
                offer.pricePerNight.originalPricePerNight > (offer.pricePerNight?.basePricePerNight ?? 0) && (
                  <p className="text-sm mb-0 text-muted">
                    <span style={{ textDecoration: "line-through", color: "#FF0000" }}>
                      $ {offer.pricePerNight.originalPricePerNight}
                    </span>
                  </p>
                )}
              <h2
                className="fw-600 subHeading d-flex justify-content-start mb-1"
                style={{ color: "#474646" }}
              >
                $ {offer.pricePerNight?.basePricePerNight}
              </h2>
              <p className="text-md m-0">
                +${offer.pricePerNight?.taxesAndFeesPerNight} Taxes & Fees per night
              </p>
              {/* Per-RATE travel-policy verdict (LEIS-993). This card knows the
                  cancellation terms, so unlike the search result it can judge
                  refundability too — which is why a property badged In policy
                  in the results can still hold a flagged rate. */}
              <HotelRatePolicyBadge
                className="mt-2"
                travelerId={searchParams.get("bookingFor")}
                countryCode={hotelMeta.countryCode || null}
                facts={{
                  nightlyRate: offer.pricePerNight?.basePricePerNight ?? null,
                  taxesPerNight: offer.pricePerNight?.taxesAndFeesPerNight ?? 0,
                  currency: offer.pricePerNight?.currency ?? "USD",
                  starRating: hotelMeta.starRating,
                  nights: nightsBetween(
                    searchParams.get("checkinDate") ?? "",
                    searchParams.get("checkoutDate") ?? ""
                  ),
                  checkIn: searchParams.get("checkinDate"),
                  isRefundable: isFreeCancellationOpen(offer.cancellationPolicies),
                  propertyType: hotelMeta.propertyType,
                  chainCode: hotelMeta.chainCode,
                  propertyCode: hotelMeta.hotelId,
                }}
              />
              <Link href={bookingHref} onClick={() => setIsNavigating(true)}>
                <span className="buttons btnColor-first text-md lh-base my-3 ls-0 py-1 px-3 rounded-2 li">
                  {isNavigating ? (
                    <>
                      <span
                        className="spinner-border spinner-border-sm text-white"
                        role="status"
                        aria-hidden="true"
                      ></span>
                      <span style={{ color: "#fff" }}>&nbsp;Loading...</span>
                    </>
                  ) : (
                    "Book Now"
                  )}
                </span>
              </Link>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
