'use client';

import { useState } from 'react';

import { useAcceptJs } from '@/hooks';
import { renewCard, type PaymentCard } from '@/services/payment-cards/payment-cards.client';
import {
  brandOf,
  cvcLengthFor,
  digitsOnly,
  formatCardNumber,
  formatExpiry,
  isExpired,
  isValidCardNumber,
  parseExpiry,
  SUPPORTED_BRANDS,
  BRAND_LABEL,
  type CardBrand,
} from '@/services/payment-cards/card-utils';

type Field = 'number' | 'expiry' | 'cvc';

interface UpdateCardModalProps {
  token: string;
  card: PaymentCard;
  onClose: () => void;
  onUpdated: () => void;
}

/**
 * LEIS-968 "Update" — renew an expired card. The design's own demo dialog
 * only asks for a new expiry + CVC, but that's not actually achievable for
 * real: Accept.js tokenizes a complete card number, there is no "just the
 * expiry" token, and the provider never hands a stored card number back out
 * to resend it. The admin re-enters the full renewed card here, same as
 * adding a new one — a deliberate, necessary departure from the design's
 * simplified (non-functional) demo, not an oversight.
 */
export default function UpdateCardModal({ token, card, onClose, onUpdated }: UpdateCardModalProps) {
  const { getOpaqueData } = useAcceptJs();
  const [cardNumber, setCardNumber] = useState('');
  const [expiry, setExpiry] = useState('');
  const [cvc, setCvc] = useState('');
  const [errors, setErrors] = useState<Partial<Record<Field, string>>>({});
  const [serverError, setServerError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const brand = brandOf(cardNumber);
  const cvcLen = cvcLengthFor(brand);
  const clearError = (f: Field) => setErrors((e) => (e[f] ? { ...e, [f]: undefined } : e));
  const label = `${BRAND_LABEL[card.brand as CardBrand] ?? card.brand} ending in ${card.last4}`;

  function validate(): Partial<Record<Field, string>> {
    const err: Partial<Record<Field, string>> = {};
    const digits = digitsOnly(cardNumber);
    if (!digits) err.number = 'Enter the card number.';
    else if (!SUPPORTED_BRANDS.has(brand)) err.number = 'We accept Visa, Mastercard, American Express and Discover.';
    else if (!isValidCardNumber(digits)) err.number = "This card number isn't valid. Check it and try again.";

    const exp = parseExpiry(expiry);
    if (!digitsOnly(expiry)) err.expiry = 'Enter the expiry date.';
    else if (!exp) err.expiry = 'Use MM / YY.';
    else if (isExpired(exp.month, exp.year)) err.expiry = 'This date has already passed too.';

    if (!digitsOnly(cvc)) err.cvc = 'Enter the security code.';
    else if (digitsOnly(cvc).length !== cvcLen) err.cvc = `Enter the ${cvcLen}-digit code.`;
    return err;
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    const err = validate();
    setErrors(err);
    if (Object.keys(err).length > 0) return;

    setServerError(null);
    setSubmitting(true);
    try {
      const digits = digitsOnly(cardNumber);
      const exp = parseExpiry(expiry)!;
      const opaqueData = await getOpaqueData(digits, String(exp.month).padStart(2, '0'), String(exp.year), digitsOnly(cvc));
      const res = await renewCard(card.id, { opaqueData, brand, last4: digits.slice(-4), expMonth: exp.month, expYear: exp.year }, token);
      if (!res.success) {
        setServerError(res.message ?? 'We could not update this card. Please check the details and try again.');
        return;
      }
      onUpdated();
    } catch (err) {
      setServerError(err instanceof Error ? err.message : 'We could not verify this card. Please try again.');
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="bz-overlay" onClick={() => !submitting && onClose()}>
      <form className="bz-modal" style={{ maxWidth: 460 }} onClick={(e) => e.stopPropagation()} onSubmit={handleSubmit} noValidate>
        <div className="bz-modal-head">
          <span className="bz-icon-tile tone-navy" aria-hidden="true">
            <i className="bi bi-credit-card" />
          </span>
          <div>
            <h3 className="bz-modal-title">Update {label}</h3>
            <p className="bz-modal-sub">Enter the renewed card&rsquo;s details. The number, expiry and CVC are all re-verified.</p>
          </div>
        </div>
        <div className="bz-modal-body">
          <div className="bc-field">
            <label className="bz-label" htmlFor="ucNumber">
              Card number
            </label>
            <div className="bc-num">
              <input
                type="text"
                className={`bz-input${errors.number ? ' is-invalid' : ''}`}
                id="ucNumber"
                inputMode="numeric"
                autoComplete="cc-number"
                placeholder="1234 1234 1234 1234"
                maxLength={19}
                value={cardNumber}
                onChange={(e) => {
                  setCardNumber(formatCardNumber(e.target.value));
                  clearError('number');
                }}
                autoFocus
              />
              {brand !== 'card' && <span className={`bc-brand is-${brand}`}>{BRAND_LABEL[brand]}</span>}
              <i className="bi bi-lock-fill" aria-hidden="true" />
            </div>
            {errors.number && <span className="bz-error">{errors.number}</span>}
          </div>
          <div className="bc-row">
            <div className="bc-field">
              <label className="bz-label" htmlFor="ucExp">
                New expiry date
              </label>
              <input
                type="text"
                className={`bz-input${errors.expiry ? ' is-invalid' : ''}`}
                id="ucExp"
                inputMode="numeric"
                autoComplete="cc-exp"
                placeholder="MM / YY"
                maxLength={7}
                value={expiry}
                onChange={(e) => {
                  setExpiry(formatExpiry(e.target.value));
                  clearError('expiry');
                }}
              />
              {errors.expiry && <span className="bz-error">{errors.expiry}</span>}
            </div>
            <div className="bc-field">
              <label className="bz-label" htmlFor="ucCvc">
                Security code
              </label>
              <input
                type="text"
                className={`bz-input${errors.cvc ? ' is-invalid' : ''}`}
                id="ucCvc"
                inputMode="numeric"
                autoComplete="cc-csc"
                placeholder="CVC"
                maxLength={cvcLen}
                value={cvc}
                onChange={(e) => {
                  setCvc(digitsOnly(e.target.value).slice(0, cvcLen));
                  clearError('cvc');
                }}
              />
              {errors.cvc && <span className="bz-error">{errors.cvc}</span>}
            </div>
          </div>
          {serverError && <p className="bz-error">{serverError}</p>}
        </div>
        <div className="bz-modal-foot">
          <button type="button" className="bz-btn bz-btn-secondary" onClick={onClose} disabled={submitting}>
            Cancel
          </button>
          <button type="submit" className="bz-btn bz-btn-primary" disabled={submitting}>
            {submitting ? 'Updating…' : 'Update card'}
          </button>
        </div>
      </form>
    </div>
  );
}
