import React, { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { get, put } from '../../../services/api';
import { showNotification } from '../../../store/notification.slice';
import UserPermissionDetails from './UserPermissionDetails';

export default function UserPermissions() {
    const dispatch = useDispatch();
    const [users, setUsers] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [selectedUser, setSelectedUser] = useState(null);
    const [showDetailsModal, setShowDetailsModal] = useState(false);

    // 获取用户列表
    useEffect(() => {
        const fetchUsers = async () => {
            try {
                setLoading(true);
                const response = await get('/users/permissions/');

                if (response && response.code === 200) {
                    setUsers(response.data.users || []);
                } else {
                    setError('获取用户列表失败');
                }
            } catch (error) {
                console.error('获取用户列表失败:', error);
                setError('获取用户列表失败');
            } finally {
                setLoading(false);
            }
        };

        fetchUsers();
    }, []);

    // 打开用户权限详情弹窗
    const handleOpenDetailsModal = (user) => {
        setSelectedUser(user);
        setShowDetailsModal(true);
    };

    // 关闭用户权限详情弹窗
    const handleCloseDetailsModal = () => {
        setShowDetailsModal(false);
        setSelectedUser(null);
    };

    // 保存用户权限更改
    const handleSavePermissions = async (userId, updatedPermissions) => {
        try {
            const response = await put(`/users/${userId}/permissions/`, {
                permissions: updatedPermissions,
            });

            if (response && response.code === 200) {
                // 更新用户列表中的权限信息
                setUsers(
                    users.map((user) => {
                        if (user.id === userId) {
                            return {
                                ...user,
                                permissions: {
                                    ...user.permissions,
                                    ...response.data.permissions,
                                },
                            };
                        }
                        return user;
                    })
                );

                dispatch(
                    showNotification({
                        message: '权限更新成功',
                        type: 'success',
                    })
                );

                // 关闭弹窗
                handleCloseDetailsModal();
            } else {
                dispatch(
                    showNotification({
                        message: '权限更新失败',
                        type: 'danger',
                    })
                );
            }
        } catch (error) {
            console.error('权限更新失败:', error);
            dispatch(
                showNotification({
                    message: '权限更新失败',
                    type: 'danger',
                })
            );
        }
    };

    // 渲染加载状态
    if (loading) {
        return (
            <div className='text-center py-5'>
                <div className='spinner-border' role='status'>
                    <span className='visually-hidden'>加载中...</span>
                </div>
                <p className='mt-3'>加载用户列表...</p>
            </div>
        );
    }

    // 渲染错误状态
    if (error) {
        return (
            <div className='alert alert-danger' role='alert'>
                {error}
            </div>
        );
    }

    // 渲染空状态
    if (users.length === 0) {
        return (
            <div className='alert alert-info' role='alert'>
                暂无用户数据
            </div>
        );
    }

    // 渲染用户列表
    return (
        <>
            <div className='card'>
                <div className='card-header bg-white'>
                    <h5 className='mb-0'>用户权限管理</h5>
                </div>
                <div className='card-body p-0'>
                    <div className='table-responsive'>
                        <table className='table table-hover mb-0'>
                            <thead className='table-light'>
                                <tr>
                                    <th>用户名</th>
                                    <th>姓名</th>
                                    <th>部门</th>
                                    <th>职位</th>
                                    <th>权限</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {users.map((user) => (
                                    <tr key={user.id}>
                                        <td>{user.username}</td>
                                        <td>{user.name}</td>
                                        <td>{user.department}</td>
                                        <td>{user.position}</td>
                                        <td>
                                            {user.permissions_count && (
                                                <div className='d-flex gap-2'>
                                                    {user.permissions_count.read > 0 && (
                                                        <span className='badge bg-info'>
                                                            只读: {user.permissions_count.read}
                                                        </span>
                                                    )}
                                                    {user.permissions_count.edit > 0 && (
                                                        <span className='badge bg-success'>
                                                            编辑: {user.permissions_count.edit}
                                                        </span>
                                                    )}
                                                    {user.permissions_count.admin > 0 && (
                                                        <span className='badge bg-danger'>
                                                            管理: {user.permissions_count.admin}
                                                        </span>
                                                    )}
                                                </div>
                                            )}
                                        </td>
                                        <td>
                                            <button
                                                className='btn btn-sm btn-primary'
                                                onClick={() => handleOpenDetailsModal(user)}
                                            >
                                                权限详情
                                            </button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            {/* 用户权限详情弹窗 */}
            {showDetailsModal && selectedUser && (
                <UserPermissionDetails
                    user={selectedUser}
                    onClose={handleCloseDetailsModal}
                    onSave={handleSavePermissions}
                />
            )}
        </>
    );
}
