File size: 5,938 Bytes
240bbb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { getGroupDetail, createExpense } from '../api';

// VARIANT (screenshot2): deliberate visual quirks vs. golden:
//   - Summary panel above the form
//   - Amount field BEFORE Description (swapped)
//   - "Split among" members in a 2-column grid
//   - Primary "Add Expense" button on the LEFT, Cancel on the RIGHT (swapped)

export default function AddExpense() {
  const { groupId } = useParams();
  const navigate = useNavigate();
  const [group, setGroup] = useState(null);
  const [description, setDescription] = useState('');
  const [amount, setAmount] = useState('');
  const [paidBy, setPaidBy] = useState('');
  const [splitAmong, setSplitAmong] = useState([]);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    getGroupDetail(groupId)
      .then((g) => {
        setGroup(g);
        const members = g.members || [];
        setSplitAmong(members.map((m) => m.id));
        if (members.length > 0) setPaidBy(String(members[0].id));
      })
      .catch((e) => setError(e.message));
  }, [groupId]);

  function toggleSplit(id) {
    setSplitAmong((prev) =>
      prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]
    );
  }

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    if (!description.trim() || !amount || !paidBy) {
      setError('All fields are required');
      return;
    }
    if (splitAmong.length === 0) {
      setError('Select at least one person to split with');
      return;
    }
    setLoading(true);
    try {
      await createExpense(
        groupId,
        description.trim(),
        amount,
        parseInt(paidBy),
        splitAmong
      );
      navigate(`/groups/${groupId}`);
    } catch (e) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  }

  if (!group) {
    return error ? (
      <div className="error-msg">{error}</div>
    ) : (
      <div className="loading">Loading...</div>
    );
  }

  const members = group.members || [];

  return (
    <div className="page-form">
      <Link to={`/groups/${groupId}`} className="back-link">
        &larr; Back to {group.name}
      </Link>
      <h1>Add Expense</h1>

      <div
        data-testid="summary-panel"
        style={{
          padding: '12px 16px',
          background: 'var(--bg-soft, #f4f5f9)',
          borderRadius: 8,
          marginBottom: 16,
          fontSize: 14,
          color: 'var(--text-light, #555)',
        }}
      >
        <strong>{group.name}</strong> &middot; {members.length} members
      </div>

      <div className="card">
        <div className="card-body">
          {error && <div className="error-msg">{error}</div>}

          <form onSubmit={handleSubmit}>
            <div className="form-group">
              <label>Amount ($)</label>
              <input
                className="form-input"
                type="number"
                step="0.01"
                min="0.01"
                placeholder="0.00"
                value={amount}
                onChange={(e) => setAmount(e.target.value)}
                required
              />
            </div>

            <div className="form-group">
              <label>Description</label>
              <input
                className="form-input"
                type="text"
                placeholder="e.g. Dinner at the restaurant"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                required
              />
            </div>

            <div className="form-group">
              <label>Paid by</label>
              <select
                className="form-input"
                value={paidBy}
                onChange={(e) => setPaidBy(e.target.value)}
                required
              >
                <option value="">Select who paid...</option>
                {members.map((m) => (
                  <option key={m.id} value={m.id}>
                    {m.name}
                  </option>
                ))}
              </select>
            </div>

            <div className="form-group">
              <label>Split among</label>
              <div
                className="checkbox-list"
                style={{
                  display: 'grid',
                  gridTemplateColumns: 'repeat(2, 1fr)',
                  gap: 8,
                }}
              >
                {members.map((m) => (
                  <label
                    key={m.id}
                    className={`checkbox-item ${splitAmong.includes(m.id) ? 'checked' : ''}`}
                  >
                    <input
                      type="checkbox"
                      checked={splitAmong.includes(m.id)}
                      onChange={() => toggleSplit(m.id)}
                    />
                    {m.name}
                  </label>
                ))}
              </div>
              {splitAmong.length > 0 && amount && (
                <p
                  style={{
                    marginTop: 10,
                    fontSize: 13,
                    color: 'var(--text-light)',
                  }}
                >
                  ${(parseFloat(amount) / splitAmong.length).toFixed(2)} per
                  person
                </p>
              )}
            </div>

            <div className="form-actions">
              <button
                type="submit"
                className="btn btn-primary"
                disabled={loading}
              >
                {loading ? 'Adding...' : 'Add Expense'}
              </button>
              <Link to={`/groups/${groupId}`} className="btn btn-secondary">
                Cancel
              </Link>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}