'use client';

import { useState } from 'react';

import { useAcceptJs } from '@/hooks';
import { addCard, type AddCardPayload, type ApiEnvelope, type PaymentCard } from '@/services/payment-cards/payment-cards.client';
import {
  brandOf,
  cvcLengthFor,
  digitsOnly,
  formatCardNumber,
  formatExpiry,
  isExpired,
  isValidCardNumber,
  parseExpiry,
  SUPPORTED_BRANDS,
  BRAND_LABEL,
} from '@/services/payment-cards/card-utils';
import BillingAddressFields, {
  validateNewAddress,
  type AddressMode,
  type BillingAddressValue,
} from './BillingAddressFields';

type Field = 'name' | 'number' | 'expiry' | 'cvc' | 'line1' | 'city' | 'region' | 'postal';

interface AddCardFormProps {
  token: string;
  /** The company's stored business address, for "Use company address" — null if somehow unset, in which case that option isn't offered. */
  companyAddress: string | null;
  /** Parent just refetches the whole list on success — no need to hand the new row back. */
  onAdded: () => void;
  /**
   * Defaults to the admin `addCard` (POST /business/payment-cards). The
   * employee direct-booking dialog (LEIS-1010) passes its own function
   * pointed at the employee-scoped route instead — same request/response
   * shape, same Accept.js tokenization, different endpoint/auth.
   */
  submit?: (payload: AddCardPayload, token: string) => Promise<ApiEnvelope<PaymentCard>>;
}

/**
 * LEIS-969: card number/expiry/CVC are tokenized through Accept.js
 * (useAcceptJs — already in this app, reused as-is) before anything is sent
 * to our own server; the request body below only ever carries the resulting
 * opaque token, never the raw digits. Field markup/copy/validation ported
 * from the design's own biz-cards.js (formFields/validateNew), with the
 * billing-address section simplified to the ticket's literal two-option
 * spec ("the company address, or a new one") rather than the design's own
 * richer N-saved-addresses picker — this app has one company address on
 * file to offer, not several past cards' worth.
 */
export default function AddCardForm({ token, companyAddress, onAdded, submit = addCard }: AddCardFormProps) {
  const { getOpaqueData } = useAcceptJs();

  const [nameOnCard, setNameOnCard] = useState('');
  const [cardNumber, setCardNumber] = useState('');
  const [expiry, setExpiry] = useState('');
  const [cvc, setCvc] = useState('');
  const [addressMode, setAddressMode] = useState<AddressMode>(companyAddress ? 'company' : 'new');
  const [address, setAddress] = useState<BillingAddressValue>({ line1: '', city: '', region: '', postal: '', country: 'US' });
  const [setAsDefault, setSetAsDefault] = useState(false);

  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));

  function validate(): Partial<Record<Field, string>> {
    const err: Partial<Record<Field, string>> = {};
    if (!nameOnCard.trim()) err.name = 'Enter the name on the card.';

    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 card has expired.';

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

    return { ...err, ...validateNewAddress(addressMode, address) };
  }

  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 billingAddress: AddCardPayload['billingAddress'] =
        addressMode === 'company'
          ? { line1: companyAddress ?? '' }
          : { line1: address.line1.trim(), city: address.city.trim(), region: address.region.trim(), postal: address.postal.trim(), country: address.country };

      const res = await submit(
        {
          opaqueData,
          brand,
          last4: digits.slice(-4),
          expMonth: exp.month,
          expYear: exp.year,
          nameOnCard: nameOnCard.trim(),
          billingAddress,
          setDefault: setAsDefault,
        },
        token,
      );

      if (!res.success || !res.data) {
        setServerError(res.message ?? 'We could not save this card. Please check the details and try again.');
        return;
      }

      onAdded();
      setNameOnCard('');
      setCardNumber('');
      setExpiry('');
      setCvc('');
      setSetAsDefault(false);
      if (addressMode === 'new') {
        setAddress({ line1: '', city: '', region: '', postal: '', country: 'US' });
      }
    } catch (err) {
      // Accept.js itself failing (not loaded, declined, bad data) lands here —
      // same message slot as a server-side rejection.
      setServerError(err instanceof Error ? err.message : 'We could not verify this card. Please try again.');
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <aside className="bz-card pm-add" aria-labelledby="pmAddTitle">
      <div className="pm-add-head">
        <h2 className="bz-card-title" id="pmAddTitle">
          Add a new card
        </h2>
        <p className="bz-card-sub">Visa, Mastercard, American Express and Discover accepted.</p>
      </div>
      <form className="pm-form" noValidate onSubmit={handleSubmit}>
        <div className="bc-field">
          <label className="bz-label" htmlFor="pmName">
            Name on card
          </label>
          <input
            type="text"
            className={`bz-input${errors.name ? ' is-invalid' : ''}`}
            id="pmName"
            autoComplete="cc-name"
            placeholder="Full name"
            maxLength={60}
            value={nameOnCard}
            onChange={(e) => {
              setNameOnCard(e.target.value);
              clearError('name');
            }}
          />
          {errors.name && <span className="bz-error">{errors.name}</span>}
        </div>

        <div className="bc-field">
          <label className="bz-label" htmlFor="pmNumber">
            Card number
          </label>
          <div className="bc-num">
            <input
              type="text"
              className={`bz-input${errors.number ? ' is-invalid' : ''}`}
              id="pmNumber"
              inputMode="numeric"
              autoComplete="cc-number"
              placeholder="1234 1234 1234 1234"
              maxLength={19}
              value={cardNumber}
              onChange={(e) => {
                setCardNumber(formatCardNumber(e.target.value));
                clearError('number');
              }}
            />
            {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="pmExp">
              Expiry date
            </label>
            <input
              type="text"
              className={`bz-input${errors.expiry ? ' is-invalid' : ''}`}
              id="pmExp"
              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="pmCvc">
              Security code
            </label>
            <input
              type="text"
              className={`bz-input${errors.cvc ? ' is-invalid' : ''}`}
              id="pmCvc"
              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>

        <BillingAddressFields
          idPrefix="pm"
          companyAddress={companyAddress}
          mode={addressMode}
          onModeChange={setAddressMode}
          value={address}
          onChange={setAddress}
          errors={errors}
          onClearError={clearError}
        />

        <label className="bz-check bc-check">
          <input type="checkbox" checked={setAsDefault} onChange={(e) => setSetAsDefault(e.target.checked)} />
          <span>Set as default payment method</span>
        </label>

        {serverError && <p className="bz-error">{serverError}</p>}

        <button type="submit" className="bz-btn bz-btn-primary pm-save" disabled={submitting}>
          {submitting ? 'Saving…' : 'Save card'}
        </button>
        <p className="pm-form-note">You won&rsquo;t be charged now. We may place a temporary hold to verify the card.</p>
      </form>
    </aside>
  );
}
