// Payment Links — Stripe checkout links that belong to this account
// (RepoWireModal's sibling). Managers/admins create and deactivate; any rep
// with account access can view and copy. When the customer pays, the Stripe
// poller drops it on the timeline and opens an urgent follow-up task.

const PaymentLinksModal = ({ accountId, accountName, isManager, onClose }) => {
    const [links, setLinks]     = React.useState(null);   // null = loading
    const [error, setError]     = React.useState('');
    const [showNew, setShowNew] = React.useState(false);
    const [form, setForm]       = React.useState({ description: '', amount: '', recurring: true, interval: 'month' });
    const [saving, setSaving]   = React.useState(false);
    const [copied, setCopied]   = React.useState(null);

    const refresh = () => api.getPaymentLinks(accountId).then(setLinks).catch(e => setError(e.message));
    React.useEffect(() => { refresh(); }, [accountId]);

    const handleCreate = async (e) => {
        e.preventDefault();
        setSaving(true); setError('');
        try {
            await api.createPaymentLink({
                account_id: accountId,
                description: form.description.trim(),
                amount: parseFloat(form.amount),
                interval: form.recurring ? form.interval : null,
            });
            setShowNew(false);
            setForm({ description: '', amount: '', recurring: true, interval: 'month' });
            refresh();
        } catch (err) { setError(err.message); }
        finally { setSaving(false); }
    };

    const handleDeactivate = async (link) => {
        if (!window.confirm(`Deactivate "${link.description}"? The link stops accepting new payments. Existing subscriptions are NOT cancelled — manage those in Stripe.`)) return;
        try { await api.deactivatePaymentLink(link.id); refresh(); }
        catch (err) { setError(err.message); }
    };

    const copyUrl = (link) => {
        navigator.clipboard?.writeText(link.url)
            .then(() => { setCopied(link.id); setTimeout(() => setCopied(null), 1500); })
            .catch(() => window.prompt('Copy the link:', link.url));
    };

    const money = (n) => `$${Number(n).toFixed(2)}`;
    const per = (l) => l.kind === 'subscription' ? (l.billing_interval === 'year' ? '/yr' : '/mo') : '';

    return (
        <Modal isOpen={true} onClose={onClose} title={`Payment Links — ${accountName}`}>
            {error && <div className="api-error">{error}</div>}

                    {links === null ? <p style={{ color: 'var(--text-3)' }}>Loading…</p> : (
                        links.length === 0 && !showNew ? (
                            <p style={{ color: 'var(--text-3)', fontSize: '0.875rem' }}>
                                No payment links yet. Create one and send it to the customer — when they
                                pay, it lands on the timeline and opens a follow-up task automatically.
                            </p>
                        ) : (
                            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem', marginBottom: '0.75rem' }}>
                                {links.map(l => (
                                    <div key={l.id} className="detail-info-card" style={{ display: 'flex', alignItems: 'center', gap: '0.75rem', opacity: l.status === 'deactivated' ? 0.55 : 1 }}>
                                        <div style={{ flex: 1 }}>
                                            <div style={{ fontWeight: 600 }}>
                                                {l.description}
                                                <span style={{ marginLeft: '0.5rem', color: 'var(--accent, #3b82f6)' }}>{money(l.amount)}{per(l)}</span>
                                            </div>
                                            <div style={{ fontSize: '0.75rem', color: 'var(--text-3)', marginTop: '0.15rem' }}>
                                                {l.status === 'deactivated' ? 'Deactivated' :
                                                 l.first_paid_at ? `Paid — first payment ${new Date(l.first_paid_at).toLocaleDateString()}` : 'Awaiting payment'}
                                            </div>
                                        </div>
                                        {l.status === 'active' && (
                                            <button className="btn btn-secondary btn-small" onClick={() => copyUrl(l)}>
                                                <i className={copied === l.id ? 'fas fa-check' : 'fas fa-copy'}></i> {copied === l.id ? 'Copied' : 'Copy link'}
                                            </button>
                                        )}
                                        {isManager && l.status === 'active' && (
                                            <button className="btn-icon-sm danger" title="Deactivate link" onClick={() => handleDeactivate(l)}>
                                                <i className="fas fa-ban"></i>
                                            </button>
                                        )}
                                    </div>
                                ))}
                            </div>
                        )
                    )}

                    {isManager && !showNew && (
                        <button className="btn btn-primary btn-small" onClick={() => setShowNew(true)}>
                            <i className="fas fa-plus"></i> New Payment Link
                        </button>
                    )}

                    {showNew && (
                        <form onSubmit={handleCreate} className="detail-info-card">
                            <div className="form-group">
                                <label className="form-label">What is this for? *</label>
                                <input className="form-input" value={form.description} maxLength={255} required
                                       placeholder="e.g. Website hosting — example.com"
                                       onChange={e => setForm(p => ({ ...p, description: e.target.value }))} />
                                <p style={{ fontSize: '0.75rem', color: 'var(--text-3)', marginTop: '0.35rem' }}>
                                    The customer sees this on the Stripe checkout page and their receipt.
                                </p>
                            </div>
                            <div style={{ display: 'flex', gap: '1rem', alignItems: 'flex-end' }}>
                                <div className="form-group" style={{ flex: 1 }}>
                                    <label className="form-label">Amount (USD) *</label>
                                    <input className="form-input" type="number" min="0.50" step="0.01" required
                                           value={form.amount} placeholder="45.00"
                                           onChange={e => setForm(p => ({ ...p, amount: e.target.value }))} />
                                </div>
                                <div className="form-group" style={{ flex: 1 }}>
                                    <label className="form-label">Billing</label>
                                    {/* chips, not checkboxes (house rule) */}
                                    <div className="tag-filter-row">
                                        {[['month', 'Monthly'], ['year', 'Yearly'], [null, 'One-time']].map(([val, lbl]) => {
                                            const active = form.recurring ? form.interval === val : val === null;
                                            return (
                                                <span key={lbl} className="tag-pill tag-filter-chip"
                                                      style={active ? { background: 'var(--accent, #3b82f6)', color: '#fff' } : {}}
                                                      onClick={() => setForm(p => ({ ...p, recurring: val !== null, interval: val || p.interval }))}>
                                                    {lbl}
                                                </span>
                                            );
                                        })}
                                    </div>
                                </div>
                            </div>
                            <div style={{ display: 'flex', gap: '0.5rem' }}>
                                <button type="submit" className="btn btn-primary btn-small" disabled={saving || !form.description.trim() || !form.amount}>
                                    {saving ? <><i className="fas fa-spinner fa-spin"></i> Creating in Stripe…</> : <><i className="fas fa-link"></i> Create Link</>}
                                </button>
                                <button type="button" className="btn btn-secondary btn-small" onClick={() => setShowNew(false)}>Cancel</button>
                            </div>
                        </form>
            )}
        </Modal>
    );
};
