Spaces:
Running

File size: 20,487 Bytes
0235b53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68688a7
3f91467
0235b53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68688a7
 
 
0235b53
 
 
 
 
 
 
 
68688a7
0235b53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68688a7
0235b53
 
a7e3546
0235b53
 
a7e3546
0235b53
 
 
 
a7e3546
0235b53
 
 
 
 
 
 
 
 
 
 
a7e3546
0235b53
 
 
 
a7e3546
0235b53
a7e3546
0235b53
 
 
 
a7e3546
0235b53
 
 
 
 
 
 
a7e3546
0235b53
 
 
 
a7e3546
0235b53
a7e3546
0235b53
 
 
 
 
a7e3546
0235b53
a7e3546
0235b53
a7e3546
0235b53
 
 
a7e3546
 
0235b53
a7e3546
 
0235b53
 
 
a7e3546
0235b53
 
 
a7e3546
 
 
0235b53
a7e3546
 
0235b53
a7e3546
 
0235b53
 
 
 
 
 
 
 
 
a7e3546
 
0235b53
 
 
 
68688a7
 
 
 
 
 
 
 
 
0235b53
3f91467
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0235b53
a7e3546
0235b53
a7e3546
0235b53
 
a7e3546
0235b53
 
 
 
a7e3546
0235b53
a7e3546
0235b53
 
a7e3546
0235b53
a7e3546
0235b53
 
 
a7e3546
 
0235b53
 
 
 
 
 
 
 
 
a7e3546
0235b53
 
a7e3546
 
 
0235b53
 
 
a7e3546
 
 
 
0235b53
a7e3546
0235b53
 
 
a7e3546
 
0235b53
 
 
a7e3546
 
0235b53
 
 
 
 
 
 
 
 
a7e3546
0235b53
a7e3546
0235b53
 
 
a7e3546
 
 
0235b53
a7e3546
0235b53
a7e3546
 
 
0235b53
 
a7e3546
0235b53
 
 
 
 
a7e3546
0235b53
a7e3546
0235b53
 
 
 
 
 
 
 
 
 
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import { useState, useEffect } from 'react'
import { X, User as UserIcon, Shield, CreditCard, AlertTriangle, Check, Briefcase, DollarSign, Trash } from 'lucide-react'
import { useToast } from '@/contexts/ToastContext'

interface User {
    id: string
    email: string
    full_name: string
    is_active: boolean
    is_superuser: boolean
    is_verified: boolean
    role: string
    created_at: string
    tenant_name: string
    partner_status: string | null
    referral_code: string | null
    tenant_id?: string
    subscription_plan?: string
    subscription_end?: string
}

interface UserDetailsModalProps {
    user: User | null
    isOpen: boolean
    onClose: () => void
    onUpdate: () => void // Refresh list
}

