'use client';

import { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';

import { decodeBusinessJwt, getActiveBusinessSession, getBusinessAccessToken } from '@/lib/business-session';
import { toast } from '@/lib/toast';
import { getCheckout, payCheckout, type CheckoutCard, type CheckoutData, type BookingReceipt } from '@/services/business-checkout/business-checkout.client';
import { BRAND_LABEL, digitsOnly, type CardBrand } from '@/services/payment-cards/card-utils';
import AddCardForm from '@/components/payment-cards/AddCardForm';
import ChangeAddressModal from '@/components/payment-cards/ChangeAddressModal';
import { EMPLOYEE_HOME } from '@/constants/business-routes';

type Step = 'approve' | 'payment' | 'done';

/**
 * LEIS-971/972/973 Checkout — Approve → Payment → Done, one request at a
 * time. Built against the real reference (design.admedia.com/.../
 * approval-checkout.php?ids=FR-1048) using the `.co-*` classes already
 * ported into public/assets/css/biz-payment.css for exactly this page —
 * same design system as Payment methods (LEIS-968/969), so card tiles
 * (`.bc-tile`) and form fields (`.bc-field`) are shared with that page.
 */
export default function CheckoutPage({ requestId }: { requestId: string }) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const comment = searchParams.get('comment') ?? '';

  const [authorised, setAuthorised] = useState(false);
  const [token, setToken] = useState<string | null>(null);

  const [data, setData] = useState<CheckoutData | null>(null);
  const [loaded, setLoaded] = useState(false);
  const [notFound, setNotFound] = useState(false);

  const [selectedCardId, setSelectedCardId] = useState<string | 'new' | null>(null);
  const [cardCode, setCardCode] = useState('');
  const [addressTarget, setAddressTarget] = useState<CheckoutCard | null>(null);
  const [paying, setPaying] = useState(false);
  const [payError, setPayError] = useState<string | null>(null);
  const [doneReceipt, setDoneReceipt] = useState<BookingReceipt | null>(null);

  useEffect(() => {
    async function checkAccess() {
      const session = getActiveBusinessSession();
      if (!session) {
        router.replace('/employee-login');
        return;
      }
      const current = getBusinessAccessToken();
      const payload = decodeBusinessJwt(current ?? '');
      if (payload?.role !== 'ADMIN') {
        router.replace(EMPLOYEE_HOME);
        return;
      }
      setToken(current);
      setAuthorised(true);
    }
    checkAccess();
  }, [router]);

  const load = async (t: string) => {
    const res = await getCheckout(t, requestId);
    if (!res.success || !res.data) {
      setNotFound(true);
      setLoaded(true);
      return;
    }
    setData(res.data);
    const defaultCard = res.data.cards.find((c) => c.isDefault && !c.expired) ?? res.data.cards.find((c) => !c.expired) ?? null;
    setSelectedCardId((current) => current ?? defaultCard?.id ?? null);
    setLoaded(true);
  };

  useEffect(() => {
    if (!authorised || !token) return;
    async function run() {
      await load(token!);
    }
    run();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [authorised, token]);

  if (!authorised) return null;

  // Any status Checkout can't act on (rejected, withdrawn, booking_failed,
  // etc.) reads the same as a request that couldn't be found — the design's
  // own "Nothing to pay for" empty state covers both, per the reference.
  const ACTIONABLE = new Set(['PENDING', 'APPROVED', 'BOOKED']);
  const unavailable = notFound || (loaded && data && !ACTIONABLE.has(data.status));

  const step: Step = doneReceipt || data?.status === 'APPROVED' || data?.status === 'BOOKED' ? 'done' : 'payment';

  const selectedCard = data?.cards.find((c) => c.id === selectedCardId) ?? null;

  const handlePay = async () => {
    if (!token || !data) return;
    setPayError(null);
    if (!selectedCardId) {
      setPayError('Select a card to pay with.');
      return;
    }
    if (selectedCardId === 'new') {
      setPayError('Save the new card above first, then select it to pay.');
      return;
    }
    const digits = digitsOnly(cardCode);
    if (digits.length < 3 || digits.length > 4) {
      setPayError('Enter the security code.');
      return;
    }
    setPaying(true);
    const res = await payCheckout(token, requestId, { cardId: selectedCardId, cardCode: digits, comment: comment || undefined });
    setPaying(false);
    if (!res.success || !res.data) {
      setPayError(res.message ?? 'The card was declined. Try again or choose another card.');
      return;
    }
    setDoneReceipt(res.data.booking);
    toast.success(`${data.approving.reference} paid and booked.`);
  };

  return (
    <section className="bz-ui bz-page">
      <div className="mx-auto w-full max-w-[1100px] px-3 py-8">
        <div className="co-top">
          <div>
            <ol className="co-crumbs">
              <li>
                <Link href="/admin/flight-approvals">
                  Approval queue
                </Link>
              </li>
              <li aria-current="page">Checkout</li>
            </ol>
            <h1 className="co-title">Checkout</h1>
          </div>
          <ol className="co-steps">
            <li className="is-done">
              <span>
                <i className="bi bi-check" aria-hidden="true" />
              </span>
              Approve
            </li>
            <li className={step === 'payment' ? 'is-current' : step === 'done' ? 'is-done' : ''}>
              <span>{step === 'done' ? <i className="bi bi-check" aria-hidden="true" /> : 2}</span>
              Payment
            </li>
            <li className={step === 'done' ? 'is-current' : ''}>
              <span>3</span>
              Done
            </li>
          </ol>
        </div>

        {!loaded && <div className="bz-card p-8 text-center text-gray-500">Loading…</div>}

        {loaded && unavailable && (
          <div className="bz-card co-empty">
            <span className="bz-icon-tile tone-navy" aria-hidden="true">
              <i className="bi bi-credit-card" />
            </span>
            <h2 className="co-h2">Nothing to pay for</h2>
            <p>We couldn&rsquo;t find the requests you were approving. Go back to the approval queue and click Approve again.</p>
            <Link href="/admin/flight-approvals" className="bz-btn bz-btn-primary">
              <i className="bi bi-list-check" aria-hidden="true" />
              <span>Back to approval queue</span>
            </Link>
          </div>
        )}

        {loaded && !unavailable && data && step === 'payment' && (
          <div className="co-layout">
            <div className="co-left">
              <ApprovingBox data={data} />

              {data.priceCheck?.changed && (
                <div className="bz-card co-box flex items-start gap-3" style={{ borderColor: 'var(--bz-warn, #c58a1a)' }}>
                  <i className="bi bi-exclamation-triangle-fill text-amber-500 mt-0.5" aria-hidden="true" />
                  <div className="text-sm">
                    <strong>Price changed</strong> from {data.priceCheck.currency} {data.priceCheck.previousFare} to {data.priceCheck.currency}{' '}
                    {data.priceCheck.fare}. You&rsquo;ll pay the current price.
                  </div>
                </div>
              )}

              <div className="bz-card co-box">
                <div className="co-box-head">
                  <h2 className="co-h2">Payment method</h2>
                  <Link href="/admin/payment-methods" className="co-change">
                    Manage cards
                  </Link>
                </div>
                <div className="co-opts">
                  {data.cards.map((card) => (
                    <CardOption
                      key={card.id}
                      card={card}
                      selected={selectedCardId === card.id}
                      onSelect={() => setSelectedCardId(card.id)}
                      cardCode={cardCode}
                      onCardCode={setCardCode}
                      onChangeAddress={() => setAddressTarget(card)}
                    />
                  ))}

                  <div className={`co-opt${selectedCardId === 'new' ? ' is-selected' : ''}`}>
                    <label className="co-opt-head">
                      <input type="radio" name="checkoutCard" checked={selectedCardId === 'new'} onChange={() => setSelectedCardId('new')} />
                      <span className="bc-tile is-blank" aria-hidden="true">
                        <i className="bi bi-plus-lg" />
                      </span>
                      <span className="co-opt-text">
                        <strong>Add a new card</strong>
                        <small>Visa, Mastercard, American Express, Discover</small>
                      </span>
                    </label>
                    {selectedCardId === 'new' && (
                      <div className="co-opt-body co-new">
                        <AddCardForm
                          token={token!}
                          companyAddress={data.companyAddress}
                          onAdded={async () => {
                            await load(token!);
                            toast.success('Card saved. Select it to pay.');
                            setSelectedCardId(null);
                          }}
                        />
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>

            <OrderSummarySidebar
              data={data}
              selectedCard={selectedCard}
              paying={paying}
              payError={payError}
              onPay={handlePay}
            />
          </div>
        )}

        {loaded && !unavailable && data && step === 'done' && (
          <DoneBox data={data} receipt={doneReceipt ?? data.booking} />
        )}
      </div>

      {token && addressTarget && (
        <ChangeAddressModal
          token={token}
          card={{ ...addressTarget, addedAt: '' }}
          companyAddress={data?.companyAddress ?? null}
          onClose={() => setAddressTarget(null)}
          onChanged={async () => {
            setAddressTarget(null);
            toast.success('Billing address updated.');
            await load(token);
          }}
        />
      )}
    </section>
  );
}

function ApprovingBox({ data }: { data: CheckoutData }) {
  const { approving } = data;
  const flight = approving.flight;
  const hotel = approving.hotel;
  return (
    <div className="bz-card co-box">
      <div className="co-box-head">
        <span className="co-eyebrow">Approving</span>
        <Link href="/admin/flight-approvals" className="co-change">
          Change
        </Link>
      </div>
      <ul className="co-trips">
        <li>
          <span className="co-trip-icon" aria-hidden="true">
            <i className={`bi ${hotel ? 'bi-building' : 'bi-airplane'}`} />
          </span>
          <div className="co-trip-text">
            <strong>
              {hotel ? (
                hotel.property
              ) : flight ? (
                <>
                  {flight.origin} <i className="bi bi-arrow-left-right" aria-hidden="true" /> {flight.destination}
                </>
              ) : (
                approving.reference
              )}
            </strong>
            <small>
              {approving.traveller ?? 'Traveller'}
              {hotel && (
                <>
                  {' '}
                  · {hotel.location} · {hotel.checkIn} – {hotel.checkOut} · {hotel.roomType ?? hotel.rateType ?? ''}
                </>
              )}
              {flight && (
                <>
                  {' '}
                  · {flight.departDate}
                  {flight.returnDate ? ` – ${flight.returnDate}` : ''} · {flight.airline ?? ''} · {flight.cabin}
                </>
              )}
            </small>
          </div>
          <span className="co-trip-id">{approving.reference}</span>
        </li>
      </ul>
    </div>
  );
}

function CardOption({
  card,
  selected,
  onSelect,
  cardCode,
  onCardCode,
  onChangeAddress,
}: {
  card: CheckoutCard;
  selected: boolean;
  onSelect: () => void;
  cardCode: string;
  onCardCode: (v: string) => void;
  onChangeAddress: () => void;
}) {
  const brandLabel = BRAND_LABEL[card.brand as CardBrand] ?? card.brand;
  const addr = [card.billingAddress.line1, card.billingAddress.city, card.billingAddress.region, card.billingAddress.postal].filter(Boolean).join(', ');
  return (
    <div className={`co-opt${selected ? ' is-selected' : ''}${card.expired ? ' is-disabled' : ''}`}>
      <label className="co-opt-head">
        <input type="radio" name="checkoutCard" checked={selected} disabled={card.expired} onChange={onSelect} />
        <span className={`bc-tile is-${card.brand}`} aria-hidden="true">
          <b>{brandLabel.toUpperCase()}</b>
          <i>•• {card.last4}</i>
        </span>
        <span className="co-opt-text">
          <strong>
            {brandLabel} ending in {card.last4}
            {card.isDefault && <span className="bz-badge">Default</span>}
          </strong>
          <small className={card.expired ? 'is-expired' : undefined}>
            {card.expired ? 'Expired' : 'Expires'} {String(card.expMonth).padStart(2, '0')}/{String(card.expYear).slice(-2)} · {card.nameOnCard}
          </small>
        </span>
      </label>
      {card.expired && (
        <Link href="/admin/payment-methods" className="co-update">
          Update card
        </Link>
      )}
      {selected && !card.expired && (
        <div className="co-opt-body">
          <div className="bc-field">
            <label className="bz-label" htmlFor={`cvc-${card.id}`}>
              Security code
            </label>
            <input
              type="password"
              className="bz-input"
              id={`cvc-${card.id}`}
              inputMode="numeric"
              autoComplete="cc-csc"
              placeholder="CVC"
              maxLength={4}
              value={cardCode}
              onChange={(e) => onCardCode(digitsOnly(e.target.value).slice(0, 4))}
              autoFocus
            />
          </div>
          <div className="co-billing">
            <span className="bz-label">Billing address</span>
            <p>{addr || '—'}</p>
            <button type="button" className="co-billing-edit" onClick={onChangeAddress}>
              <i className="bi bi-pencil" aria-hidden="true" />
              Change
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function OrderSummarySidebar({
  data,
  selectedCard,
  paying,
  payError,
  onPay,
}: {
  data: CheckoutData;
  selectedCard: CheckoutCard | null;
  paying: boolean;
  payError: string | null;
  onPay: () => void;
}) {
  const s = data.orderSummary;
  const hotel = data.approving.hotel;
  return (
    <aside className="bz-card co-summary">
      <div className="co-eyebrow">Order summary</div>
      <div className="co-trip-text mt-2">
        <strong>
          {data.approving.reference}
          {hotel && <> · {hotel.property}</>}
          {!hotel && data.approving.flight && (
            <>
              {' '}
              · {data.approving.flight.origin} → {data.approving.flight.destination}
            </>
          )}
        </strong>
        <small>{data.approving.traveller}</small>
      </div>

      <ul className="co-lines">
        <li>
          <span>{hotel ? 'Hotel fare' : 'Flight fare'}</span>
          <strong>
            {s.currency} {s.fare}
          </strong>
        </li>
        {!hotel && (
          <li>
            <span>Bags & seats</span>
            <strong>
              {s.currency} {s.bagsAndSeats}
            </strong>
          </li>
        )}
        <li>
          <span>Taxes & {hotel ? 'fees' : 'carrier fees'}</span>
          <strong>{s.taxesIncludedInFare ? 'Included' : `${s.currency} ${s.taxesAndFees}`}</strong>
        </li>
      </ul>

      <dl className="co-totals">
        <div className="co-total">
          <dt>Total</dt>
          <dd>
            {s.currency} {s.total}
          </dd>
        </div>
      </dl>

      {selectedCard && (
        <div className="co-paying">
          <small>Paying with</small>
          <div>
            <span className={`bc-tile is-${selectedCard.brand}`} aria-hidden="true">
              <b>{(BRAND_LABEL[selectedCard.brand as CardBrand] ?? selectedCard.brand).toUpperCase()}</b>
              <i>•• {selectedCard.last4}</i>
            </span>
            <strong>
              {BRAND_LABEL[selectedCard.brand as CardBrand] ?? selectedCard.brand} ending in {selectedCard.last4}
            </strong>
          </div>
        </div>
      )}

      {payError && <p className="bz-error co-pay-err">{payError}</p>}

      <button type="button" className="bz-btn bz-btn-primary co-pay" disabled={paying || data.cards.length === 0} onClick={onPay}>
        <i className="bi bi-lock-fill" aria-hidden="true" />
        <span>{paying ? 'Paying…' : `Pay ${s.currency} ${s.total}`}</span>
      </button>
      <p className="co-secure">
        <i className="bi bi-shield-check" aria-hidden="true" />
        Secure payment. Your card may be verified by your bank before the payment goes through.
      </p>
      <p className="co-terms">By paying you approve the request(s) above under your company&rsquo;s travel policy and agree to the fare rules of the airline.</p>
    </aside>
  );
}

function DoneBox({ data, receipt }: { data: CheckoutData; receipt: BookingReceipt | null }) {
  const addr = receipt?.billingAddress
    ? [receipt.billingAddress.line1, receipt.billingAddress.city, receipt.billingAddress.region, receipt.billingAddress.postal, receipt.billingAddress.country]
        .filter(Boolean)
        .join(', ')
    : null;
  return (
    <div className="bz-card co-done" tabIndex={-1}>
      <div className="co-done-icon">
        <i className="bi bi-check-lg" aria-hidden="true" />
      </div>
      <h2 className="co-h2">Payment complete</h2>
      <p className="co-done-sub">
        {data.approving.reference} is approved. {data.approving.traveller ?? 'The traveller'} will be notified and the travel team will{' '}
        {data.approving.hotel ? 'confirm the stay' : 'book the flight'}.
      </p>
      {receipt && (
        <dl className="co-receipt">
          <div>
            <dt>Amount paid</dt>
            <dd>
              {data.orderSummary.currency} {receipt.amountCharged}
            </dd>
          </div>
          {receipt.card && (
            <div>
              <dt>Paid with</dt>
              <dd>
                {BRAND_LABEL[receipt.card.brand as CardBrand] ?? receipt.card.brand} ending in {receipt.card.last4}
              </dd>
            </div>
          )}
          {addr && (
            <div>
              <dt>Billing address</dt>
              <dd>{addr}</dd>
            </div>
          )}
          {receipt.paymentReference && (
            <div>
              <dt>Reference</dt>
              <dd>{receipt.paymentReference}</dd>
            </div>
          )}
          {receipt.chargedAt && (
            <div>
              <dt>Date</dt>
              <dd>{new Date(receipt.chargedAt).toLocaleString('en-US', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })}</dd>
            </div>
          )}
        </dl>
      )}
      <div className="co-done-actions">
        <Link href="/admin/flight-approvals" className="bz-btn bz-btn-primary">
          <i className="bi bi-list-check" aria-hidden="true" />
          <span>Back to approval queue</span>
        </Link>
        <Link href="/admin/payment-methods" className="bz-btn bz-btn-secondary">
          <i className="bi bi-credit-card" aria-hidden="true" />
          <span>Manage payment methods</span>
        </Link>
      </div>
    </div>
  );
}
