// [REQ F5]  System płatności online – karta kredytowa, Google Pay, przelew bankowy, depozyt
// [REQ D4]  React Portals – modal montowany w #portal-root
import { useState } from 'react';
import { createPortal } from 'react-dom';
import { CreditCard, CheckCircle2, Loader2, X, Smartphone, Landmark } from 'lucide-react';
import styles from './PaymentModal.module.scss';

const makeTxnId = () => 'TXN-' + Math.random().toString(36).slice(2, 10).toUpperCase();

const fmtCard = (v) =>
  v.replace(/\D/g, '').slice(0, 16).replace(/(.{4})/g, '$1 ').trim();

const METHODS = [
  { id: 'card',         label: 'Card',         icon: CreditCard },
  { id: 'google-pay',   label: 'Google Pay',   icon: Smartphone },
  { id: 'bank',         label: 'Bank Transfer', icon: Landmark },
];

const CardForm = ({ phase, onPay, deposit }) => {
  const [card, setCard]     = useState('');
  const [expiry, setExpiry] = useState('');
  const [cvv, setCvv]       = useState('');
  const [name, setName]     = useState('');
  const [errs, setErrs]     = useState({});

  const validate = () => {
    const e = {};
    if (!/^\d{16}$/.test(card.replace(/\s/g, '')))
      e.card = 'Enter a valid 16-digit card number.';
    if (!/^\d{2}\/\d{2}$/.test(expiry))
      e.expiry = 'Enter expiry as MM/YY.';
    if (!/^\d{3,4}$/.test(cvv))
      e.cvv = 'Enter a 3–4 digit CVV.';
    if (!name.trim())
      e.name = 'Cardholder name is required.';
    setErrs(e);
    return Object.keys(e).length === 0;
  };

  const handleExpiry = (v) => {
    let digits = v.replace(/\D/g, '').slice(0, 4);
    if (digits.length > 2) digits = digits.slice(0, 2) + '/' + digits.slice(2);
    setExpiry(digits);
  };

  return (
    <div className={styles['pay__form']}>
      <div className={styles['pay__field']}>
        <label className={styles['pay__label']}>Card Number</label>
        <input
          className={[styles['pay__input'], errs.card ? styles['pay__input--error'] : ''].join(' ')}
          placeholder="1234 5678 9012 3456"
          value={card}
          maxLength={19}
          onChange={(e) => setCard(fmtCard(e.target.value))}
          disabled={phase === 'processing'}
        />
        {errs.card && <p className={styles['pay__error']}>{errs.card}</p>}
      </div>

      <div className={styles['pay__row']}>
        <div className={styles['pay__field']}>
          <label className={styles['pay__label']}>Expiry</label>
          <input
            className={[styles['pay__input'], errs.expiry ? styles['pay__input--error'] : ''].join(' ')}
            placeholder="MM/YY"
            value={expiry}
            maxLength={5}
            onChange={(e) => handleExpiry(e.target.value)}
            disabled={phase === 'processing'}
          />
          {errs.expiry && <p className={styles['pay__error']}>{errs.expiry}</p>}
        </div>
        <div className={styles['pay__field']}>
          <label className={styles['pay__label']}>CVV</label>
          <input
            className={[styles['pay__input'], errs.cvv ? styles['pay__input--error'] : ''].join(' ')}
            placeholder="•••"
            type="password"
            value={cvv}
            maxLength={4}
            onChange={(e) => setCvv(e.target.value.replace(/\D/g, '').slice(0, 4))}
            disabled={phase === 'processing'}
          />
          {errs.cvv && <p className={styles['pay__error']}>{errs.cvv}</p>}
        </div>
      </div>

      <div className={styles['pay__field']}>
        <label className={styles['pay__label']}>Cardholder Name</label>
        <input
          className={[styles['pay__input'], errs.name ? styles['pay__input--error'] : ''].join(' ')}
          placeholder="John Smith"
          value={name}
          onChange={(e) => setName(e.target.value)}
          disabled={phase === 'processing'}
        />
        {errs.name && <p className={styles['pay__error']}>{errs.name}</p>}
      </div>

      <button
        className={styles['pay__pay-btn']}
        onClick={() => validate() && onPay()}
        disabled={phase === 'processing'}
      >
        {phase === 'processing'
          ? <><Loader2 size={16} className={styles['pay__spinner']} /> Processing…</>
          : `Pay Deposit $${deposit.toFixed(2)}`
        }
      </button>
      <p className={styles['pay__secure-note']}>
        Simulated payment — no real transaction will occur.
      </p>
    </div>
  );
};

const GooglePayForm = ({ phase, onPay, deposit }) => (
  <div className={styles['pay__form']}>
    <div className={styles['pay__gpay-preview']}>
      <div className={styles['pay__gpay-logo']}>
        <span style={{ color: '#4285F4', fontWeight: 700 }}>G</span>
        <span style={{ color: '#EA4335', fontWeight: 700 }}>o</span>
        <span style={{ color: '#FBBC05', fontWeight: 700 }}>o</span>
        <span style={{ color: '#4285F4', fontWeight: 700 }}>g</span>
        <span style={{ color: '#34A853', fontWeight: 700 }}>l</span>
        <span style={{ color: '#EA4335', fontWeight: 700 }}>e</span>
        <span style={{ marginLeft: 4, fontWeight: 700 }}> Pay</span>
      </div>
      <p className={styles['pay__gpay-account']}>krzysztofcieslik875@gmail.com</p>
      <p className={styles['pay__gpay-card']}>Visa •••• 4242</p>
    </div>
    <button
      className={[styles['pay__pay-btn'], styles['pay__pay-btn--gpay']].join(' ')}
      onClick={onPay}
      disabled={phase === 'processing'}
    >
      {phase === 'processing'
        ? <><Loader2 size={16} className={styles['pay__spinner']} /> Processing…</>
        : <><span style={{ fontWeight: 700 }}>G</span> Pay ${deposit.toFixed(2)}</>
      }
    </button>
    <p className={styles['pay__secure-note']}>
      Simulated payment — no real transaction will occur.
    </p>
  </div>
);

