summaryrefslogtreecommitdiff
path: root/front/src/components/ProfileEditor.tsx
blob: 9a7493fa6d7deb5f036f5e150d0ecd9a313af702 (plain)
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import { useState, useEffect } from "react";
import type { UserProfile } from "@/types/nostrill";
import useLocalState from "@/state/state";
import Icon from "@/components/Icon";
import toast from "react-hot-toast";
import Avatar from "./Avatar";

interface ProfileEditorProps {
  ship: string;
  onSave?: () => void;
}

const ProfileEditor: React.FC<ProfileEditorProps> = ({ ship, onSave }) => {
  const { api, profiles } = useLocalState((s) => ({
    api: s.api,
    profiles: s.profiles,
  }));
  const isOwnProfile = ship === api?.airlock.our;

  // Initialize state with existing profile or defaults
  const existingProfile = profiles.get(ship);
  const [name, setName] = useState(existingProfile?.name || "");
  const [picture, setPicture] = useState(existingProfile?.picture || "");
  const [about, setAbout] = useState(existingProfile?.about || "");
  const [customFields, setCustomFields] = useState<
    Array<{ key: string; value: string }>
  >(
    Object.entries(existingProfile?.other || {}).map(([key, value]) => ({
      key,
      value,
    })),
  );
  const [isEditing, setIsEditing] = useState(false);
  const [isSaving, setIsSaving] = useState(false);

  useEffect(() => {
    const profile = profiles.get(ship);
    if (profile) {
      setName(profile.name || "");
      setPicture(profile.picture || "");
      setAbout(profile.about || "");
      setCustomFields(
        Object.entries(profile.other || {}).map(([key, value]) => ({
          key,
          value,
        })),
      );
    }
  }, [ship, profiles]);

  const handleAddCustomField = () => {
    setCustomFields([...customFields, { key: "", value: "" }]);
  };

  const handleUpdateCustomField = (
    index: number,
    field: "key" | "value",
    newValue: string,
  ) => {
    const updated = [...customFields];
    updated[index][field] = newValue;
    setCustomFields(updated);
  };

  const handleRemoveCustomField = (index: number) => {
    setCustomFields(customFields.filter((_, i) => i !== index));
  };

  const handleSave = async () => {
    setIsSaving(true);
    try {
      // Convert custom fields array to object
      const other: Record<string, string> = {};
      customFields.forEach(({ key, value }) => {
        if (key.trim()) {
          other[key.trim()] = value;
        }
      });

      const profile: UserProfile = {
        name,
        picture,
        about,
        other,
      };

      // Call API to save profile
      if (api && typeof api.createProfile === "function") {
        await api.createProfile(profile);
      } else {
        throw new Error("Profile update API not available");
      }

      toast.success("Profile updated successfully");
      setIsEditing(false);
      onSave?.();
    } catch (error) {
      toast.error("Failed to update profile");
      console.error("Failed to save profile:", error);
    } finally {
      setIsSaving(false);
    }
  };

  const handleCancel = () => {
    // Reset to original values
    const profile = profiles.get(ship);
    if (profile) {
      setName(profile.name || "");
      setPicture(profile.picture || "");
      setAbout(profile.about || "");
      setCustomFields(
        Object.entries(profile.other || {}).map(([key, value]) => ({
          key,
          value,
        })),
      );
    }
    setIsEditing(false);
  };

  if (!isOwnProfile) {
    // View-only mode for other users' profiles - no editing allowed
    return (
      <div className="profile-editor view-mode">
        <div className="profile-picture">
          <Avatar p={ship} size={120} picOnly={true} />
        </div>
        <div className="profile-info">
          <h2>{name || ship}</h2>
          {about && <p className="profile-about">{about}</p>}

          {customFields.length > 0 && (
            <div className="profile-custom-fields">
              <h4>Additional Info</h4>
              {customFields.map(({ key, value }, index) => (
                <div key={index} className="custom-field-view">
                  <span className="field-key">{key}:</span>
                  <span className="field-value">{value}</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    );
  }

  return (
    <div className="profile-editor">
      <div className="profile-header">
        <h2>Edit Profile</h2>
        {isOwnProfile && !isEditing && (
          <button onClick={() => setIsEditing(true)} className="edit-btn">
            <Icon name="settings" size={16} />
            Edit
          </button>
        )}
      </div>

      {isEditing ? (
        <div className="profile-form">
          <div className="form-group">
            <label htmlFor="name">Display Name</label>
            <input
              id="name"
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Your display name"
            />
          </div>

          <div className="form-group">
            <label htmlFor="picture">Profile Picture URL</label>
            <input
              id="picture"
              type="url"
              value={picture}
              onChange={(e) => setPicture(e.target.value)}
              placeholder="https://example.com/avatar.jpg"
            />
            <div className="picture-preview">
              <Avatar p={ship} size={54} picOnly={true} />
            </div>
          </div>

          <div className="form-group">
            <label htmlFor="about">About</label>
            <textarea
              id="about"
              value={about}
              onChange={(e) => setAbout(e.target.value)}
              placeholder="Tell us about yourself..."
              rows={4}
            />
          </div>

          <div className="form-group custom-fields">
            <label>Custom Fields</label>
            {customFields.map((field, index) => (
              <div key={index} className="custom-field-row">
                <input
                  type="text"
                  value={field.key}
                  onChange={(e) =>
                    handleUpdateCustomField(index, "key", e.target.value)
                  }
                  placeholder="Field name"
                  className="field-key-input"
                />
                <input
                  type="text"
                  value={field.value}
                  onChange={(e) =>
                    handleUpdateCustomField(index, "value", e.target.value)
                  }
                  placeholder="Field value"
                  className="field-value-input"
                />
                <button
                  onClick={() => handleRemoveCustomField(index)}
                  className="remove-field-btn"
                  title="Remove field"
                >
                  ×
                </button>
              </div>
            ))}
            <button onClick={handleAddCustomField} className="add-field-btn">
              + Add Custom Field
            </button>
          </div>

          <div className="form-actions">
            <button
              onClick={handleSave}
              disabled={isSaving}
              className="save-btn"
            >
              {isSaving ? "Saving..." : "Save Profile"}
            </button>
            <button
              onClick={handleCancel}
              disabled={isSaving}
              className="cancel-btn"
            >
              Cancel
            </button>
          </div>
        </div>
      ) : (
        <div className="profile-view">
          <div className="profile-picture">
            <Avatar p={ship} size={120} picOnly={true} />
          </div>

          <div className="profile-info">
            <h3>{name || ship}</h3>
            {about && <p className="profile-about">{about}</p>}

            {customFields.length > 0 && (
              <div className="profile-custom-fields">
                <h4>Additional Info</h4>
                {customFields.map(({ key, value }, index) => (
                  <div key={index} className="custom-field-view">
                    <span className="field-key">{key}:</span>
                    <span className="field-value">{value}</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default ProfileEditor;