'use client';

import { useState } from 'react';

import { changeCardAddress, type PaymentCard } from '@/services/payment-cards/payment-cards.client';
import { BRAND_LABEL, type CardBrand } from '@/services/payment-cards/card-utils';
import BillingAddressFields, {
  validateNewAddress,
  type AddressMode,
  type BillingAddressErrors,
  type BillingAddressValue,
} from './BillingAddressFields';

interface ChangeAddressModalProps {
  token: string;
  card: PaymentCard;
  companyAddress: string | null;
  onClose: () => void;
  onChanged: () => void;
}

/** LEIS-968 "Change address" — pre-filled with the card's current billing address, editable or swappable for the company address. */
export default function ChangeAddressModal({ token, card, companyAddress, onClose, onChanged }: ChangeAddressModalProps) {
  const [mode, setMode] = useState<AddressMode>('new');
  const [value, setValue] = useState<BillingAddressValue>({
    line1: card.billingAddress.line1,
    city: card.billingAddress.city ?? '',
    region: card.billingAddress.region ?? '',
    postal: card.billingAddress.postal ?? '',
    country: card.billingAddress.country ?? 'US',
  });
  const [errors, setErrors] = useState<BillingAddressErrors>({});
  const [serverError, setServerError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const clearError = (f: keyof BillingAddressErrors) => setErrors((e) => (e[f] ? { ...e, [f]: undefined } : e));
  const label = `${BRAND_LABEL[card.brand as CardBrand] ?? card.brand} ending in ${card.last4}`;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const err = validateNewAddress(mode, value);
    setErrors(err);
    if (Object.keys(err).length > 0) return;

    setSubmitting(true);
    setServerError(null);
    const billingAddress =
      mode === 'company'
        ? { line1: companyAddress ?? '' }
        : { line1: value.line1.trim(), city: value.city.trim(), region: value.region.trim(), postal: value.postal.trim(), country: value.country };
    const res = await changeCardAddress(card.id, billingAddress, token);
    setSubmitting(false);
    if (!res.success) {
      setServerError(res.message ?? 'We could not update the billing address. Please try again.');
      return;
    }
    onChanged();
  };

  return (
    <div className="bz-overlay" onClick={() => !submitting && onClose()}>
      <form className="bz-modal" style={{ maxWidth: 520 }} 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-geo-alt" />
          </span>
          <div>
            <h3 className="bz-modal-title">Change billing address</h3>
            <p className="bz-modal-sub">For {label}. It must match the address your bank has for this card.</p>
          </div>
        </div>
        <div className="bz-modal-body">
          <BillingAddressFields
            idPrefix="bcAd"
            companyAddress={companyAddress}
            mode={mode}
            onModeChange={setMode}
            value={value}
            onChange={setValue}
            errors={errors}
            onClearError={clearError}
          />
          {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 ? 'Saving…' : 'Save address'}
          </button>
        </div>
      </form>
    </div>
  );
}
