import React, { useState, useEffect } from 'react';
import api from '../api';
import { reportError, logUserActionError } from '../utils/errorLogger';

const UserManagementPage = ({ onNavigate, user }) => {
    const [users, setUsers] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [message, setMessage] = useState({ type: '', text: '' });
    const [showCreateModal, setShowCreateModal] = useState(false);
    const [showRoleModal, setShowRoleModal] = useState(false);
    const [selectedUser, setSelectedUser] = useState(null);

    // 새 사용자 생성 폼 데이터
    const [createFormData, setCreateFormData] = useState({
        username: '',
        password: '',
        name: '',
        email: '',
        department: '',
        position: '',
        role: 'user'
    });

    const [validationErrors, setValidationErrors] = useState({});

    useEffect(() => {
        loadUsers();
    }, []);

    const loadUsers = async () => {
        try {
            setIsLoading(true);
            const response = await api.get('/auth/users');
            
            if (response.data.success) {
                setUsers(response.data.users);
            } else {
                setMessage({ type: 'error', text: '사용자 목록을 불러올 수 없습니다' });
            }
        } catch (err) {
            console.error('Load users error:', err);
            setMessage({ type: 'error', text: '사용자 목록 조회 중 오류가 발생했습니다' });
            logUserActionError('load_users', err, { userId: user?.user_id });
        } finally {
            setIsLoading(false);
        }
    };

    const handleCreateUser = async (e) => {
        e.preventDefault();
        
        if (!validateCreateForm()) {
            return;
        }

        try {
            setIsLoading(true);
            const response = await api.post('/auth/register', createFormData);
            
            if (response.data.success) {
                setMessage({ type: 'success', text: '사용자가 성공적으로 생성되었습니다' });
                setShowCreateModal(false);
                setCreateFormData({
                    username: '',
                    password: '',
                    name: '',
                    email: '',
                    department: '',
                    position: '',
                    role: 'user'
                });
                await loadUsers();
            } else {
                setMessage({ type: 'error', text: response.data.message || '사용자 생성에 실패했습니다' });
            }
        } catch (err) {
            console.error('Create user error:', err);
            const errorMessage = err.response?.data?.detail || '사용자 생성 중 오류가 발생했습니다';
            setMessage({ type: 'error', text: errorMessage });
            logUserActionError('create_user', err, { formData: createFormData });
        } finally {
            setIsLoading(false);
        }
    };

    const handleChangeRole = async (newRole) => {
        if (!selectedUser) return;

        try {
            setIsLoading(true);
            const response = await api.put(`/auth/users/${selectedUser.user_id}/role?new_role=${newRole}`);
            
            if (response.data.success) {
                setMessage({ type: 'success', text: `${selectedUser.name}의 역할이 변경되었습니다` });
                setShowRoleModal(false);
                setSelectedUser(null);
                await loadUsers();
            } else {
                setMessage({ type: 'error', text: response.data.message || '역할 변경에 실패했습니다' });
            }
        } catch (err) {
            console.error('Change role error:', err);
            const errorMessage = err.response?.data?.detail || '역할 변경 중 오류가 발생했습니다';
            setMessage({ type: 'error', text: errorMessage });
            logUserActionError('change_role', err, { userId: selectedUser.user_id, newRole });
        } finally {
            setIsLoading(false);
        }
    };

    const handleDeleteUser = async (userToDelete) => {
        if (!window.confirm(`정말로 ${userToDelete.name} 사용자를 삭제하시겠습니까?`)) {
            return;
        }

        try {
            setIsLoading(true);
            const response = await api.delete(`/auth/users/${userToDelete.user_id}`);
            
            if (response.data.success) {
                setMessage({ type: 'success', text: `${userToDelete.name} 사용자가 삭제되었습니다` });
                await loadUsers();
            } else {
                setMessage({ type: 'error', text: response.data.message || '사용자 삭제에 실패했습니다' });
            }
        } catch (err) {
            console.error('Delete user error:', err);
            const errorMessage = err.response?.data?.detail || '사용자 삭제 중 오류가 발생했습니다';
            setMessage({ type: 'error', text: errorMessage });
            logUserActionError('delete_user', err, { userId: userToDelete.user_id });
        } finally {
            setIsLoading(false);
        }
    };

    const validateCreateForm = () => {
        const errors = {};

        if (!createFormData.username.trim()) {
            errors.username = '사용자명을 입력해주세요';
        } else if (!/^[a-zA-Z0-9_]+$/.test(createFormData.username)) {
            errors.username = '사용자명은 영문, 숫자, 언더스코어만 사용 가능합니다';
        }

        if (!createFormData.password) {
            errors.password = '비밀번호를 입력해주세요';
        } else if (createFormData.password.length < 8) {
            errors.password = '비밀번호는 8자 이상이어야 합니다';
        }

        if (!createFormData.name.trim()) {
            errors.name = '이름을 입력해주세요';
        }

        if (createFormData.email && createFormData.email.trim() && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(createFormData.email)) {
            errors.email = '올바른 이메일 형식을 입력해주세요';
        }

        setValidationErrors(errors);
        return Object.keys(errors).length === 0;
    };

    const getRoleDisplayName = (role) => {
        const roleNames = {
            'system': '시스템 관리자',
            'admin': '관리자',
            'user': '사용자'
        };
        return roleNames[role] || role;
    };

    const getRoleBadgeColor = (role) => {
        const colors = {
            'system': { bg: '#fef2f2', color: '#dc2626' },
            'admin': { bg: '#fef7e0', color: '#92400e' },
            'user': { bg: '#f0f9ff', color: '#1e40af' }
        };
        return colors[role] || colors.user;
    };

    return (
        <div style={{ minHeight: '100vh', background: '#f8f9fa' }}>
            {/* 헤더 */}
            <div style={{
                background: 'white',
                borderBottom: '1px solid #e9ecef',
                padding: '16px 32px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between'
            }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                    <button
                        onClick={() => onNavigate('dashboard')}
                        style={{
                            background: 'none',
                            border: 'none',
                            color: '#28a745',
                            fontSize: '20px',
                            cursor: 'pointer',
                            padding: '4px',
                            borderRadius: '4px',
                            transition: 'background-color 0.2s'
                        }}
                        onMouseEnter={(e) => e.target.style.background = '#f8f9fa'}
                        onMouseLeave={(e) => e.target.style.background = 'none'}
                        title="대시보드로 돌아가기"
                    >
                        ←
                    </button>
                    <div>
                        <h1 style={{ fontSize: '24px', fontWeight: '700', color: '#2d3748', margin: 0 }}>
                            👥 사용자 관리
                        </h1>
                        <p style={{ color: '#6c757d', fontSize: '14px', margin: '4px 0 0 0' }}>
                            시스템 사용자 계정을 생성하고 관리하세요
                        </p>
                    </div>
                </div>
                
                <button
                    onClick={() => setShowCreateModal(true)}
                    style={{
                        background: '#007bff',
                        color: 'white',
                        border: 'none',
                        borderRadius: '8px',
                        padding: '10px 16px',
                        fontSize: '14px',
                        fontWeight: '600',
                        cursor: 'pointer',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '8px',
                        transition: 'background-color 0.2s'
                    }}
                    onMouseEnter={(e) => e.target.style.backgroundColor = '#0056b3'}
                    onMouseLeave={(e) => e.target.style.backgroundColor = '#007bff'}
                >
                    ➕ 새 사용자 생성
                </button>
            </div>

            <div style={{ padding: '32px', maxWidth: '1200px', margin: '0 auto' }}>
                {/* 메시지 표시 */}
                {message.text && (
                    <div style={{
                        padding: '12px 16px',
                        borderRadius: '8px',
                        marginBottom: '24px',
                        backgroundColor: message.type === 'success' ? '#d1edff' : '#f8d7da',
                        border: `1px solid ${message.type === 'success' ? '#bee5eb' : '#f5c6cb'}`,
                        color: message.type === 'success' ? '#0c5460' : '#721c24'
                    }}>
                        {message.text}
                    </div>
                )}

                {/* 사용자 목록 */}
                <div style={{
                    background: 'white',
                    borderRadius: '12px',
                    boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
                    overflow: 'hidden'
                }}>
                    <div style={{
                        padding: '20px 24px',
                        borderBottom: '1px solid #e9ecef',
                        background: '#f8f9fa'
                    }}>
                        <h2 style={{ fontSize: '18px', fontWeight: '600', color: '#2d3748', margin: 0 }}>
                            등록된 사용자 ({users.length}명)
                        </h2>
                    </div>

                    {isLoading ? (
                        <div style={{ padding: '40px', textAlign: 'center' }}>
                            <div style={{ fontSize: '16px', color: '#6c757d' }}>로딩 중...</div>
                        </div>
                    ) : users.length === 0 ? (
                        <div style={{ padding: '40px', textAlign: 'center' }}>
                            <div style={{ fontSize: '16px', color: '#6c757d' }}>등록된 사용자가 없습니다</div>
                        </div>
                    ) : (
                        <div style={{ overflow: 'auto' }}>
                            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                                <thead>
                                    <tr style={{ background: '#f8f9fa' }}>
                                        <th style={{ padding: '12px 16px', textAlign: 'left', fontWeight: '600', color: '#495057', borderBottom: '1px solid #dee2e6' }}>사용자</th>
                                        <th style={{ padding: '12px 16px', textAlign: 'left', fontWeight: '600', color: '#495057', borderBottom: '1px solid #dee2e6' }}>역할</th>
                                        <th style={{ padding: '12px 16px', textAlign: 'left', fontWeight: '600', color: '#495057', borderBottom: '1px solid #dee2e6' }}>부서/직책</th>
                                        <th style={{ padding: '12px 16px', textAlign: 'left', fontWeight: '600', color: '#495057', borderBottom: '1px solid #dee2e6' }}>상태</th>
                                        <th style={{ padding: '12px 16px', textAlign: 'left', fontWeight: '600', color: '#495057', borderBottom: '1px solid #dee2e6' }}>가입일</th>
                                        <th style={{ padding: '12px 16px', textAlign: 'center', fontWeight: '600', color: '#495057', borderBottom: '1px solid #dee2e6' }}>관리</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {users.map((userItem) => {
                                        const roleColor = getRoleBadgeColor(userItem.role);
                                        return (
                                            <tr key={userItem.user_id} style={{ borderBottom: '1px solid #f1f3f4' }}>
                                                <td style={{ padding: '16px' }}>
                                                    <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                                                        <div style={{
                                                            width: '40px',
                                                            height: '40px',
                                                            borderRadius: '50%',
                                                            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                                                            display: 'flex',
                                                            alignItems: 'center',
                                                            justifyContent: 'center',
                                                            color: 'white',
                                                            fontSize: '16px',
                                                            fontWeight: '600'
                                                        }}>
                                                            {userItem.name.charAt(0).toUpperCase()}
                                                        </div>
                                                        <div>
                                                            <div style={{ fontSize: '14px', fontWeight: '600', color: '#2d3748' }}>
                                                                {userItem.name}
                                                            </div>
                                                            <div style={{ fontSize: '12px', color: '#6c757d' }}>
                                                                @{userItem.username}
                                                            </div>
                                                            {userItem.email && (
                                                                <div style={{ fontSize: '12px', color: '#6c757d' }}>
                                                                    {userItem.email}
                                                                </div>
                                                            )}
                                                        </div>
                                                    </div>
                                                </td>
                                                <td style={{ padding: '16px' }}>
                                                    <span style={{
                                                        background: roleColor.bg,
                                                        color: roleColor.color,
                                                        padding: '4px 8px',
                                                        borderRadius: '12px',
                                                        fontSize: '12px',
                                                        fontWeight: '600'
                                                    }}>
                                                        {getRoleDisplayName(userItem.role)}
                                                    </span>
                                                </td>
                                                <td style={{ padding: '16px' }}>
                                                    <div style={{ fontSize: '14px', color: '#495057' }}>
                                                        {userItem.department || '-'}
                                                    </div>
                                                    <div style={{ fontSize: '12px', color: '#6c757d' }}>
                                                        {userItem.position || '-'}
                                                    </div>
                                                </td>
                                                <td style={{ padding: '16px' }}>
                                                    <span style={{
                                                        background: userItem.is_active ? '#d1edff' : '#f8d7da',
                                                        color: userItem.is_active ? '#0c5460' : '#721c24',
                                                        padding: '4px 8px',
                                                        borderRadius: '12px',
                                                        fontSize: '12px',
                                                        fontWeight: '600'
                                                    }}>
                                                        {userItem.is_active ? '활성' : '비활성'}
                                                    </span>
                                                </td>
                                                <td style={{ padding: '16px', fontSize: '14px', color: '#6c757d' }}>
                                                    {new Date(userItem.created_at).toLocaleDateString('ko-KR')}
                                                </td>
                                                <td style={{ padding: '16px', textAlign: 'center' }}>
                                                    <div style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}>
                                                        <button
                                                            onClick={() => {
                                                                setSelectedUser(userItem);
                                                                setShowRoleModal(true);
                                                            }}
                                                            style={{
                                                                background: '#ffc107',
                                                                color: 'white',
                                                                border: 'none',
                                                                borderRadius: '4px',
                                                                padding: '6px 12px',
                                                                fontSize: '12px',
                                                                cursor: 'pointer',
                                                                transition: 'background-color 0.2s'
                                                            }}
                                                            onMouseEnter={(e) => e.target.style.backgroundColor = '#e0a800'}
                                                            onMouseLeave={(e) => e.target.style.backgroundColor = '#ffc107'}
                                                            title="역할 변경"
                                                        >
                                                            역할 변경
                                                        </button>
                                                        {userItem.user_id !== user?.user_id && (
                                                            <button
                                                                onClick={() => handleDeleteUser(userItem)}
                                                                style={{
                                                                    background: '#dc3545',
                                                                    color: 'white',
                                                                    border: 'none',
                                                                    borderRadius: '4px',
                                                                    padding: '6px 12px',
                                                                    fontSize: '12px',
                                                                    cursor: 'pointer',
                                                                    transition: 'background-color 0.2s'
                                                                }}
                                                                onMouseEnter={(e) => e.target.style.backgroundColor = '#c82333'}
                                                                onMouseLeave={(e) => e.target.style.backgroundColor = '#dc3545'}
                                                                title="사용자 삭제"
                                                            >
                                                                삭제
                                                            </button>
                                                        )}
                                                    </div>
                                                </td>
                                            </tr>
                                        );
                                    })}
                                </tbody>
                            </table>
                        </div>
                    )}
                </div>
            </div>

            {/* 사용자 생성 모달 */}
            {showCreateModal && (
                <div style={{
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    background: 'rgba(0, 0, 0, 0.5)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 1000
                }}>
                    <div style={{
                        background: 'white',
                        borderRadius: '12px',
                        padding: '32px',
                        maxWidth: '500px',
                        width: '90%',
                        maxHeight: '90vh',
                        overflow: 'auto'
                    }}>
                        <h3 style={{ fontSize: '20px', fontWeight: '600', color: '#2d3748', marginBottom: '24px' }}>
                            새 사용자 생성
                        </h3>

                        <form onSubmit={handleCreateUser}>
                            <div style={{ display: 'grid', gap: '16px' }}>
                                <div>
                                    <label style={{ display: 'block', fontSize: '14px', fontWeight: '600', color: '#374151', marginBottom: '6px' }}>
                                        사용자명 *
                                    </label>
                                    <input
                                        type="text"
                                        value={createFormData.username}
                                        onChange={(e) => setCreateFormData(prev => ({ ...prev, username: e.target.value }))}
                                        style={{
                                            width: '100%',
                                            padding: '12px',
                                            border: validationErrors.username ? '2px solid #ef4444' : '1px solid #d1d5db',
                                            borderRadius: '8px',
                                            fontSize: '14px',
                                            boxSizing: 'border-box'
                                        }}
                                    />
                                    {validationErrors.username && (
                                        <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>
                                            {validationErrors.username}
                                        </p>
                                    )}
                                </div>

                                <div>
                                    <label style={{ display: 'block', fontSize: '14px', fontWeight: '600', color: '#374151', marginBottom: '6px' }}>
                                        이름 *
                                    </label>
                                    <input
                                        type="text"
                                        value={createFormData.name}
                                        onChange={(e) => setCreateFormData(prev => ({ ...prev, name: e.target.value }))}
                                        style={{
                                            width: '100%',
                                            padding: '12px',
                                            border: validationErrors.name ? '2px solid #ef4444' : '1px solid #d1d5db',
                                            borderRadius: '8px',
                                            fontSize: '14px',
                                            boxSizing: 'border-box'
                                        }}
                                    />
                                    {validationErrors.name && (
                                        <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>
                                            {validationErrors.name}
                                        </p>
                                    )}
                                </div>

                                <div>
                                    <label style={{ display: 'block', fontSize: '14px', fontWeight: '600', color: '#374151', marginBottom: '6px' }}>
                                        비밀번호 *
                                    </label>
                                    <input
                                        type="password"
                                        value={createFormData.password}
                                        onChange={(e) => setCreateFormData(prev => ({ ...prev, password: e.target.value }))}
                                        style={{
                                            width: '100%',
                                            padding: '12px',
                                            border: validationErrors.password ? '2px solid #ef4444' : '1px solid #d1d5db',
                                            borderRadius: '8px',
                                            fontSize: '14px',
                                            boxSizing: 'border-box'
                                        }}
                                    />
                                    {validationErrors.password && (
                                        <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>
                                            {validationErrors.password}
                                        </p>
                                    )}
                                </div>

                                <div>
                                    <label style={{ display: 'block', fontSize: '14px', fontWeight: '600', color: '#374151', marginBottom: '6px' }}>
                                        이메일
                                    </label>
                                    <input
                                        type="email"
                                        value={createFormData.email}
                                        onChange={(e) => setCreateFormData(prev => ({ ...prev, email: e.target.value }))}
                                        style={{
                                            width: '100%',
                                            padding: '12px',
                                            border: validationErrors.email ? '2px solid #ef4444' : '1px solid #d1d5db',
                                            borderRadius: '8px',
                                            fontSize: '14px',
                                            boxSizing: 'border-box'
                                        }}
                                    />
                                    {validationErrors.email && (
                                        <p style={{ color: '#ef4444', fontSize: '12px', marginTop: '4px' }}>
                                            {validationErrors.email}
                                        </p>
                                    )}
                                </div>

                                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
                                    <div>
                                        <label style={{ display: 'block', fontSize: '14px', fontWeight: '600', color: '#374151', marginBottom: '6px' }}>
                                            부서
                                        </label>
                                        <input
                                            type="text"
                                            value={createFormData.department}
                                            onChange={(e) => setCreateFormData(prev => ({ ...prev, department: e.target.value }))}
                                            style={{
                                                width: '100%',
                                                padding: '12px',
                                                border: '1px solid #d1d5db',
                                                borderRadius: '8px',
                                                fontSize: '14px',
                                                boxSizing: 'border-box'
                                            }}
                                        />
                                    </div>
                                    <div>
                                        <label style={{ display: 'block', fontSize: '14px', fontWeight: '600', color: '#374151', marginBottom: '6px' }}>
                                            직책
                                        </label>
                                        <input
                                            type="text"
                                            value={createFormData.position}
                                            onChange={(e) => setCreateFormData(prev => ({ ...prev, position: e.target.value }))}
                                            style={{
                                                width: '100%',
                                                padding: '12px',
                                                border: '1px solid #d1d5db',
                                                borderRadius: '8px',
                                                fontSize: '14px',
                                                boxSizing: 'border-box'
                                            }}
                                        />
                                    </div>
                                </div>

                                <div>
                                    <label style={{ display: 'block', fontSize: '14px', fontWeight: '600', color: '#374151', marginBottom: '6px' }}>
                                        역할 *
                                    </label>
                                    <select
                                        value={createFormData.role}
                                        onChange={(e) => setCreateFormData(prev => ({ ...prev, role: e.target.value }))}
                                        style={{
                                            width: '100%',
                                            padding: '12px',
                                            border: '1px solid #d1d5db',
                                            borderRadius: '8px',
                                            fontSize: '14px',
                                            boxSizing: 'border-box'
                                        }}
                                    >
                                        <option value="user">사용자</option>
                                        <option value="admin">관리자</option>
                                        <option value="system">시스템 관리자</option>
                                    </select>
                                </div>
                            </div>

                            <div style={{ display: 'flex', gap: '12px', marginTop: '24px' }}>
                                <button
                                    type="submit"
                                    disabled={isLoading}
                                    style={{
                                        flex: 1,
                                        padding: '12px',
                                        background: '#007bff',
                                        color: 'white',
                                        border: 'none',
                                        borderRadius: '8px',
                                        fontSize: '14px',
                                        fontWeight: '600',
                                        cursor: isLoading ? 'not-allowed' : 'pointer'
                                    }}
                                >
                                    {isLoading ? '생성 중...' : '사용자 생성'}
                                </button>
                                <button
                                    type="button"
                                    onClick={() => setShowCreateModal(false)}
                                    style={{
                                        flex: 1,
                                        padding: '12px',
                                        background: '#6c757d',
                                        color: 'white',
                                        border: 'none',
                                        borderRadius: '8px',
                                        fontSize: '14px',
                                        fontWeight: '600',
                                        cursor: 'pointer'
                                    }}
                                >
                                    취소
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* 역할 변경 모달 */}
            {showRoleModal && selectedUser && (
                <div style={{
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    background: 'rgba(0, 0, 0, 0.5)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    zIndex: 1000
                }}>
                    <div style={{
                        background: 'white',
                        borderRadius: '12px',
                        padding: '32px',
                        maxWidth: '400px',
                        width: '90%'
                    }}>
                        <h3 style={{ fontSize: '20px', fontWeight: '600', color: '#2d3748', marginBottom: '16px' }}>
                            역할 변경
                        </h3>
                        <p style={{ fontSize: '14px', color: '#6c757d', marginBottom: '24px' }}>
                            {selectedUser.name}의 역할을 변경하시겠습니까?
                        </p>

                        <div style={{ display: 'grid', gap: '12px', marginBottom: '24px' }}>
                            {['user', 'admin', 'system'].map((role) => (
                                <button
                                    key={role}
                                    onClick={() => handleChangeRole(role)}
                                    disabled={role === selectedUser.role}
                                    style={{
                                        padding: '12px 16px',
                                        border: role === selectedUser.role ? '2px solid #007bff' : '1px solid #d1d5db',
                                        borderRadius: '8px',
                                        background: role === selectedUser.role ? '#f0f9ff' : 'white',
                                        color: role === selectedUser.role ? '#007bff' : '#495057',
                                        fontSize: '14px',
                                        fontWeight: '600',
                                        cursor: role === selectedUser.role ? 'default' : 'pointer',
                                        textAlign: 'left',
                                        transition: 'all 0.2s'
                                    }}
                                    onMouseEnter={(e) => {
                                        if (role !== selectedUser.role) {
                                            e.target.style.background = '#f8f9fa';
                                        }
                                    }}
                                    onMouseLeave={(e) => {
                                        if (role !== selectedUser.role) {
                                            e.target.style.background = 'white';
                                        }
                                    }}
                                >
                                    {getRoleDisplayName(role)}
                                    {role === selectedUser.role && (
                                        <span style={{ fontSize: '12px', color: '#6c757d', marginLeft: '8px' }}>
                                            (현재)
                                        </span>
                                    )}
                                </button>
                            ))}
                        </div>

                        <button
                            onClick={() => {
                                setShowRoleModal(false);
                                setSelectedUser(null);
                            }}
                            style={{
                                width: '100%',
                                padding: '12px',
                                background: '#6c757d',
                                color: 'white',
                                border: 'none',
                                borderRadius: '8px',
                                fontSize: '14px',
                                fontWeight: '600',
                                cursor: 'pointer'
                            }}
                        >
                            취소
                        </button>
                    </div>
                </div>
            )}
        </div>
    );
};

export default UserManagementPage;