'use client';

import { useState } from 'react';

import { removeCard, type PaymentCard } from '@/services/payment-cards/payment-cards.client';
import { BRAND_LABEL, type CardBrand } from '@/services/payment-cards/card-utils';

interface RemoveCardModalProps {
  token: string;
  card: PaymentCard;
  /** Label of the card that will become default next, if this one is the current default and another valid card exists — matches the design's own removeModal copy. */
  nextDefaultLabel: string | null;
  onClose: () => void;
  onRemoved: () => void;
}

/** LEIS-968 "Remove", with a confirmation step (the ticket's own explicit requirement). */
export default function RemoveCardModal({ token, card, nextDefaultLabel, onClose, onRemoved }: RemoveCardModalProps) {
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const label = `${BRAND_LABEL[card.brand as CardBrand] ?? card.brand} ending in ${card.last4}`;

  const handleRemove = async () => {
    setSubmitting(true);
    setError(null);
    const res = await removeCard(card.id, token);
    setSubmitting(false);
    if (!res.success) {
      setError(res.message ?? 'We could not remove this card. Please try again.');
      return;
    }
    onRemoved();
  };

  return (
    <div className="bz-overlay" onClick={() => !submitting && onClose()}>
      <div className="bz-modal" style={{ maxWidth: 460 }} onClick={(e) => e.stopPropagation()}>
        <div className="bz-modal-head">
          <span className="bz-icon-tile tone-coral" aria-hidden="true">
            <i className="bi bi-trash3" />
          </span>
          <div>
            <h3 className="bz-modal-title">Remove {label}?</h3>
            <p className="bz-modal-sub">
              You won&rsquo;t be able to use it at checkout.
              {card.isDefault && nextDefaultLabel ? ` ${nextDefaultLabel} will become your default card.` : ''}
            </p>
          </div>
        </div>
        {error && (
          <div className="bz-modal-body">
            <p className="bz-error">{error}</p>
          </div>
        )}
        <div className="bz-modal-foot">
          <button type="button" className="bz-btn bz-btn-secondary" onClick={onClose} disabled={submitting} autoFocus>
            Cancel
          </button>
          <button type="button" className="bz-btn bz-btn-danger" onClick={handleRemove} disabled={submitting}>
            {submitting ? 'Removing…' : 'Remove card'}
          </button>
        </div>
      </div>
    </div>
  );
}
