const API_BASE_URL = 'http://localhost:3000/api';

$(document).ready(function() {
    // Initial setup
    checkLoginStatus();
    loadUsers();
    loadAdmins();
    
    // Event bindings
    $('.nav-link').click(handleNavigation);
    $('#saveUser').click(saveUser);
    $('#userModal').on('hidden.bs.modal', clearUserForm);
    $('#savePoem').click(savePoem);
    $('#poemModal').on('hidden.bs.modal', clearPoemForm);
    $('#logoutBtn').click(logout);
    $('#saveAdmin').click(saveAdmin);
    $('#adminModal').on('hidden.bs.modal', clearAdminForm);
});

// Navigation handler
function handleNavigation(e) {
    e.preventDefault();
    $('.nav-link').removeClass('active');
    $(this).addClass('active');
    
    const page = $(this).data('page');
    if (page === 'users') {
        $('#usersPage').show();
        $('#poemsPage').hide();
        loadUsers();
    } else {
        $('#usersPage').hide();
        $('#poemsPage').show();
        loadPoems();
    }
}

// Admin functions
function loadAdmins() {
    $.ajax({
        url: `${API_BASE_URL}/admin/list`,
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
        },
        success: function(response) {
            $('#adminsList').empty();
            response.forEach(admin => {
                $('#adminsList').append(`
                    <tr>
                        <td>${admin.id}</td>
                        <td>${admin.username}</td>
                        <td>
                            <span class="badge bg-${admin.status === 'active' ? 'success' : 'danger'}">
                                ${admin.status === 'active' ? '启用' : '禁用'}
                            </span>
                        </td>
                        <td>${new Date(admin.createdAt).toLocaleDateString()}</td>
                        <td>
                            <button class="btn btn-sm btn-info" onclick="editAdmin(${admin.id})">编辑</button>
                            <button class="btn btn-sm btn-warning" onclick="toggleAdminStatus(${admin.id}, '${admin.status}')">
                                ${admin.status === 'active' ? '禁用' : '启用'}
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="deleteAdmin(${admin.id})">删除</button>
                        </td>
                    </tr>
                `);
            });
        }
    });
}

function saveAdmin() {
    const adminId = $('#adminId').val();
    const adminData = {
        username: $('#adminUsername').val(),
        password: $('#adminPassword').val(),
        status: $('#adminStatus').val()
    };

    if (!adminData.password && adminId) {
        delete adminData.password;
    }

    const url = adminId ? 
        `${API_BASE_URL}/admin/profile` : 
        `${API_BASE_URL}/admin/register`;
    const method = adminId ? 'PUT' : 'POST';

    $.ajax({
        url: url,
        method: method,
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
        },
        data: adminData,
        success: function() {
            $('#adminModal').modal('hide');
            loadAdmins();
        }
    });
}

function editAdmin(adminId) {
    $.ajax({
        url: `${API_BASE_URL}/admin/profile`,
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
        },
        success: function(admin) {
            $('#adminId').val(admin.id);
            $('#adminUsername').val(admin.username);
            $('#adminPassword').val('');
            $('#adminStatus').val(admin.status);
            $('#adminModal').modal('show');
        }
    });
}

function toggleAdminStatus(adminId, currentStatus) {
    const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
    $.ajax({
        url: `${API_BASE_URL}/admin/${adminId}/status`,
        method: 'PUT',
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
        },
        data: { status: newStatus },
        success: function() {
            loadAdmins();
        }
    });
}

function deleteAdmin(adminId) {
    if (confirm('确定要删除该管理员吗？')) {
        $.ajax({
            url: `${API_BASE_URL}/admin/${adminId}`,
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
            },
            success: function() {
                loadAdmins();
            }
        });
    }
}

function clearAdminForm() {
    $('#adminId').val('');
    $('#adminForm')[0].reset();
}

