'use client';

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

import { decodeBusinessJwt, getActiveBusinessSession, getBusinessAccessToken } from '@/lib/business-session';
import { toast } from '@/lib/toast';
import { listCards, makeDefaultCard, type CardsListResult, type PaymentCard } from '@/services/payment-cards/payment-cards.client';
import { BRAND_LABEL, isExpired, type CardBrand } from '@/services/payment-cards/card-utils';

import AddCardForm from './AddCardForm';
import UpdateCardModal from './UpdateCardModal';
import ChangeAddressModal from './ChangeAddressModal';
import RemoveCardModal from './RemoveCardModal';
import { ADMIN_HOME, EMPLOYEE_HOME } from '@/constants/business-routes';

/**
 * Payment methods (LEIS-967/968/969) — admin-only, same gate as Workforce/
 * the Approval queue (plain useState+useEffect; this app deliberately
 * doesn't use a fancier external-store hook here, see WorkforcePage's own
 * history).
 *
 * Per-card actions match the design's own row-action set: Make default
 * (non-default, non-expired cards only — fires immediately, no modal, same
 * as the design's own demo), Update (expired cards only — a modal, since it
 * needs a full re-tokenized card, see UpdateCardModal's own doc comment),
 * Change address (always) and Remove (always, with a confirmation step —
 * the ticket's own explicit requirement, where the design's own demo just
 * fires immediately).
 */
