// Declare a milestone on an account — 'Onboarded', 'Contract signed',
// 'Website live'. Types come from the admin-managed vocabulary
// (Settings → Milestones), picked as chips per the no-checkbox rule.
// The event snapshots the type's name/color server-side, so later
// vocabulary edits never rewrite the account's history.
const MilestoneModal = ({ accountId, onClose, onCreated }) => {
    const [types, setTypes]         = React.useState(null); // null = loading
    const [typeId, setTypeId]       = React.useState(null);
    const [when, setWhen]           = React.useState(new Date().toISOString().slice(0, 10));
    const [note, setNote]           = React.useState('');
    const [saving, setSaving]       = React.useState(false);

    React.useEffect(() => {
        api.getMilestoneTypes().then(setTypes).catch(() => setTypes([]));
    }, []);

    const handleSave = async (e) => {
        e.preventDefault();
        if (!typeId) return;
        setSaving(true);
        try {
            // Date input gives a local calendar day; send it as local noon so
            // timezone conversion can't shift the milestone to the wrong day.
            const created = await api.createMilestone({
                account_id: accountId,
                milestone_type_id: typeId,
                occurred_at: new Date(`${when}T12:00:00`).toISOString(),
                note: note.trim() || undefined,
            });
            onCreated(created);
        } catch (err) {
            alert(err.message);
        } finally {
            setSaving(false);
        }
    };

    return (
        <Modal isOpen={true} onClose={onClose} title="Add Milestone">
            <form onSubmit={handleSave}>
                <div className="form-group">
                    <label className="form-label">Milestone</label>
                    {types === null ? (
                        <div className="loading-state"><i className="fas fa-spinner fa-spin"></i> Loading…</div>
                    ) : types.length === 0 ? (
                        <p style={{ fontSize: '0.875rem', color: 'var(--text-3)' }}>
                            No milestone types yet — a manager can create them in Settings → Milestones.
                        </p>
                    ) : (
                        <div className="tag-filter-row" style={{ marginTop: '0.25rem' }}>
                            {types.map(t => (
                                <span key={t.id}
                                      className="tag-pill tag-filter-chip"
                                      onClick={() => setTypeId(t.id)}
                                      style={{
                                          background: typeId === t.id ? t.color : t.color + '22',
                                          color: typeId === t.id ? '#fff' : t.color,
                                          border: `1px solid ${t.color}66`,
                                      }}>
                                    {t.name}
                                </span>
                            ))}
                        </div>
                    )}
                </div>
                <div className="form-group">
                    <label className="form-label">Date</label>
                    <input type="date" className="form-input" value={when} onChange={e => setWhen(e.target.value)} required />
                </div>
                <div className="form-group">
                    <label className="form-label">Note <span style={{ color: 'var(--text-3)', fontWeight: 400 }}>(optional)</span></label>
                    <textarea className="form-input" rows={2} maxLength={500} value={note}
                              onChange={e => setNote(e.target.value)}
                              placeholder="e.g. Signed the 12-month hosting agreement" />
                </div>
                <div className="modal-actions">
                    <button type="button" className="btn btn-secondary" onClick={onClose}>Cancel</button>
                    <button type="submit" className="btn btn-primary" disabled={saving || !typeId}>
                        {saving ? <><i className="fas fa-spinner fa-spin"></i> Saving…</> : <><i className="fas fa-flag"></i> Add Milestone</>}
                    </button>
                </div>
            </form>
        </Modal>
    );
};
