import ReviewFlightCard from './ReviewFlightCard';
import PolicySection from './PolicySection';
import ReviewPolicyPanel from './ReviewPolicyPanel';
import type { TravelPolicyLimits } from '@/services/employee-requests/fare-policy';
import type { FlightReviewViewModel } from '@/services/flights/types';
import type { FlightLayoverDetail } from '@/components/flights/types';
import { TRANSFER_SEVERITY_ORDER_UI } from '@/services/flights/selfTransferCopy';

const POLICY_ACCORDION_ID = 'reviewFlightAccordion';

/**
 * Cancellation terms are what people actually came to this accordion for, so
 * that panel opens by default and the rest start collapsed.
 */
const DEFAULT_OPEN_SECTION = 'cancellation';

/**
 * LEIS-930 ticket B6 — "Level 2 and Level 3 only... Continue stays disabled
 * until the box is ticked." `connections` is never empty when this renders
 * (the caller only mounts it when selfTransferConnectionsRequiringAck()
 * found at least one) — the worst one names the city in the copy; a second
 * connection is acknowledged by the same single checkbox, per the ticket's
 * singular wording ("this trip includes a self-transfer"), not one box per
 * connection.
 */
function SelfTransferAcknowledgement({
  connections,
  checked,
  onChange,
}: {
  connections: FlightLayoverDetail[];
  checked: boolean;
  onChange: (checked: boolean) => void;
}) {
  const worst = connections.reduce((acc, c) => {
    const accRank = TRANSFER_SEVERITY_ORDER_UI.indexOf((acc.riskLevel as 'HIGH' | 'MEDIUM') ?? 'MEDIUM');
    const cRank = TRANSFER_SEVERITY_ORDER_UI.indexOf((c.riskLevel as 'HIGH' | 'MEDIUM') ?? 'MEDIUM');
    return cRank < accRank ? c : acc;
  }, connections[0]);
  const city = worst.airport;

  return (
    <div className="border border-color-warning-200 bgColor-warning-50 rounded-3 p-3 p-md-4 mt-4 d-flex align-items-start gap-2">
      <input
        type="checkbox"
        id="self-transfer-ack"
        className="mt-1"
        checked={checked}
        onChange={(e) => onChange(e.target.checked)}
      />
      <label htmlFor="self-transfer-ack" className="text-sm color-text-dark mb-0">
        I understand this trip includes a self-transfer in {city}. I may need to collect my bags, check in again,
        and I&rsquo;m responsible for making my connection.
      </label>
    </div>
  );
}

export default function PaneReviewFlight({
  review,
  selfTransferConnections = [],
  selfTransferAcknowledged = false,
  onSelfTransferAcknowledgedChange,
  policyOffer = null,
  policyLimits = null,
  policyCurrency,
}: {
  review?: FlightReviewViewModel;
  /** LEIS-930 — connections requiring the checkbox (Level 2/3 only); empty = no checkbox at all. */
  selfTransferConnections?: FlightLayoverDetail[];
  selfTransferAcknowledged?: boolean;
  onSelfTransferAcknowledgedChange?: (checked: boolean) => void;
  /** corp (LEIS-981): the priced request payload and this traveller's limits.
   *  Both null outside Business mode, where the panel renders nothing. */
  policyOffer?: { cabin?: string; fare?: number; departDate?: string } | null;
  policyLimits?: TravelPolicyLimits | null;
  policyCurrency?: string;
}) {
  if (!review) return null;

  // Structured policies from search-service. `sections` only ever contains
  // populated entries, so there is nothing to check per section — the backend
  // already decided what is worth showing.
  const sections = review.policies?.sections ?? [];

  return (
    <div
      className="fb-pane"
      data-step-title="Price Breakup"
      data-next-label="Continue with Travel Details"
      data-total-label="Total Amount to be paid"
      data-footer-note="By continuing, you agree to our Terms &amp; Conditions"
    >
      <ReviewFlightCard review={review} nested />

      {selfTransferConnections.length > 0 && (
        <SelfTransferAcknowledgement
          connections={selfTransferConnections}
          checked={selfTransferAcknowledged}
          onChange={(checked) => onSelfTransferAcknowledgedChange?.(checked)}
        />
      )}

      {/* corp (LEIS-981). Before the airline's own fare rules below: this is
          the traveller's own company telling them something, which outranks
          a refund table in what they need to see first. */}
      <ReviewPolicyPanel offer={policyOffer} currency={policyCurrency} limits={policyLimits} />

      {sections.length > 0 ? (
        <div
          className="accordion review-flight-accordion mt-4 d-flex flex-column gap-4"
          id={POLICY_ACCORDION_ID}
        >
          {sections.map((section) => (
            <PolicySection
              key={section.key}
              section={section}
              parentId={POLICY_ACCORDION_ID}
              defaultOpen={section.key === DEFAULT_OPEN_SECTION}
            />
          ))}
        </div>
      ) : null}

      {review.importantInfo.length > 0 ? (
      <div className="bgColor-blue-50 border border-color-blue-200 rounded-3 p-3 p-md-4 mt-4">
        <h3 className="text-lg color-text-same fw-700 mb-3">Important Information</h3>
        <ul className="list-style-disc mb-0 d-flex flex-column gap-2 ps-3">
          {review.importantInfo.map((line, idx) => (
            <li key={`${idx}-${line}`} className="text-sm color-text-same">
              {line}
            </li>
          ))}
        </ul>
      </div>
      ) : null}
    </div>
  );
}
