File size: 6,869 Bytes
c40c75a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Select as AntSelect, Button as AntButton, message } from 'antd';
import { Select, SelectItem } from "@tremor/react";
import { Card, Text } from "@tremor/react";

interface BaseMember {
  user_email?: string;
  user_id?: string;
  role: string;
}

interface ModalConfig {
  title: string;
  roleOptions: Array<{
    label: string;
    value: string;
  }>;
  defaultRole?: string;
  showEmail?: boolean;
  showUserId?: boolean;
  additionalFields?: Array<{
    name: string;
    label: string;
    type: 'input' | 'select';
    options?: Array<{ label: string; value: string }>;
    rules?: any[];
  }>;
}

interface MemberModalProps<T extends BaseMember> {
  visible: boolean;
  onCancel: () => void;
  onSubmit: (data: T) => void;
  initialData?: T | null;
  mode: 'add' | 'edit';
  config: ModalConfig;
}

const MemberModal = <T extends BaseMember>({
  visible,
  onCancel,
  onSubmit,
  initialData,
  mode,
  config
}: MemberModalProps<T>) => {
  const [form] = Form.useForm();

  console.log("Initial Data:", initialData);

  // Reset form and set initial values when modal becomes visible or initialData changes
  useEffect(() => {
    if (visible) {
      if (mode === 'edit' && initialData) {
        // For edit mode, use the initialData values
        form.setFieldsValue({
          ...initialData,
          // Ensure role is set correctly for editing
          role: initialData.role || config.defaultRole
        });
      } else {
        // For add mode, reset to defaults
        form.resetFields();
        form.setFieldsValue({
          role: config.defaultRole || config.roleOptions[0]?.value
        });
      }
    }
  }, [visible, initialData, mode, form, config.defaultRole, config.roleOptions]);

  const handleSubmit = async (values: any) => {
    try {
      // Trim string values
      const formData = Object.entries(values).reduce((acc, [key, value]) => ({
        ...acc,
        [key]: typeof value === 'string' ? value.trim() : value
      }), {}) as T;
      
      onSubmit(formData);
      form.resetFields();
      message.success(`Successfully ${mode === 'add' ? 'added' : 'updated'} member`);
    } catch (error) {
      message.error('Failed to submit form');
      console.error('Form submission error:', error);
    }
  };

  // Helper function to get role label from value
  const getRoleLabel = (value: string) => {
    return config.roleOptions.find(option => option.value === value)?.label || value;
  };

  const renderField = (field: {
    name: string;
    label: string;
    type: 'input' | 'select';
    options?: Array<{ label: string; value: string }>;
    rules?: any[];
  }) => {
    switch (field.type) {
      case 'input':
        return (
          <Input
            className="px-3 py-2 border rounded-md w-full"
            onChange={(e) => {
              e.target.value = e.target.value.trim();
            }}
          />
        );
      case 'select':
        return (
          <AntSelect>
            {field.options?.map(option => (
              <AntSelect.Option key={option.value} value={option.value}>
                {option.label}
              </AntSelect.Option>
            ))}
          </AntSelect>
        );
      default:
        return null;
    }
  };

  return (
    <Modal
      title={config.title || (mode === 'add' ? "Add Member" : "Edit Member")}
      open={visible}
      width={800}
      footer={null}
      onCancel={onCancel}
    >
      <Form
        form={form}
        onFinish={handleSubmit}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        labelAlign="left"
      >
        {config.showEmail && (
          <Form.Item 
            label="Email" 
            name="user_email"
            className="mb-4"
            rules={[
              { type: 'email', message: 'Please enter a valid email!' }
            ]}
          >
            <Input
              className="px-3 py-2 border rounded-md w-full"
              placeholder="[email protected]"
              onChange={(e) => {
                e.target.value = e.target.value.trim();
              }}
            />
          </Form.Item>
        )}

        {config.showEmail && config.showUserId && (
          <div className="text-center mb-4">
            <Text>OR</Text>
          </div>
        )}

        {config.showUserId && (
          <Form.Item 
            label="User ID" 
            name="user_id"
            className="mb-4"
          >
            <Input
              className="px-3 py-2 border rounded-md w-full"
              placeholder="user_123"
              onChange={(e) => {
                e.target.value = e.target.value.trim();
              }}
            />
          </Form.Item>
        )}

        <Form.Item 
          label={
            <div className="flex items-center gap-2">
              <span>Role</span>
              {mode === 'edit' && initialData && (
                <span className="text-gray-500 text-sm">
                  (Current: {getRoleLabel(initialData.role)})
                </span>
              )}
            </div>
          }
          name="role"
          className="mb-4"
          rules={[
            { required: true, message: 'Please select a role!' }
          ]}
        >
          <AntSelect>
            {mode === 'edit' && initialData
              ? [
                  // Current role first
                  ...config.roleOptions.filter(option => option.value === initialData.role),
                  // Then all other roles
                  ...config.roleOptions.filter(option => option.value !== initialData.role)
                ].map(option => (
                  <AntSelect.Option key={option.value} value={option.value}>
                    {option.label}
                  </AntSelect.Option>
                ))
              : config.roleOptions.map(option => (
                  <AntSelect.Option key={option.value} value={option.value}>
                    {option.label}
                  </AntSelect.Option>
                ))}
          </AntSelect>
        </Form.Item>

        {config.additionalFields?.map(field => (
          <Form.Item
            key={field.name}
            label={field.label}
            name={field.name}
            className="mb-4"
            rules={field.rules}
          >
            {renderField(field)}
          </Form.Item>
        ))}

        <div className="text-right mt-6">
          <AntButton 
            onClick={onCancel} 
            className="mr-2"
          >
            Cancel
          </AntButton>
          <AntButton 
            type="default" 
            htmlType="submit"
          >
            {mode === 'add' ? 'Add Member' : 'Save Changes'}
          </AntButton>
        </div>
      </Form>
    </Modal>
  );
};

export default MemberModal;