import Image from "next/image";

import type { HotelRequestSelection } from "./types";
import { formatDate } from "@/services/employee-requests/format";
import { assetPath } from "@/utils/assets";

/** "Mon 12 Oct 2026" — matches the reference "Review your Booking" page's
 *  own check-in/out date format, which `formatDate` (short month, no
 *  weekday) does not. */
function formatFullDate(iso: string | null | undefined): string {
  if (!iso) return "";
  const date = new Date(`${iso.slice(0, 10)}T00:00:00`);
  if (Number.isNaN(date.getTime())) return "";
  const weekday = date.toLocaleDateString("en-US", { weekday: "short" });
  const day = date.getDate();
  const month = date.toLocaleDateString("en-US", { month: "short" });
  const year = date.getFullYear();
  return `${weekday} ${day} ${month} ${year}`;
}

function StarIcon() {
  return (
    <svg
      className="iconSize-15 stars-svg active"
      xmlns="http://www.w3.org/2000/svg"
      version="1.1"
      viewBox="0 0 105 100"
      aria-hidden
    >
      <path
        className="star"
        d="M57.8,5.9l12.1,24.5,27.1,3.9c4.9.8,6.8,6.7,3.3,10.2l-19.6,19.1,4.7,26.9c.9,4.9-4.3,8.6-8.6,6.3l-24.2-12.7-24.2,12.7c-4.4,2.3-9.4-1.4-8.7-6.3l4.7-26.9L4.8,44.6c-3.5-3.4-1.6-9.4,3.3-10.2l27.1-3.9,12.1-24.5c2.1-4.4,8.4-4.4,10.7,0h-.1Z"
      />
    </svg>
  );
}

function CheckIcon() {
  return (
    <svg
      clipRule="evenodd"
      fillRule="evenodd"
      viewBox="0 0 21.0002 21.0002"
      xmlns="http://www.w3.org/2000/svg"
      className="me-2 iconSize-15"
      aria-hidden
    >
      <path
        d="m6.33787 15.5981c4.20248-4.20248 7.61374-7.61391 11.8162-11.8162.0711-.0711.18751-.07077.25828 0l.32657.32641.00314.00331.70259.70259.00331.00331.32657.32657c.07077.07077.0711.18702 0 .25812-4.20248 4.20248-7.61374 7.61391-11.8162 11.8164-.0711.07094-.18702.07094-.25812 0l-.32657-.32657-.00331-.00331-.70259-.70259-.00331-.00331-.32657-.32657c-.0711-.0711-.0711-.18702 0-.25812l.00001-.00001z"
        fill="#00ba00"
      />
    </svg>
  );
}

/**
 * LEIS-988 — the Review-your-trip property/room/refund card, ported from
 * leisure-ui's BookingSummaryServer so the Business flow reads the same way
 * the real "Review your Booking" page does (the user's own reference).
 *
 * What was left out on purpose, because HotelRequestSelection has no data
 * for it: room inclusions (a bulleted amenity list BookingSummaryServer
 * reads off a priced-offer response this flow never fetches), partial-refund
 * percentages (search-service's cancellationPolicies carry one flat fee, not
 * a tiered schedule — so the slider is a plain two-state refundable /
 * non-refundable bar, which is what the ported markup already renders
 * regardless of the real percentage: both halves are fixed at 50% width in
 * the source component too). Check-in/out TIMES come from `selection`
 * already resolved — the property's own checkInOutPolicies when the
 * supplier sent one, else the standard hotel default (see
 * checkInTimeOrDefault/checkOutTimeOrDefault in types.ts), matching the
 * leisure-ui reference.
 */
