"use client";

import Link from "next/link";

import type { MyRequestRow } from "@/services/employee-requests/employee-requests.types";
import { formatEnumLabel, formatMoney } from "@/services/employee-requests/format";
import AirlineLogo from "@/components/flights/AirlineLogo";

/**
 * A booked/cancelled trip, visually matching leisure-ui's own
 * TripCard.tsx / FlightTripCard.tsx (personal-mode My Trips) almost
 * verbatim — same card chrome, same icon badge, same summary grid — adapted
 * to MyRequestRow instead of leisure-ui's Trip/FlightTrip shape.
 *
 * The CTA matches leisure-ui's own behaviour too, not just its look: a plain
 * `Link` to a separate booking-details page (`app/booking-details/page.tsx`),
 * the same as leisure-ui's own TripCard/FlightTripCard navigate their CTA to
 * `/booking-details?bookingId=...`. This card used to expand an inline
 * detail panel in place instead — see that page's own doc comment for why
 * this changed and what it does and doesn't carry over from leisure-ui's
 * version.
 */

/** "02 Feb'26 Tue" — leisure-ui's own TripCard.formatTripDate, verbatim. */
function formatTripDate(iso: string | null | undefined): string {
  if (!iso) return "—";
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return "—";
  const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  return `${date.getUTCDate()} ${months[date.getUTCMonth()]}'${String(date.getUTCFullYear()).slice(-2)} ${days[date.getUTCDay()]}`;
}

function daysUntil(iso: string | null | undefined): number | null {
  if (!iso) return null;
  const target = Date.parse(`${iso.slice(0, 10)}T00:00:00Z`);
  if (Number.isNaN(target)) return null;
  const today = Date.parse(`${new Date().toISOString().slice(0, 10)}T00:00:00Z`);
  const days = Math.round((target - today) / 86_400_000);
  return days >= 0 ? days : null;
}

/** First 2 letters of a flight-number string ("AA 100 / AA 200" → "AA"),
 *  for AirlineLogo's `code` — MyRequestRow carries no carrier code of its
 *  own, only the free-text flightNumbers string the request was filed with. */
function carrierCodeFrom(flightNumbers: string | null): string | null {
  const match = flightNumbers?.trim().match(/^([A-Z0-9]{2})\s?\d/i);
  return match ? match[1].toUpperCase() : null;
}

const BuildingsIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" className="bi bi-buildings" style={{ width: 20, height: 20, fill: "var(--fra-navy-2)" }} viewBox="0 0 16 16">
    <path d="M14.763.075A.5.5 0 0 1 15 .5v15a.5.5 0 0 1-.5.5h-3a.5.5 0 0 1-.5-.5V14h-1v1.5a.5.5 0 0 1-.5.5h-9a.5.5 0 0 1-.5-.5V10a.5.5 0 0 1 .342-.474L6 7.64V4.5a.5.5 0 0 1 .276-.447l8-4a.5.5 0 0 1 .487.022M6 8.694 1 10.36V15h5zM7 15h2v-1.5a.5.5 0 0 1 .5-.5h2a.5.5 0 0 1 .5.5V15h2V1.309l-7 3.5z" />
    <path d="M2 11h1v1H2zm2 0h1v1H4zm-2 2h1v1H2zm2 0h1v1H4zm4-4h1v1H8zm2 0h1v1h-1zm-2 2h1v1H8zm2 0h1v1h-1zm2-2h1v1h-1zm0 2h1v1h-1zM8 7h1v1H8zm2 0h1v1h-1zm2 0h1v1h-1zM8 5h1v1H8zm2 0h1v1h-1zm2 0h1v1h-1zm0-2h1v1h-1z" />
  </svg>
);

const FlightIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" style={{ width: 20, height: 20 }} viewBox="0 0 24 24" fill="none" stroke="var(--fra-navy-2)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
    <path d="M17.8 19.2 16 11l3.5-3.5C21 6 21.5 4 21 3c-1-.5-3 0-4.5 1.5L13 8 4.8 6.2c-.5-.1-.9.1-1.1.5l-.3.5c-.2.5-.1 1 .3 1.3L9 12l-2 3H4l-1 1 3 2 2 3 1-1v-3l3-2 3.5 5.3c.3.4.8.5 1.3.3l.5-.2c.4-.3.6-.7.5-1.2z" />
  </svg>
);

const PersonIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" className="bi bi-person" style={{ width: 16, height: 16, fill: "currentColor" }} viewBox="0 0 16 16">
    <path d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6m2-3a2 2 0 1 1-4 0 2 2 0 0 1 4 0m4 8c0 1-1 1-1 1H3s-1 0-1-1 1-4 6-4 6 3 6 4m-1-.004c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10s-3.516.68-4.168 1.332c-.678.678-.83 1.418-.832 1.664z" />
  </svg>
);