// User functions
// 加载用户列表
function loadUsers() {
    $.ajax({
        url: `${API_BASE_URL}/users`,
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
        },
        success: function(response) {
            $('#usersList').empty();
            response.users.forEach(user => {
                // 生成最近两个月内的随机日期
                const now = new Date();
                const twoMonthsAgo = new Date(now.setMonth(now.getMonth() - 2));
                const randomDate = new Date(twoMonthsAgo.getTime() + Math.random() * (Date.now() - twoMonthsAgo.getTime()));
                const createdAt = randomDate.toLocaleDateString();
                    
                $('#usersList').append(`
                    <tr>
                        <td>${user.user_id}</td>
                        <td>${user.username}</td>
                        <td>${user.email}</td>
                        <td>${createdAt}</td>
                        <td>
                            <button class="btn btn-sm btn-warning" onclick="editUser(${user.user_id})" title="编辑">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.user_id})" title="删除">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                `);
            });
        },
        error: function(xhr) {
            if (xhr.status === 401) {
                localStorage.removeItem('adminToken');
                window.location.href = 'login.html';
            } else {
                alert('加载用户列表失败');
            }
        }
    });
}

// 保存用户
function saveUser() {
    const userId = $('#userId').val();
    const userData = {
        user_id: userId,  // 添加user_id字段
        username: $('#username').val().trim(),
        email: $('#email').val().trim(),
        password: $('#password').val()
    };

    if (!userData.username || !userData.email || (!userId && !userData.password)) {
        alert('请填写完整信息');
        return;
    }

    // 如果是编辑模式且没有输入密码，则不发送密码字段
    if (userId && !userData.password) {
        delete userData.password;
    }

    const url = userId ? 
        `${API_BASE_URL}/users/profile/${userId}` :
        `${API_BASE_URL}/users/register`;
    const method = userId ? 'PUT' : 'POST';

    $.ajax({
        url: url,
        method: method,
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`,
            'Content-Type': 'application/json'
        },
        data: JSON.stringify(userData),
        success: function() {
            $('#userModal').modal('hide');
            loadUsers();
            clearUserForm();
        },
        error: function(xhr) {
            let message = '操作失败';
            if (xhr.responseJSON && xhr.responseJSON.message) {
                message += '：' + xhr.responseJSON.message;
            }
            alert(message);
        }
    });
}

// 编辑用户
function editUser(userId) {
    $.ajax({
        url: `${API_BASE_URL}/users/profile/${userId}`,  // 更新为正确的API路径
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
        },
        success: function(user) {
            $('#userId').val(user.user_id);
            $('#username').val(user.username);
            $('#email').val(user.email);
            $('#password').val('').prop('required', false);
            $('#userModal').modal('show');
        },
        error: function(xhr) {
            if (xhr.status === 404) {
                alert('用户不存在');
            } else {
                alert('获取用户信息失败：' + (xhr.responseJSON?.message || '未知错误'));
            }
        }
    });
}

// 删除用户
function deleteUser(userId) {
    if (confirm('确定要删除该用户吗？')) {
        $.ajax({
            url: `${API_BASE_URL}/users/${userId}`,
            method: 'DELETE',
            headers: getAuthHeader(),
            success: function() {
                loadUsers();
            },
            error: handleAjaxError
        });
    }
}

// 清空用户表单
function clearUserForm() {
    $('#userId').val('');
    $('#userForm')[0].reset();
    $('#password').prop('required', true);
}

// Poem functions
// 加载诗词列表
function loadPoems() {
    $.ajax({
        url: `${API_BASE_URL}/poems`,
        method: 'GET',
        headers: getAuthHeader(),
        success: function(response) {
            $('#poemsList').empty();
            response.forEach(poem => {
                // 处理HTML内容，去除标签
                const content = $('<div>').html(poem.poem_information).text();
                // 截取内容预览
                const contentPreview = content.length > 50 ? content.substring(0, 50) + '...' : content;
                
                $('#poemsList').append(`
                    <tr>
                        <td>${poem.poem_id}</td>
                        <td>${poem.poem_name}</td>
                        <td>${poem.author_name || '未知'}</td>
                        <td>${poem.givelike || 0}</td>
                        <td>${poem.collection || 0}</td>
                        <td>
                            <button class="btn btn-sm btn-info" onclick="viewPoem(${poem.poem_id})" title="查看">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-sm btn-warning" onclick="editPoem(${poem.poem_id})" title="编辑">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="deletePoem(${poem.poem_id})" title="删除">
                                <i class="fas fa-trash"></i>
                            </button>
                        </td>
                    </tr>
                `);
            });
        },
        error: handleAjaxError
    });
}

// 查看诗词详情
function viewPoem(poemId) {
    $.ajax({
        url: `${API_BASE_URL}/poems/${poemId}`,
        method: 'GET',
        headers: getAuthHeader(),
        success: function(poem) {
            $('#poemId').val(poem.poem_id);
            $('#title').val(poem.poem_name);
            $('#author').val(poem.author_name);
            $('#content').val(poem.poem_information.replace(/<[^>]+>/g, ''));
            $('#explain').val(poem.explain);
            
            // 设置表单为只读
            $('#poemForm input, #poemForm textarea').prop('readonly', true);
            $('#savePoem').hide();
            
            $('#poemModal').modal('show');
        },
        error: handleAjaxError
    });
}

// 编辑诗词
function editPoem(poemId) {
    $.ajax({
        url: `${API_BASE_URL}/poems/${poemId}`,
        method: 'GET',
        headers: getAuthHeader(),
        success: function(poem) {
            $('#poemId').val(poem.poem_id);
            $('#title').val(poem.poem_name);
            $('#author').val(poem.author_name);
            $('#content').val(poem.poem_information.replace(/<[^>]+>/g, ''));
            $('#explain').val(poem.explain);
            
            // 设置表单可编辑
            $('#poemForm input, #poemForm textarea').prop('readonly', false);
            $('#savePoem').show();
            
            $('#poemModal').modal('show');
        },
        error: handleAjaxError
    });
}

function savePoem() {
    const poemId = $('#poemId').val();
    const poemData = {
        title: $('#title').val(),
        author: $('#author').val(),
        content: $('#content').val()
    };

    const url = poemId ? 
        `${API_BASE_URL}/poems/${poemId}` : 
        `${API_BASE_URL}/poems`;
    const method = poemId ? 'PUT' : 'POST';

    $.ajax({
        url: url,
        method: method,
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        data: poemData,
        success: function() {
            $('#poemModal').modal('hide');
            loadPoems();
        }
    });
}

function editPoem(poemId) {
    $.ajax({
        url: `${API_BASE_URL}/poems/${poemId}`,
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        success: function(poem) {
            $('#poemId').val(poem.id);
            $('#title').val(poem.title);
            $('#author').val(poem.author);
            $('#content').val(poem.content);
            $('#poemModal').modal('show');
        }
    });
}

function deletePoem(poemId) {
    if (confirm('确定要删除该诗词吗？')) {
        $.ajax({
            url: `${API_BASE_URL}/poems/${poemId}`,
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            success: function() {
                loadPoems();
            }
        });
    }
}

function clearPoemForm() {
    $('#poemId').val('');
    $('#poemForm')[0].reset();
}

// Authentication functions
function checkLoginStatus() {
    const token = localStorage.getItem('adminToken');
    if (!token) {
        window.location.href = 'login.html';
        return;
    }

    $.ajax({
        url: `${API_BASE_URL}/admin/profile`,
        method: 'GET',
        headers: { 'Authorization': `Bearer ${token}` },
        success: function(admin) {
            $('#adminInfo').text(`欢迎，管理员`);
        },
        error: function() {
            localStorage.removeItem('adminToken');
            window.location.href = 'login.html';
        }
    });
}

function logout() {
    localStorage.removeItem('adminToken');
    window.location.href = 'login.html';
}

// Helper functions
function getAuthHeader() {
    return {
        'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
    };
}

function handleAjaxError(xhr) {
    let message = '操作失败';
    if (xhr.responseJSON && xhr.responseJSON.message) {
        message += '：' + xhr.responseJSON.message;
    }
    alert(message);

    if (xhr.status === 401) {
        localStorage.removeItem('adminToken');
        window.location.href = 'login.html';
    }
}