const BankTransferForm = ({ phase, onPay, deposit }) => (
  <div className={styles['pay__form']}>
    <div className={styles['pay__bank-info']}>
      <p className={styles['pay__bank-label']}>Transfer details</p>
      <div className={styles['pay__bank-row']}>
        <span>Account name</span><span>Reservation Services Sp. z o.o.</span>
      </div>
      <div className={styles['pay__bank-row']}>
        <span>IBAN</span><span className={styles['pay__bank-mono']}>PL61 1090 1014 0000 0712 1981 2874</span>
      </div>
      <div className={styles['pay__bank-row']}>
        <span>BIC/SWIFT</span><span className={styles['pay__bank-mono']}>WBKPPLPP</span>
      </div>
      <div className={[styles['pay__bank-row'], styles['pay__bank-row--total']].join(' ')}>
        <span>Amount due</span><span>${deposit.toFixed(2)}</span>
      </div>
    </div>
    <div className={styles['pay__field']}>
      <label className={styles['pay__label']}>Reference / Transfer title</label>
      <input
        className={styles['pay__input']}
        defaultValue={`Deposit reservation`}
        disabled={phase === 'processing'}
      />
    </div>
    <button
      className={styles['pay__pay-btn']}
      onClick={onPay}
      disabled={phase === 'processing'}
    >
      {phase === 'processing'
        ? <><Loader2 size={16} className={styles['pay__spinner']} /> Processing…</>
        : `Confirm Transfer $${deposit.toFixed(2)}`
      }
    </button>
    <p className={styles['pay__secure-note']}>
      Simulated payment — no real transaction will occur.
    </p>
  </div>
);

const PaymentModal = ({ isOpen, onClose, onSuccess, service, date, time }) => {
  const [method, setMethod] = useState('card');
  const [phase, setPhase]   = useState('idle'); // 'idle' | 'processing' | 'done'

  const deposit = service ? +(service.price * 0.5).toFixed(2) : 0;

  if (!isOpen) return null;

  const handlePay = () => {
    setPhase('processing');
    setTimeout(() => {
      const txn = { amount: deposit, transactionId: makeTxnId(), method };
      setPhase('done');
      onSuccess?.(txn);
    }, 1500);
  };

  const portalRoot = document.getElementById('portal-root') ?? document.body;

  return createPortal(
    <div className={styles['pay']} role="dialog" aria-modal="true" aria-label="Secure payment">
      <div
        className={styles['pay__overlay']}
        onClick={phase !== 'processing' ? onClose : undefined}
      />
      <div className={styles['pay__panel']}>
        {/* Header */}
        <div className={styles['pay__header']}>
          <div className={styles['pay__header-left']}>
            <CreditCard size={20} className={styles['pay__header-icon']} />
            <h2 className={styles['pay__title']}>Secure Payment</h2>
          </div>
          {phase !== 'processing' && (
            <button className={styles['pay__close']} onClick={onClose} aria-label="Close">
              <X size={18} />
            </button>
          )}
        </div>

        {/* Booking summary */}
        <div className={styles['pay__summary']}>
          <p className={styles['pay__summary-label']}>Booking Summary</p>
          <div className={styles['pay__summary-row']}>
            <span>{service?.name}</span>
            <span>${service?.price}</span>
          </div>
          <div className={styles['pay__summary-row']}>
            <span>{date} at {time}</span>
          </div>
          <div className={[styles['pay__summary-row'], styles['pay__summary-row--total']].join(' ')}>
            <span>Deposit Due (50%)</span>
            <span className={styles['pay__deposit-amt']}>${deposit.toFixed(2)}</span>
          </div>
        </div>

        {/* Done state */}
        {phase === 'done' ? (
          <div className={styles['pay__done']}>
            <CheckCircle2 size={44} className={styles['pay__done-icon']} />
            <p className={styles['pay__done-title']}>Payment successful!</p>
            <p className={styles['pay__done-sub']}>Creating your reservation…</p>
          </div>
        ) : (
          <>
            {/* Payment method tabs */}
            <div className={styles['pay__methods']}>
              {METHODS.map(({ id, label, icon: Icon }) => (
                <button
                  key={id}
                  className={[styles['pay__method-btn'], method === id ? styles['pay__method-btn--active'] : ''].join(' ')}
                  onClick={() => setMethod(id)}
                  disabled={phase === 'processing'}
                >
                  <Icon size={15} /> {label}
                </button>
              ))}
            </div>

            {method === 'card' && (
              <CardForm phase={phase} onPay={handlePay} deposit={deposit} />
            )}
            {method === 'google-pay' && (
              <GooglePayForm phase={phase} onPay={handlePay} deposit={deposit} />
            )}
            {method === 'bank' && (
              <BankTransferForm phase={phase} onPay={handlePay} deposit={deposit} />
            )}
          </>
        )}
      </div>
    </div>,
    portalRoot
  );
};

export default PaymentModal;