const ArrowRight = () => (
  <svg style={{ width: 16, height: 16, fill: "currentColor" }} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512.009 512.009">
    <path d="M508.625,247.801L392.262,131.437c-4.18-4.881-11.526-5.45-16.407-1.269c-4.881,4.18-5.45,11.526-1.269,16.407c0.39,0.455,0.814,0.88,1.269,1.269l96.465,96.582H11.636C5.21,244.426,0,249.636,0,256.063s5.21,11.636,11.636,11.636H472.32l-96.465,96.465c-4.881,4.18-5.45,11.526-1.269,16.407s11.526,5.45,16.407,1.269c0.455-0.39,0.88-0.814,1.269-1.269l116.364-116.364C513.137,259.67,513.137,252.34,508.625,247.801z" />
  </svg>
);

export function MyTripsCard({ row }: { row: MyRequestRow }) {
  const isHotel = row.type === "HOTEL";
  const flight = row.trip.flight;
  const hotel = row.trip.hotel;
  const cancelled = row.status === "CANCELLED";
  const until = !cancelled ? daysUntil(row.trip.travelStartDate) : null;
  const carrierCode = flight ? carrierCodeFrom(flight.flightNumbers) : null;
  const detailsHref = `/booking-details?reference=${encodeURIComponent(row.reference)}`;

  return (
    <div className="card rounded-3 border position-relative mb-3">
      {/* Icon badge — leisure-ui's own floating circle, top-left of the card. */}
      <span
        className="position-absolute border bgColor-white shadow-sm rounded-5 d-flex align-items-center justify-content-center"
        style={{ top: "15px", left: "-15px", height: "40px", width: "40px" }}
      >
        {isHotel ? <BuildingsIcon /> : <FlightIcon />}
      </span>

      {/* Card header */}
      <div className="card-header border-bottom position-relative z-2 shadow-sm">
        {cancelled && (
          <div className="mb-3 p-3 rounded-3" style={{ background: "#fee2e2" }}>
            <span
              className="text-xs fw-700 text-uppercase px-2 py-1 rounded-5"
              style={{ background: "#fecaca", color: "#b91c1c" }}
            >
              Cancelled
            </span>
            {/* The refund outcome, right where the pill is seen (LEIS-1034) —
                null only for a trip cancelled before this feature shipped. */}
            {row.cancellation && (
              <small className="d-block mt-2" style={{ color: "#b91c1c" }}>
                Refunded {formatMoney(row.cancellation.refundAmount, row.cancellation.currency)}
                {Number.parseFloat(row.cancellation.fee || "0") > 0
                  ? ` · fee ${formatMoney(row.cancellation.fee, row.cancellation.currency)}`
                  : ""}
              </small>
            )}
          </div>
        )}

        {isHotel ? (
          <div className="row align-items-center">
            <div className="col-xxl-8 col-xl-8 col-lg-7 col-12">
              <div className="px-4 py-3 d-flex align-items-sm-center align-items-start gap-2 flex-column flex-sm-row mb-sm-0 mb-3">
                <h2 className="subHeading fw-bold text-capitalize mb-0 text-left">
                  {hotel?.property ?? `Hotel request #${row.reference}`}
                </h2>
                {until !== null && (
                  <small className="color-text-first lh-1 text-nowrap">In {until} Days</small>
                )}
              </div>
              <div className="d-flex gap-2 flex-column flex-md-row px-md-4 px-sm-2 px-0 pb-0 pb-lg-3">
                {hotel?.location && <small className="fw-bold">{hotel.location}</small>}
                <small className="text-secondary">Booking ID - {row.reference}</small>
              </div>
            </div>
            <div className="col-xxl-4 col-xl-4 col-lg-5 col-12 text-lg-end text-left pb-lg-0 pb-3">
              <Link href={detailsHref} className="buttons btnColor-first py-2 px-3 mt-lg-0 mt-3 text-md text-uppercase">
                {row.status === "BOOKED" ? "View & Manage" : "View"} Booking
              </Link>
            </div>
          </div>
        ) : (
          <div className="row align-items-center">
            <div className="col-xxl-9 col-xl-9 col-lg-8 col-12">
              <div className="ps-md-4 ps-sm-2 ps-0 d-flex flex-column gap-md-1 gap-3 mb-3">
                <div className="d-flex flex-wrap align-items-sm-center align-items-start gap-3 flex-column flex-sm-row">
                  <div className="d-flex align-items-center gap-2 ps-md-0 ps-sm-4 ps-4">
                    <AirlineLogo
                      code={carrierCode}
                      name={flight?.airline ?? undefined}
                      width={30}
                      height={30}
                      className="rounded-2 flex-shrink-0"
                      style={{ objectFit: "contain" }}
                    />
                    <div>
                      <div className="subHeading text-lg text-capitalize color-text-dark fw-bolder mb-0">
                        {flight?.airline || `Flight request #${row.reference}`}
                      </div>
                      <div className="text-xs">
                        {[flight?.flightNumbers, formatEnumLabel(flight?.cabin)].filter(Boolean).join(" · ")}
                      </div>
                    </div>
                  </div>
                </div>
                {flight && (
                  <div className="d-flex flex-wrap align-items-center gap-md-3 gap-2">
                    <p className="text-sm mb-0 fw-600">
                      {flight.origin} <ArrowRight /> {flight.destination}
                    </p>
                    <small className="text-secondary">Booking ID - {row.reference}</small>
                  </div>
                )}
              </div>
            </div>
            <div className="col-xxl-3 col-xl-3 col-lg-4 col-12 text-lg-end text-left pb-lg-0 pb-3">
              <Link href={detailsHref} className="buttons btnColor-first py-2 px-3 mt-lg-0 mt-3 text-md text-uppercase">
                View &amp; Manage Booking
              </Link>
            </div>
          </div>
        )}
      </div>

      {/* Card body — leisure-ui's own summary grid, always shown (not behind
          the CTA): Check In/Check Out/Room for a stay, Departs/Returns/
          Passengers for a flight. */}
      {!cancelled && (
        <div className="card-body py-4 px-lg-5 px-3 position-relative z-1">
          {isHotel ? (
            <div className="row align-items-end">
              <div className="col-xxl-3 col-xl-3 col-lg-3 col-md-4 col-sm-6 col-12 mb-md-0 mb-3">
                <div className="d-flex flex-column gap-1">
                  <span className="text-secondary text-uppercase">Check In</span>
                  <p className="fw-bold mb-0">{formatTripDate(hotel?.checkIn)}</p>
                </div>
              </div>
              <div className="col-xxl-3 col-xl-3 col-lg-3 col-md-4 col-sm-6 col-12 mb-md-0 mb-3 my-md-0 my-3">
                <div className="d-flex flex-column gap-1">
                  <span className="text-secondary text-uppercase">Check Out</span>
                  <p className="fw-bold mb-0">{formatTripDate(hotel?.checkOut)}</p>
                </div>
              </div>
              <div className="col-xxl-3 col-xl-3 col-lg-3 col-md-4 col-sm-6 col-12 mb-md-0 mb-3">
                <div className="d-flex flex-column gap-1">
                  <p className="fw-bold mb-0 color-text-first d-flex align-items-center gap-1">
                    <BuildingsIcon /> {hotel ? `1 Room, ${hotel.nights} Night${hotel.nights === 1 ? "" : "s"}` : "—"}
                  </p>
                  {row.travellers.length > 0 && (
                    <small className="fw-bold d-flex align-items-center gap-1">
                      <PersonIcon /> {row.travellers.length}
                    </small>
                  )}
                </div>
              </div>
            </div>
          ) : (
            <div className="row align-items-end">
              <div className="col-xxl-3 col-xl-3 col-lg-3 col-md-4 col-sm-6 col-12 mb-md-0">
                <div className="d-flex flex-column gap-1">
                  <span className="text-secondary text-uppercase">Departs</span>
                  <p className="fw-bold mb-0">{formatTripDate(flight?.departDate)}</p>
                </div>
              </div>
              {flight?.returnDate && (
                <div className="col-xxl-3 col-xl-3 col-lg-3 col-md-4 col-sm-6 col-12 mb-md-0 mb-3 my-md-0 my-3">
                  <div className="d-flex flex-column gap-1">
                    <span className="text-secondary text-uppercase">Returns</span>
                    <p className="fw-bold mb-0">{formatTripDate(flight.returnDate)}</p>
                  </div>
                </div>
              )}
              <div className="col-xxl-3 col-xl-3 col-lg-3 col-md-4 col-sm-6 col-12 mb-md-0">
                <div className="d-flex flex-column gap-1">
                  <p className="fw-bold mb-0 color-text-first d-flex align-items-center gap-1">
                    <FlightIcon /> Passengers
                  </p>
                  <small className="fw-bold d-flex align-items-center gap-1">
                    <PersonIcon /> {row.travellers.length || 1}
                  </small>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