export default function UserDetailsModal({ user, isOpen, onClose, onUpdate }: UserDetailsModalProps) {
    const [activeTab, setActiveTab] = useState<'profile' | 'partner' | 'danger'>('profile')
    const [isLoading, setIsLoading] = useState(false)
    const toast = useToast()

    // Form State
    const [role, setRole] = useState('')
    const [isActive, setIsActive] = useState(true)
    const [isVerified, setIsVerified] = useState(false)

    // Subscription Plan
    const [subscriptionPlan, setSubscriptionPlan] = useState('')

    // Partner Form
    const [partnerName, setPartnerName] = useState('')

    useEffect(() => {
        if (user) {
            setRole(user.role)
            setIsActive(user.is_active)
            setIsVerified(user.is_verified)
            setSubscriptionPlan(user.subscription_plan || 'trial')
            setPartnerName(user.tenant_name || '')
        }
    }, [user])

    if (!isOpen || !user) return null

    const handleSaveProfile = async () => {
        setIsLoading(true)
        try {
            const res = await fetch(`/api/v1/admin/users/${user.id}`, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
                },
                body: JSON.stringify({ role, is_active: isActive, is_verified: isVerified, subscription_plan: subscriptionPlan })
            })
            if (res.ok) {
                toast.success('Сохранено', 'Профиль обновлен')
                onUpdate()
            }
        } catch (e) { toast.error('Ошибка', 'Не удалось сохранить') }
        finally { setIsLoading(false) }
    }

    const handleCreatePartner = async () => {
        if (!partnerName) return toast.error('Ошибка', 'Название компании обязательно')
        setIsLoading(true)
        try {
            const res = await fetch(`/api/v1/admin/users/${user.id}/partner`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
                },
                body: JSON.stringify({ company_name: partnerName })
            })
            if (res.ok) {
                toast.success('Успех', 'Партнерский профиль создан')
                onUpdate()
                onClose()
            } else {
                const err = await res.json()
                toast.error('Ошибка', err.detail || 'Ошибка')
            }
        } catch (e) { toast.error('Ошибка', 'Ошибка сети') }
        finally { setIsLoading(false) }
    }

    const handleDeleteUser = async () => {
        if (!confirm(`ВЫ УВЕРЕНЫ? Это удалит ${user.email} и все связанные данные.`)) return
        setIsLoading(true)
        try {
            const res = await fetch(`/api/v1/admin/users/${user.id}`, {
                method: 'DELETE',
                headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` }
            })
            if (res.ok) {
                toast.success('Удалено', 'Пользователь удален навсегда')
                onUpdate()
                onClose()
            } else {
                const err = await res.json()
                toast.error('Ошибка', err.detail || 'Не удалось удалить')
            }
        } catch (e) { toast.error('Ошибка', 'Ошибка сети') }
        finally { setIsLoading(false) }
    }

    return (
        <div className="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center p-4">
            <div className="bg-slate-900 border border-white/10 rounded-2xl w-full max-w-2xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]">
                {/* Header */}
                <div className="p-6 border-b border-white/10 flex justify-between items-start bg-slate-800/50">
                    <div className="flex gap-4">
                        <div className="w-12 h-12 bg-indigo-600 rounded-full flex items-center justify-center text-white text-xl font-bold shadow-lg shadow-indigo-500/20">
                            {user.full_name?.[0] || user.email[0].toUpperCase()}
                        </div>
                        <div>
                            <h2 className="text-xl font-bold text-white">{user.full_name || 'Без имени'}</h2>
                            <p className="text-slate-400 font-mono text-sm">{user.email}</p>
                            <div className="flex gap-2 mt-2">
                                <span className="px-2 py-0.5 bg-slate-700/50 text-slate-300 rounded text-[10px] font-bold uppercase">{user.role}</span>
                                {user.partner_status && <span className="px-2 py-0.5 bg-amber-500/20 text-amber-400 rounded text-[10px] font-bold border border-amber-500/30">ПАРТНЕР</span>}
                            </div>
                        </div>
                    </div>
                    <button onClick={onClose} className="p-2 hover:bg-white/10 rounded-full transition-colors"><X className="w-5 h-5 text-slate-400" /></button>
                </div>

                {/* Tabs */}
                <div className="flex border-b border-white/10">
                    <button onClick={() => setActiveTab('profile')} className={`flex-1 py-3 text-sm font-bold flex items-center justify-center gap-2 transition-colors ${activeTab === 'profile' ? 'border-b-2 border-indigo-500 text-indigo-400 bg-indigo-500/10' : 'text-slate-500 hover:text-white hover:bg-white/5'}`}>
                        <UserIcon className="w-4 h-4" /> Профиль
                    </button>
                    <button onClick={() => setActiveTab('partner')} className={`flex-1 py-3 text-sm font-bold flex items-center justify-center gap-2 transition-colors ${activeTab === 'partner' ? 'border-b-2 border-amber-500 text-amber-400 bg-amber-500/10' : 'text-slate-500 hover:text-white hover:bg-white/5'}`}>
                        <DollarSign className="w-4 h-4" /> Партнер
                    </button>
                    <button onClick={() => setActiveTab('danger')} className={`flex-1 py-3 text-sm font-bold flex items-center justify-center gap-2 transition-colors ${activeTab === 'danger' ? 'border-b-2 border-red-500 text-red-400 bg-red-500/10' : 'text-slate-500 hover:text-white hover:bg-white/5'}`}>
                        <AlertTriangle className="w-4 h-4" /> Опасная зона
                    </button>
                </div>

                {/* Body */}
                <div className="p-6 overflow-y-auto flex-1">
                    {activeTab === 'profile' && (
                        <div className="space-y-6">
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="text-xs font-bold text-slate-400 uppercase">Роль</label>
                                    <select value={role} onChange={e => setRole(e.target.value)} className="w-full mt-1 p-2.5 border border-white/10 rounded-lg bg-slate-800 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50">
                                        <option value="OWNER">Owner</option>
                                        <option value="MANAGER">Manager</option>
                                        <option value="admin">Super Admin</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="text-xs font-bold text-slate-400 uppercase">Тариф подписки</label>
                                    <select value={subscriptionPlan} onChange={e => setSubscriptionPlan(e.target.value)} className="w-full mt-1 p-2.5 border border-white/10 rounded-lg bg-slate-800 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50">
                                        <option value="trial">Trial (Пробный)</option>
                                        <option value="start">Start</option>
                                        <option value="growth">Growth</option>
                                        <option value="enterprise">Enterprise</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="text-xs font-bold text-slate-400 uppercase">Окончание подписки</label>
                                    <div className="mt-1 p-2.5 border border-white/10 rounded-lg bg-slate-800 text-white flex items-center justify-between">
                                        <span className="text-sm">
                                            {user.subscription_end
                                                ? new Date(user.subscription_end).toLocaleDateString('ru-RU')
                                                : 'Нет данных'}
                                        </span>
                                        {user.tenant_id && (
                                            <button
                                                onClick={async () => {
                                                    if (!confirm('Продлить подписку на 30 дней?')) return
                                                    setIsLoading(true)
                                                    try {
                                                        const res = await fetch(`/api/v1/admin/tenants/${user.tenant_id}/subscription`, {
                                                            method: 'PATCH',
                                                            headers: {
                                                                'Content-Type': 'application/json',
                                                                'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
                                                            },
                                                            body: JSON.stringify({ extend_days: 30 })
                                                        })
                                                        if (res.ok) {
                                                            toast.success('Продлено', 'Подписка продлена на 30 дней')
                                                            onUpdate()
                                                        }
                                                    } catch (e) { toast.error('Ошибка', 'Не удалось продлить') }
                                                    finally { setIsLoading(false) }
                                                }}
                                                disabled={isLoading}
                                                className="px-3 py-1 bg-indigo-600 hover:bg-indigo-500 text-white text-[10px] font-bold rounded uppercase transition-colors"
                                            >
                                                +30 дней
                                            </button>
                                        )}
                                    </div>
                                </div>
                                <div>
                                    <label className="text-xs font-bold text-slate-400 uppercase">Статус</label>
                                    <div className="mt-2 flex items-center gap-2">
                                        <button onClick={() => setIsActive(!isActive)} className={`w-12 h-6 rounded-full p-1 transition-colors ${isActive ? 'bg-emerald-500' : 'bg-slate-600'}`}>
                                            <div className={`w-4 h-4 bg-white rounded-full shadow transition-transform ${isActive ? 'translate-x-6' : ''}`} />
                                        </button>
                                        <span className="text-sm font-medium text-slate-300">{isActive ? 'Активен' : 'Заблокирован'}</span>
                                    </div>
                                </div>
                            </div>

                            <div className="p-4 bg-indigo-500/10 rounded-xl border border-indigo-500/20">
                                <label className="flex items-center gap-3 cursor-pointer">
                                    <div className={`w-5 h-5 rounded border flex items-center justify-center transition-colors ${isVerified ? 'bg-indigo-600 border-indigo-600' : 'bg-slate-800 border-slate-600'}`} onClick={() => setIsVerified(!isVerified)}>
                                        {isVerified && <Check className="w-3 h-3 text-white" />}
                                    </div>
                                    <span className="font-medium text-white">Email подтвержден вручную</span>
                                </label>
                                <p className="text-xs text-indigo-400 mt-2 ml-8">Отметьте, если пользователь не может подтвердить email самостоятельно.</p>
                            </div>

                            <div className="flex justify-end">
                                <button onClick={handleSaveProfile} disabled={isLoading} className="px-6 py-2.5 bg-indigo-600 hover:bg-indigo-500 text-white rounded-lg font-bold transition-colors disabled:opacity-50">
                                    {isLoading ? 'Сохранение...' : 'Сохранить изменения'}
                                </button>
                            </div>
                        </div>
                    )}

                    {activeTab === 'partner' && (
                        <div className="space-y-6">
                            {user.partner_status ? (
                                <div className="text-center py-8">
                                    <div className="w-16 h-16 bg-amber-500/20 rounded-full flex items-center justify-center mx-auto mb-4 text-amber-400">
                                        <Check className="w-8 h-8" />
                                    </div>
                                    <h3 className="text-lg font-bold text-white">Уже партнер</h3>
                                    <p className="text-slate-400 mb-4">Реферальный код: <span className="font-mono text-white bg-slate-800 px-2 py-1 rounded">{user.referral_code}</span></p>
                                    <p className="text-sm text-amber-400 font-medium">Детальные настройки в разделе «Партнеры».</p>
                                </div>
                            ) : (
                                <div className="space-y-4">
                                    <div className="bg-amber-500/10 p-4 rounded-xl border border-amber-500/20">
                                        <h3 className="font-bold text-white mb-2">Назначить партнером</h3>
                                        <p className="text-sm text-slate-400 mb-4">
                                            Это создаст партнерский профиль для пользователя. Он получит доступ к партнерской панели.
                                        </p>
                                        <label className="text-xs font-bold text-slate-400 uppercase">Название компании</label>
                                        <input
                                            value={partnerName}
                                            onChange={e => setPartnerName(e.target.value)}
                                            className="w-full mt-1 p-2.5 border border-amber-500/20 rounded-lg bg-slate-800 text-white focus:outline-none focus:ring-2 focus:ring-amber-500/50"
                                            placeholder="Название агентства..."
                                        />
                                    </div>
                                    <div className="flex justify-end">
                                        <button onClick={handleCreatePartner} disabled={isLoading} className="px-6 py-2.5 bg-amber-500 hover:bg-amber-400 text-white rounded-lg font-bold transition-colors disabled:opacity-50">
                                            {isLoading ? 'Создание...' : 'Создать партнера'}
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}

                    {activeTab === 'danger' && (
                        <div className="space-y-6">
                            <div className="bg-red-500/10 p-6 rounded-xl border border-red-500/20">
                                <div className="flex items-start gap-4">
                                    <div className="bg-red-500/20 p-2 rounded-lg text-red-400">
                                        <AlertTriangle className="w-6 h-6" />
                                    </div>
                                    <div>
                                        <h3 className="text-red-400 font-bold text-lg">Опасная зона</h3>
                                        <p className="text-slate-400 mt-2 text-sm leading-relaxed">
                                            Удаление пользователя <strong className="text-white">необратимо</strong>.
                                            <br />
                                            Будут удалены:
                                            <ul className="list-disc ml-5 mt-1 space-y-1 opacity-80">
                                                <li>Партнерский профиль</li>
                                                <li>Назначения менеджера</li>
                                                <li>Данные авторизации</li>
                                            </ul>
                                            <br />
                                            Если пользователь владеет Tenant, сам Tenant <strong className="text-white">НЕ</strong> будет удален для сохранения данных.
                                        </p>
                                    </div>
                                </div>

                                <div className="mt-8 flex justify-end">
                                    <button onClick={handleDeleteUser} disabled={isLoading} className="flex items-center gap-2 px-6 py-3 bg-red-600 hover:bg-red-500 text-white rounded-xl font-bold transition-colors shadow-lg shadow-red-500/20 disabled:opacity-50">
                                        <Trash className="w-4 h-4" />
                                        {isLoading ? 'Удаление...' : 'УДАЛИТЬ НАВСЕГДА'}
                                    </button>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    )
}