import FxRateInfo from './FxRateInfo';
import type {
  FlightPolicyScope,
  FlightPolicySection,
  FlightPolicyTableRow,
  FlightPolicyTone,
} from '@/services/flights/types';

/**
 * One accordion item in the review page's policy stack.
 *
 * Everything rendered here is presentation-ready from search-service's
 * utils/flightPolicies.js — this component decides layout and colour, never
 * meaning. `tone` is the API telling us the weight of a value; the mapping to a
 * class lives here so a design change never needs a backend deploy.
 */

/**
 * Non-refundable is a fact about the fare, not an error, so the negative tone
 * uses the warning orange rather than danger red.
 */
const TONE_CLASS: Record<FlightPolicyTone, string> = {
  positive: 'color-text-green-700',
  neutral: 'color-text-same',
  negative: 'color-text-orange-600',
};

/**
 * One fee: what the airline charges, and — where we can say it — roughly what
 * that is in the fare's currency.
 *
 * The filed amount stays primary and unchanged. A fee the airline filed in its
 * own currency sits on a page where every other amount is USD, so it is marked
 * rather than left to be read carefully: a pill carrying the currency code, and
 * a muted estimate beside it.
 *
 * The estimate is always subordinate — muted, prefixed "~", and never a
 * replacement. The airline charges the filed number, in its own currency, at
 * whatever rate applies on the day the traveller actually cancels; anything we
 * print today is our approximation of someone else's future bill, inside a
 * table people book against. Every one of `convertedValue`/`convertedCurrency`/
 * `fxRate`/`fxRateAsOf` must be present or none are — the API sends them as a
 * set — so there is no state where a number appears that cannot be explained.
 */
function PolicyValue({ row, rowId }: { row: FlightPolicyTableRow; rowId: string }) {
  const hasEstimate = Boolean(
    row.convertedValue && row.convertedCurrency && row.fxRate && row.fxRateAsOf
  );

  return (
    <>
      <span className="d-flex flex-wrap align-items-baseline gap-2">
        <span className={`fw-600 ${TONE_CLASS[row.tone]}`}>
          {row.filedCurrency ? (
            <span
              className="policy-foreign-currency"
              title={`Filed by the airline in ${row.filedCurrency}`}
            >
              {row.filedCurrency}
            </span>
          ) : null}
          {row.filedCurrency ? stripLeadingCurrency(row.value, row.filedCurrency) : row.value}
        </span>

        {hasEstimate ? (
          <span className="d-inline-flex align-items-baseline gap-1 text-sm fw-400 color-text-muted">
            {/* "~" carries the meaning visually but is announced
                inconsistently — often skipped entirely — so the spoken form is
                supplied separately and this half is hidden from the reader. */}
            <span aria-hidden="true">
              ~ {row.convertedCurrency} {row.convertedValue}
            </span>
            <span className="visually-hidden">
              {spokenEstimate(row.convertedValue!, row.convertedCurrency!)}
            </span>
            <FxRateInfo
              filedCurrency={row.filedCurrency ?? ''}
              convertedCurrency={row.convertedCurrency!}
              rate={row.fxRate!}
              asOf={row.fxRateAsOf!}
              panelId={`${rowId}-fx`}
            />
          </span>
        ) : null}
      </span>

      {row.note ? (
        <span className="d-block text-xs fw-400 color-text-muted mt-1">{row.note}</span>
      ) : null}
    </>
  );
}

/**
 * "INR 5,000.00" -> "5,000.00" once the code is shown in the pill beside it.
 *
 * Only strips a code it was told to expect, and only at the start, so a value
 * that does not begin with it — or any wording search-service changes later —
 * passes through whole rather than losing a character.
 */
function stripLeadingCurrency(value: string, currency: string): string {
  const trimmed = value.trim();
  return trimmed.toUpperCase().startsWith(`${currency.toUpperCase()} `)
    ? trimmed.slice(currency.length + 1).trim()
    : trimmed;
}

/**
 * "100.75" -> "approximately 100 dollars 75 cents".
 *
 * Screen readers handle a bare "~ USD 100.75" poorly: the tilde is dropped or
 * read as punctuation, so the estimate is announced as though it were exact.
 * Spelling the units out is the only way the qualifier survives into speech.
 *
 * Any currency other than USD falls back to naming the code, since "dollars"
 * would be wrong and inventing unit names for 160-odd currencies would be worse.
 */
