import React, { useState, useEffect } from 'react'; import axios from 'axios'; const BASE_URL = "http://localhost:8000"; const UserUpdateForm = ({ show, onClose, title, userId }) => { const [formData, setFormData] = useState({ fullName: '', username: '', password: '', note: '', role: '', skype: '', email: '', is_active: false, is_admin: false }); const [showModal, setShowModal] = useState(false); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); useEffect(() => { if (userId) { fetchUserDetails(); } }, [userId]); const fetchUserDetails = async () => { setIsLoading(true); setError(null); try { const token = localStorage.getItem('token'); if (!token) { throw new Error('No authentication token found'); } const response = await axios.get(`${BASE_URL}/users/me`, { headers: { 'Authorization': `Bearer ${token}`, 'Accept': 'application/json', } }); if (!response.data) { throw new Error('User not found'); } setFormData({ fullName: response.data.fullName || '', username: response.data.username || '', email: response.data.email || '', role: response.data.role || '', skype: response.data.skype || '', note: response.data.note || '', is_active: Boolean(response.data.is_active), is_admin: Boolean(response.data.is_admin) }); } catch (error) { console.error('Error fetching user details:', error); setError(error.message || 'Failed to fetch user details'); } finally { setIsLoading(false); } }; const handleUpdate = async (e) => { e.preventDefault(); setIsLoading(true); setError(null); try { const token = localStorage.getItem('token'); if (!token) { throw new Error('No authentication token found'); } const updateData = { fullName: formData.fullName || null, username: formData.username || null, email: formData.email || null, role: formData.role || null, skype: formData.skype || null, note: formData.note || null, is_active: Boolean(formData.is_active), is_admin: Boolean(formData.is_admin) }; const cleanedData = Object.fromEntries( Object.entries(updateData).filter(([_, value]) => value !== null) ); await axios.patch( `${BASE_URL}/user/${userId}`, cleanedData, { headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}`, 'Accept': 'application/json', } } ); setShowModal(true); } catch (error) { console.error('Error updating user:', error); setError(error.response?.data?.detail || 'Failed to update user'); } finally { setIsLoading(false); } }; const handleInputChange = (e) => { const { name, value, type, checked } = e.target; setFormData(prev => ({ ...prev, [name]: type === 'checkbox' ? checked : value })); }; const handleCloseModal = () => { setShowModal(false); onClose(); window.location.reload(); }; if (!show) return null; if (isLoading) { return (
Loading...