export function BookingSummaryHotel({ selection }: { selection: HotelRequestSelection }) {
  const image = selection.imageUrl || assetPath("/assets/img/no-image.png");
  const stars = Math.min(5, Math.max(0, Math.round(selection.starRating ?? 0)));
  const freeCancelUntil = selection.freeCancellationUntil
    ? formatDate(selection.freeCancellationUntil)
    : null;
  const checkInLabel = formatFullDate(selection.checkIn);
  const checkOutLabel = formatFullDate(selection.checkOut);

  return (
    <div className="bgColor-white booking-summary shadow-sm pt-4 rounded-3">
      {/* `align-items-start` is the fix, not decoration: Bootstrap's default
       *  `align-items: stretch` was forcing the image column to the TEXT
       *  column's height, which for a one-line name is far shorter than the
       *  image's own `minHeight: 150` — the image overflowed its stretched
       *  column and visibly bled into the check-in/out card below. Starting
       *  both columns at their own natural height, plus an explicit `mb-4`
       *  instead of relying on the next block's `mt-3` alone, fixes it. */}
      <div className="row px-3 pb-3 align-items-start mb-4">
        <div className="col-xxl-10 col-xl-10 col-lg-10 col-md-9 col-sm-12 col-12">
          <h2 className="subHeading fw-semibold h3">{selection.property}</h2>
          {stars > 0 && (
            <div className="rating-stars">
              {Array.from({ length: stars }).map((_, i) => (
                <StarIcon key={i} />
              ))}
            </div>
          )}
          {selection.fullAddress && (
            <p className="mt-1 color-text-grey">
              <small>{selection.fullAddress}</small>
            </p>
          )}
        </div>
        <div className="col-xxl-2 col-xl-2 col-lg-2 col-md-3 col-sm-12 col-12 mt-3 mt-md-0">
          <div
            className="booking-summary-image-frame position-relative overflow-hidden rounded-2 w-100"
            style={{ aspectRatio: "4 / 3", minHeight: 150, maxHeight: 150 }}
          >
            <Image
              src={image}
              className="booking-img img-fluid rounded-2"
              alt={selection.property}
              width={200}
              height={150}
              priority
              sizes="(max-width: 768px) 100vw, 200px"
              style={{ width: "100%", height: "100%", objectFit: "cover" }}
            />
          </div>
        </div>
      </div>

      <div className="card rounded-0 border-0 w-100">
        <div className="card-header border-top rounded-0 lightBg py-1 px-2 mb-2">
          {/* No `align-items-center` here: that overrides Bootstrap's
           *  default `align-items: stretch` on a `.row`, which is exactly
           *  what makes the col-xxl-5 column BELOW actually as tall as its
           *  taller check-in/out sibling — without stretch, col-xxl-5 is
           *  only ever as tall as its own one line of content, so its own
           *  `d-flex align-items-center` has no real height to center
           *  within (its `h-100` was 100% of that same one-line height,
           *  i.e. a no-op) — confirmed this was the actual cause, not the
           *  inner flex wrapper, which was already correct. */}
          <div className="row">
            <div className="col-xxl-7 col-xl-7 col-lg-7 col-md-12 col-sm-12 col-12 d-flex align-items-center">
              <div className="row w-100 align-items-center">
                <div className="col-xxl-4 col-xl-4 col-lg-4 col-md-4 col-sm-12 col-12 booking-flight-time text-center">
                  <small className="text-uppercase d-block">Check in</small>
                  <p className="mb-0">
                    <small>{checkInLabel}</small>
                  </p>
                  <p className="time mb-0 text-sm">{selection.checkInTime}</p>
                </div>
                <div className="col-xxl-4 col-xl-4 col-lg-4 col-md-4 col-sm-12 col-12 text-center">
                  <div className="flight-layover text-center my-4">
                    <span className="lightBg">
                      {selection.nights} Night{selection.nights === 1 ? "" : "s"}
                    </span>
                  </div>
                </div>
                <div className="col-xxl-4 col-xl-4 col-lg-4 col-md-4 col-sm-12 col-12 booking-flight-time text-center">
                  <small className="text-uppercase d-block">Check out</small>
                  <p className="mb-0">
                    <small>{checkOutLabel}</small>
                  </p>
                  <p className="time mb-0 text-sm">{selection.checkOutTime}</p>
                </div>
              </div>
            </div>
            {/* Now that the parent row keeps its default `stretch` (see
             *  above), this column is genuinely as tall as its taller
             *  check-in/out sibling — `d-flex align-items-center` centers
             *  its one line of content within that real height. */}
            <div className="col-xxl-5 col-xl-5 col-lg-5 col-md-12 col-sm-12 col-12 d-flex align-items-center">
              <p className="m-0 text-lg-start text-center">
                <span className="fw-semibold ps-1">{selection.nights}</span> Night
                {selection.nights === 1 ? "" : "s"} |{" "}
                <span className="fw-semibold ps-1">{selection.adults ?? 1}</span> Adult
                {(selection.adults ?? 1) === 1 ? "" : "s"} | <span className="fw-semibold ps-1">1</span> Room
              </p>
            </div>
          </div>
        </div>

        <div className="card-body p-2 px-3 rounded-3">
          <h3 className="smallHeading">{selection.roomType}</h3>
          {selection.rateType && <small className="d-block mb-2">{selection.rateType}</small>}

          {selection.isRefundable ? (
            <p className="mb-2">
              <small className="text-success">
                <CheckIcon />
                {freeCancelUntil ? `Free Cancellation before ${freeCancelUntil}` : "Free Cancellation"}
              </small>
            </p>
          ) : (
            <p className="mb-2">
              <small className="text-danger">{selection.cancellationTerms}</small>
            </p>
          )}

          <div className="row">
            <div className="col-xxl-5 col-xl-5 col-lg-8 col-md-12 col-sm-12 col-12">
              <div className="refundDetails" style={{ minHeight: 72 }}>
                <div className="refundTopDetail col-length-2">
                  <div className="refundTopDetail--col refundable" style={{ width: "50%" }}>
                    <div className="refundTopDetail--oval" />
                    <div className="refundTopDetail--colText">100% Refund</div>
                  </div>
                  <div className="refundTopDetail--col nonrefundable" style={{ width: "50%" }}>
                    <div className="refundTopDetail--colText">Non Refundable</div>
                    <span className="refundTopDetail--oval" />
                  </div>
                </div>
                <div className="refundBottomDetail col-length-2">
                  <div className="fcTimelineDhLeft">
                    <div>
                      <div className="refundBottomDetail--colText">NOW</div>
                    </div>
                    {freeCancelUntil && (
                      <div className="fcTimelineCancellationDate">
                        <span className="refundBottomDetail--colText">{freeCancelUntil}</span>
                      </div>
                    )}
                  </div>
                  <div className="fcTimelineLast">
                    <span className="refundBottomDetail--colText">{checkInLabel}</span>
                    <div className="refundBottomDetail--colSubText">Check-in</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