function spokenEstimate(amount: string, currency: string): string {
  if (currency !== 'USD') return `approximately ${amount} ${currency}`;

  const [whole, fraction] = amount.replace(/,/g, '').split('.');
  const cents = Number(fraction ?? '0');
  return cents > 0
    ? `approximately ${whole} dollars ${cents} cents`
    : `approximately ${whole} dollars`;
}

function PolicyScopeBlock({
  scope,
  scopeId,
}: {
  scope: FlightPolicyScope;
  /** Unique per scope on the page — the disclosure panels are addressed by id,
   *  and a duplicate would point two triggers at the same panel. */
  scopeId: string;
}) {
  const columns = scope.columns ?? [];

  return (
    <div className="mb-3">
      {/* Route chip — which leg(s) these conditions cover. Segments sharing
          identical rules are already merged upstream, so one chip per distinct
          rule set rather than one per flight. */}
      {scope.label ? (
        <span className="d-inline-block bgColor-blue-50 border border-color-blue-200 color-text-first rounded-2 px-2 py-1 text-xs fw-600 mb-2">
          {scope.label}
        </span>
      ) : null}

      {scope.rows.length > 0 ? (
        <div className="table-responsive">
          <table className="table align-middle mb-0">
            <thead>
              <tr className="bgColor-gray-50 border-bottom">
                <th className="text-sm fw-600 py-2 ps-2">{columns[0] ?? 'Condition'}</th>
                <th className="text-sm fw-600 py-2">{columns[1] ?? 'Amount'}</th>
              </tr>
            </thead>
            <tbody>
              {scope.rows.map((row, idx) => (
                <tr key={`${row.window ?? ''}-${row.value}-${idx}`} className="border-bottom">
                  <td className="text-sm ps-2 py-2 color-text-same">{row.window ?? 'Any time'}</td>
                  <td className="text-sm py-2">
                    <PolicyValue row={row} rowId={`${scopeId}-row${idx}`} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : null}

      {/* Nothing could be structured out of this carrier's wording — show the
          source prose rather than an empty panel. Scroll-capped because an
          unparsed ATPCO block can run to thousands of characters. */}
      {scope.rows.length === 0 && scope.rawText ? (
        <p
          className="text-xs color-text-same mb-0"
          style={{ maxHeight: 180, overflowY: 'auto', whiteSpace: 'pre-wrap', lineHeight: 1.6 }}
        >
          {scope.rawText}
        </p>
      ) : null}
    </div>
  );
}

export default function PolicySection({
  section,
  parentId,
  defaultOpen = false,
}: {
  section: FlightPolicySection;
  /** Bootstrap accordion parent — keeps only one panel open at a time. */
  parentId: string;
  defaultOpen?: boolean;
}) {
  const panelId = `policyPanel-${section.key}`;

  return (
    <div className="accordion-item card bgColor-white border-0 rounded-3 shadow-sm">
      <div className="accordion-header">
        <button
          className={`accordion-button${defaultOpen ? '' : ' collapsed'} smallHeading bg-transparent shadow-none color-text-first text-md mb-0`}
          type="button"
          data-bs-toggle="collapse"
          data-bs-target={`#${panelId}`}
          aria-expanded={defaultOpen}
          aria-controls={panelId}
        >
          {section.title}
        </button>
      </div>

      <div
        id={panelId}
        className={`accordion-collapse collapse${defaultOpen ? ' show' : ''}`}
        data-bs-parent={`#${parentId}`}
      >
        <div className="accordion-body px-3 pt-0">
          {section.scopes.map((scope, idx) => (
            <PolicyScopeBlock
              key={`${scope.label}-${idx}`}
              scope={scope}
              scopeId={`${section.key}-scope${idx}`}
            />
          ))}

          {section.notes.length > 0 ? (
            <div className="mt-2">
              <h4 className="text-xs color-text-gray fw-600 text-uppercase mb-2">
                Additional information
              </h4>
              <ul
                className="list-style-disc mb-0 d-flex flex-column gap-1 ps-3"
                style={{ lineHeight: 1.6 }}
              >
                {section.notes.map((note, idx) => (
                  <li key={`${idx}-${note.slice(0, 24)}`} className="text-xs color-text-same">
                    {note}
                  </li>
                ))}
              </ul>
            </div>
          ) : null}
        </div>
      </div>
    </div>
  );
}