export default function PaymentMethodsPage() {
  const router = useRouter();
  const [authorised, setAuthorised] = useState(false);
  const [token, setToken] = useState<string | null>(null);

  const [cards, setCards] = useState<PaymentCard[]>([]);
  const [companyAddress, setCompanyAddress] = useState<string | null>(null);
  const [loaded, setLoaded] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);

  const [makingDefaultId, setMakingDefaultId] = useState<string | null>(null);
  const [updateTarget, setUpdateTarget] = useState<PaymentCard | null>(null);
  const [addressTarget, setAddressTarget] = useState<PaymentCard | null>(null);
  const [removeTarget, setRemoveTarget] = useState<PaymentCard | 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]);

  useEffect(() => {
    if (!authorised || !token) return;
    async function run() {
      const res = await listCards(token!);
      if (res.success && res.data) {
        const data: CardsListResult = res.data;
        setCards(data.cards);
        setCompanyAddress(data.companyAddress);
      }
      setLoaded(true);
    }
    run();
  }, [authorised, token, refreshKey]);

  const refreshAll = () => setRefreshKey((k) => k + 1);
  const onAdded = () => refreshAll();

  const doMakeDefault = async (card: PaymentCard) => {
    if (!token) return;
    setMakingDefaultId(card.id);
    const res = await makeDefaultCard(card.id, token);
    setMakingDefaultId(null);
    if (!res.success) {
      toast.error(res.message ?? 'Could not make this your default card.');
      return;
    }
    toast.success(`${BRAND_LABEL[card.brand as CardBrand] ?? card.brand} ending in ${card.last4} is now your default card.`);
    refreshAll();
  };

  const onUpdated = () => {
    setUpdateTarget(null);
    toast.success('Card updated.');
    refreshAll();
  };
  const onAddressChanged = () => {
    setAddressTarget(null);
    toast.success('Billing address updated.');
    refreshAll();
  };
  const onRemoved = () => {
    setRemoveTarget(null);
    toast.success('Card removed.');
    refreshAll();
  };

  if (!authorised) return null;

  const defaultCard = cards.find((c) => c.isDefault) ?? null;

  /** For RemoveCardModal's "X will become your default" copy — same not-expired check as the backend's own promotion logic. */
  function nextDefaultLabelFor(excluding: PaymentCard): string | null {
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth() + 1;
    const candidates = cards
      .filter((c) => c.id !== excluding.id)
      .filter((c) => c.expYear > currentYear || (c.expYear === currentYear && c.expMonth >= currentMonth))
      .sort((a, b) => new Date(b.addedAt).getTime() - new Date(a.addedAt).getTime());
    const next = candidates[0];
    return next ? `${BRAND_LABEL[next.brand as CardBrand] ?? next.brand} ending in ${next.last4}` : null;
  }

  return (
    <section className="bz-ui bz-page pm-page">
      <div className="mx-auto w-full max-w-[1320px] px-3">
        <section className="bz-hero">
          <div className="bz-hero-text">
            <ol className="bz-crumbs">
              <li>
                <Link href={ADMIN_HOME}>Admin</Link>
              </li>
              <li>
                <Link href="/admin/flight-approvals">Corporate Travel</Link>
              </li>
              <li aria-current="page">Payment methods</li>
            </ol>
            <h1 className="bz-hero-title">Payment methods</h1>
            <p className="bz-hero-sub">
              Save company cards for faster checkout when you approve travel. Your default card is selected first at checkout.
            </p>
          </div>
          <div className="bz-hero-actions">
            <Link href="/admin/flight-approvals" className="bz-btn bz-btn-lg bz-btn-glass">
              <i className="bi bi-list-check" />
              <span>Approval queue</span>
            </Link>
          </div>
        </section>

        <div className="pm-layout">
          <section className="bz-card pm-saved" aria-labelledby="pmSavedTitle">
            <div className="bz-card-head">
              <div>
                <h2 className="bz-card-title" id="pmSavedTitle">
                  Saved cards
                </h2>
                <p className="bz-card-sub">Used to pay for approved travel.</p>
              </div>
              {loaded && <span className="pm-count">{cards.length} {cards.length === 1 ? 'card' : 'cards'}</span>}
            </div>

            {defaultCard && (
              <div className="pm-visual-wrap" aria-hidden="true">
                <div className={`pm-visual is-${defaultCard.brand}`}>
                  <div className="pm-visual-top">
                    <b>{BRAND_LABEL[defaultCard.brand as CardBrand] ?? defaultCard.brand}</b>
                    <span className="pm-visual-tag">Default</span>
                  </div>
                  <span className="pm-visual-chip" />
                  <div className="pm-visual-num">•••• •••• •••• {defaultCard.last4}</div>
                  <div className="pm-visual-foot">
                    <span>{defaultCard.nameOnCard}</span>
                    <span>
                      {String(defaultCard.expMonth).padStart(2, '0')}/{String(defaultCard.expYear).slice(-2)}
                    </span>
                  </div>
                </div>
              </div>
            )}

            <ul className="pm-list" aria-live="polite">
              {!loaded ? null : cards.length === 0 ? (
                <li className="pm-empty">
                  <i className="bi bi-credit-card" />
                  <strong>No saved cards yet</strong>
                  <span>Add a card to pay for approved travel.</span>
                </li>
              ) : (
                cards.map((card) => {
                  const expired = isExpired(card.expMonth, card.expYear);
                  const brandLabel = BRAND_LABEL[card.brand as CardBrand] ?? card.brand;
                  return (
                    <li key={card.id} className={`pm-card${card.isDefault ? ' is-default' : ''}${expired ? ' is-expired' : ''}`}>
                      <span className={`bc-tile is-${card.brand}`} aria-hidden="true">
                        <b>{brandLabel.toUpperCase()}</b>
                        <i>•• {card.last4}</i>
                      </span>
                      <div className="pm-card-text">
                        <strong>
                          {brandLabel} ending in {card.last4}
                          {card.isDefault && <span className="bz-badge">Default</span>}
                          {!card.isDefault && expired && <span className="bz-badge is-warn">Expired</span>}
                        </strong>
                        <small>
                          {expired ? 'Expired' : 'Expires'} {String(card.expMonth).padStart(2, '0')}/{String(card.expYear).slice(-2)} · {card.nameOnCard}
                        </small>
                        <small className="pm-card-addr">
                          <i className="bi bi-geo-alt" aria-hidden="true" />
                          {[card.billingAddress.line1, card.billingAddress.city, card.billingAddress.region, card.billingAddress.postal]
                            .filter(Boolean)
                            .join(', ') || '—'}
                        </small>
                      </div>
                      <div className="pm-card-actions">
                        {!card.isDefault && !expired && (
                          <button
                            type="button"
                            className="bz-btn bz-btn-secondary bz-btn-sm"
                            disabled={makingDefaultId === card.id}
                            onClick={() => doMakeDefault(card)}
                          >
                            {makingDefaultId === card.id ? 'Setting…' : 'Make default'}
                          </button>
                        )}
                        {expired && (
                          <button type="button" className="bz-btn bz-btn-secondary bz-btn-sm" onClick={() => setUpdateTarget(card)}>
                            Update
                          </button>
                        )}
                        <button
                          type="button"
                          className="bz-link"
                          aria-label={`Change billing address for ${brandLabel} ending in ${card.last4}`}
                          onClick={() => setAddressTarget(card)}
                        >
                          Change address
                        </button>
                        <button
                          type="button"
                          className="bz-link is-danger"
                          aria-label={`Remove ${brandLabel} ending in ${card.last4}`}
                          onClick={() => setRemoveTarget(card)}
                        >
                          Remove
                        </button>
                      </div>
                    </li>
                  );
                })
              )}
            </ul>
            <p className="pm-secure">
              <i className="bi bi-lock" aria-hidden="true" />
              Card details are encrypted and processed by our payment provider. We only keep the card brand, last 4 digits, expiry date and
              billing address.
            </p>
          </section>

          {/* Gated on `loaded`, not just `token`: AddCardForm's "Use company
              address" default is a useState lazy initializer keyed off
              `companyAddress`, which only runs once on mount — mounting
              before that prop's real value has arrived from the list fetch
              would permanently default to "Enter a new address" even when a
              company address exists. */}
          {token && loaded && <AddCardForm token={token} companyAddress={companyAddress} onAdded={onAdded} />}
        </div>
      </div>

      {token && updateTarget && <UpdateCardModal token={token} card={updateTarget} onClose={() => setUpdateTarget(null)} onUpdated={onUpdated} />}
      {token && addressTarget && (
        <ChangeAddressModal
          token={token}
          card={addressTarget}
          companyAddress={companyAddress}
          onClose={() => setAddressTarget(null)}
          onChanged={onAddressChanged}
        />
      )}
      {token && removeTarget && (
        <RemoveCardModal
          token={token}
          card={removeTarget}
          nextDefaultLabel={nextDefaultLabelFor(removeTarget)}
          onClose={() => setRemoveTarget(null)}
          onRemoved={onRemoved}
        />
      )}
    </section>
  );
}
