'use client';

import React, { useEffect, useState, useCallback, ChangeEvent, FormEvent, Fragment } from 'react';
import { useAuth, User } from '@/contexts/AuthContext'; // 导入 User 类型
import { useRouter } from 'next/navigation';
import { api } from '@/services/api';
import LoadingSpinner from '@/components/LoadingSpinner';
import Link from 'next/link';
import { Dialog, Transition } from '@headlessui/react'; // Added Dialog and Transition

// 假设的角色枚举，与后端 UserRoleEnum 对应
const ROLES = [
  { label: '普通用户', value: 'user' },
  { label: '管理员', value: 'admin' },
  // { label: '封禁用户', value: 'ban' }, // 根据需要添加
];

interface UserFormData {
  username: string;
  password?: string; // 编辑时可选，新增时必须
  role: string;
  balance: string; // 表单中通常是字符串，提交时转换
}

const UserManagementPage: React.FC = () => {
  const { user: currentUser, isLoading: authLoading, isAuthenticated } = useAuth();
  const router = useRouter();
  const [users, setUsers] = useState<User[]>([]);
  const [pageLoading, setPageLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // --- Modals State (简单示例，实际应用推荐使用组件库) ---
  const [isAddUserModalOpen, setIsAddUserModalOpen] = useState(false);
  const [isEditUserModalOpen, setIsEditUserModalOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [userFormData, setUserFormData] = useState<Partial<UserFormData>>({}); // 使用 Partial 允许部分字段
  const [isLoadingAction, setIsLoadingAction] = useState(false); // Added isLoadingAction state

  const fetchUsers = useCallback(async () => {
    setPageLoading(true);
    setError(null);
    try {
      console.log('UserManagement: Fetching user list...');
      const response = await api.get<User[]>('/user/list'); // 假设API直接返回User数组或BaseResponse<User[]>
      // 根据实际API响应结构调整
      // 如果是 BaseResponse<List<User>>，则需要 response.data.data
      if (response.data && Array.isArray((response.data as any).data)) {
         setUsers((response.data as any).data);
         console.log('UserManagement: Users fetched successfully:', (response.data as any).data.length);
      } else if (Array.isArray(response.data)) { // 如果直接返回数组
         setUsers(response.data);
         console.log('UserManagement: Users fetched successfully (direct array): inconceivable, response.data is BaseResponse, not array itself', response.data.length);
      } 
      else {
        console.error('UserManagement: Unexpected response structure for user list.', response.data);
        const apiError = response.data as any;
        if (apiError && apiError.code === 50000 && apiError.message) {
            setError(`获取用户列表失败：${apiError.message}`);
        } else {
            setError('获取用户列表失败：响应格式不正确或未知错误');
        }
        setUsers([]);
      }
    } catch (err: any) {
      console.error('UserManagement: Error fetching users:', err);
      const errorMessage = err.response?.data?.message || err.message || '获取用户列表时发生错误';
      setError(errorMessage);
      if (err.response?.status === 403) {
        // setError('您没有权限访问此资源。正在重定向...'); // 提示已存在，不再重复
        // setTimeout(() => router.replace('/admin/dashboard'), 2000);
      } else if (err.response?.status === 401) {
        // setError('会话已过期或无效，请重新登录。正在重定向...');
        // setTimeout(() => router.replace('/login'), 2000);
      }
    } finally {
      setPageLoading(false);
    }
  }, []); // 空依赖数组，因为router通常不需要作为依赖

  useEffect(() => {
    if (!authLoading && (!isAuthenticated || !currentUser || currentUser.role !== 'admin')) {
      // 如果认证加载完成，但用户未认证、不是管理员，或用户信息不存在
      console.log('UserManagement: Auth check failed or not admin, redirecting.');
      router.replace(currentUser && currentUser.role === 'user' ? '/dashboard' : '/login');
      return;
    }

    if (isAuthenticated && currentUser && currentUser.role === 'admin') {
      fetchUsers();
    }
  }, [authLoading, isAuthenticated, currentUser, router, fetchUsers]); // 依赖项包含 router

  // 新增删除用户处理函数
  const handleDeleteUser = async (userId: number, username: string) => {
    if (window.confirm(`确定要删除用户 "${username}" (ID: ${userId}) 吗？此操作不可恢复。`)) {
      try {
        setError(null); // 清除之前的错误
        await api.delete(`/user/delete/${userId}`);
        alert(`用户 "${username}" 删除成功!`);
        // 刷新用户列表
        fetchUsers(); 
        // 或者从当前 users state 中移除该用户，以避免重新请求整个列表
        // setUsers(currentUsers => currentUsers.filter(u => u.id !== userId));
      } catch (err: any) {
        console.error('Error deleting user:', err);
        const errorMessage = err.response?.data?.message || err.message || '删除用户失败';
        setError(errorMessage);
        alert(`删除用户 "${username}" 失败: ${errorMessage}`);
      }
    }
  };

  // --- Add User Modal Logic ---
  const handleOpenAddUserModal = () => {
    setUserFormData({ role: 'user', balance: '0' }); // 默认值
    setIsAddUserModalOpen(true);
  };

  const handleAddUser = async (e: FormEvent) => {
    e.preventDefault();
    if (!userFormData.username || !userFormData.password || !userFormData.role) {
        alert('用户名、密码和角色不能为空!');
        return;
    }
    setIsLoadingAction(true); // Set loading true
    setError(null);
    try {
        const payload = {
            username: userFormData.username,
            password: userFormData.password,
            role: userFormData.role,
            balance: parseFloat(userFormData.balance || '0'),
        };
        await api.post('/user/admin/add', payload);
        alert('用户添加成功!');
        setIsAddUserModalOpen(false);
        setEditingUser(null);
        await fetchUsers();
    } catch (err: any) {
        const errorMessage = err.response?.data?.message || err.message || '添加用户失败';
        alert(`添加用户失败: ${errorMessage}`);
        setError(errorMessage);
    } finally {
        setIsLoadingAction(false); // Set loading false
    }
  };

  // --- Edit User Modal Logic ---
  const handleOpenEditUserModal = (userToEdit: User) => {
    setEditingUser(userToEdit);
    setUserFormData({
        username: userToEdit.username,
        role: userToEdit.role,
        balance: userToEdit.balance.toString(),
        password: '' // 密码字段留空，除非用户输入新密码
    });
    setIsEditUserModalOpen(true);
  };

  const handleUpdateUser = async (e: FormEvent) => {
    e.preventDefault();
    if (!editingUser || !userFormData.username || !userFormData.role) {
        alert('用户信息不完整!');
        return;
    }
    setIsLoadingAction(true); // Set loading true
    setError(null);
    try {
        const payload: any = {
            id: editingUser.id,
            username: userFormData.username,
            role: userFormData.role,
            balance: parseFloat(userFormData.balance || '0'),
        };
        if (userFormData.password && userFormData.password.length > 0) {
            payload.password = userFormData.password;
        }
        await api.put('/user/admin/update', payload);
        alert('用户信息更新成功!');
        setIsEditUserModalOpen(false);
        setEditingUser(null);
        await fetchUsers();
    } catch (err: any) {
        const errorMessage = err.response?.data?.message || err.message || '更新用户信息失败';
        alert(`更新用户信息失败: ${errorMessage}`);
        setError(errorMessage);
    } finally {
        setIsLoadingAction(false); // Set loading false
    }
  };

  const handleFormInputChange = (e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setUserFormData(prev => ({ ...prev, [name]: value }));
  };

  const closeModal = () => {
    setIsAddUserModalOpen(false);
    setIsEditUserModalOpen(false);
    // Reset form data if needed, or do it on open
    setUserFormData({ username: '', password: '', role: 'user', balance: '0' });
    setEditingUser(null);
  };

  if (authLoading || pageLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <LoadingSpinner />
      </div>
    );
  }

  // 如果在 authLoading 后仍然未认证或不是管理员，AuthenticatedLayout 或此组件的 useEffect 会处理重定向
  // 但为了防止在重定向前渲染内容，可以加一个判断
  if (!isAuthenticated || !currentUser || currentUser.role !== 'admin') {
    // 此处应该已经被重定向，显示加载动画避免闪烁
    return <div className="flex items-center justify-center min-h-screen"><LoadingSpinner /></div>;
  }
  
  return (
    <div className="container mx-auto p-4 pt-10">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold text-gray-800">用户管理</h1>
        <div>
            <button 
                onClick={handleOpenAddUserModal}
                className="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded-lg mr-3 transition duration-150 ease-in-out"
            >
                新增用户
            </button>
            <Link href="/admin/dashboard" legacyBehavior>
            <a className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-lg transition duration-150 ease-in-out">
                返回管理员主页
            </a>
            </Link>
        </div>
      </div>

      {error && (
        <div className="mb-4 p-4 bg-red-100 text-red-700 border border-red-400 rounded-md">
          {error}
        </div>
      )}

      {/* Add/Edit User Modal using Headless UI */}
      <Transition appear show={isAddUserModalOpen || isEditUserModalOpen} as={Fragment}>
        <Dialog as="div" className="relative z-50" onClose={closeModal}>
          <Transition.Child
            as={Fragment}
            enter="ease-out duration-300"
            enterFrom="opacity-0"
            enterTo="opacity-100"
            leave="ease-in duration-200"
            leaveFrom="opacity-100"
            leaveTo="opacity-0"
          >
            <div className="fixed inset-0 bg-black/30 backdrop-blur-sm" />
          </Transition.Child>

          <div className="fixed inset-0 overflow-y-auto">
            <div className="flex min-h-full items-center justify-center p-4 text-center">
              <Transition.Child
                as={Fragment}
                enter="ease-out duration-300"
                enterFrom="opacity-0 scale-95"
                enterTo="opacity-100 scale-100"
                leave="ease-in duration-200"
                leaveFrom="opacity-100 scale-100"
                leaveTo="opacity-0 scale-95"
              >
                <Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
                  <Dialog.Title
                    as="h3"
                    className="text-lg font-medium leading-6 text-gray-900 mb-4"
                  >
                    {isAddUserModalOpen ? '新增用户' : `编辑用户: ${editingUser?.username || ''}`}
                  </Dialog.Title>
                  
                  {error && <p className="mb-3 text-sm text-red-600 bg-red-100 p-2 rounded">{error}</p>} {/* Display error messages in modal */}

                  <form onSubmit={isAddUserModalOpen ? handleAddUser : handleUpdateUser}>
                    <div className="mb-4">
                      <label htmlFor="username" className="block text-sm font-medium text-gray-700">用户名</label>
                      <input
                        type="text"
                        name="username"
                        id="username"
                        value={userFormData.username}
                        onChange={handleFormInputChange}
                        required
                        className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                      />
                    </div>
                    {/* Password field: only required for add, optional for edit (to change password) */}
                    {(isAddUserModalOpen || isEditUserModalOpen) && (
                      <div className="mb-4">
                        <label htmlFor="password" className="block text-sm font-medium text-gray-700">
                          密码 {isAddUserModalOpen ? '' : '(如需重置请输入新密码)'}
                        </label>
                        <input
                          type="password"
                          name="password"
                          id="password"
                          value={userFormData.password}
                          onChange={handleFormInputChange}
                          required={isAddUserModalOpen} // Only required for new users
                          minLength={isAddUserModalOpen ? 6 : undefined} // Min length for new users
                          className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                          placeholder={isEditUserModalOpen ? "留空则不修改密码" : ""}
                        />
                      </div>
                    )}
                    <div className="mb-4">
                      <label htmlFor="role" className="block text-sm font-medium text-gray-700">角色</label>
                      <select
                        name="role"
                        id="role"
                        value={userFormData.role}
                        onChange={handleFormInputChange}
                        required
                        disabled={isEditUserModalOpen && editingUser?.id === currentUser?.id && currentUser?.role === 'admin'} // Prevent admin from changing own role easily
                        className="mt-1 block w-full px-3 py-2 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                      >
                        <option value="user">User</option>
                        <option value="admin">Admin</option>
                        {/* <option value="ban">Ban</option> */}
                      </select>
                       {isEditUserModalOpen && editingUser?.id === currentUser?.id && currentUser?.role === 'admin' && (
                          <p className="mt-1 text-xs text-red-600">管理员不能在此处修改自己的角色。</p>
                      )}
                    </div>
                    <div className="mb-6">
                      <label htmlFor="balance" className="block text-sm font-medium text-gray-700">余额</label>
                      <input
                        type="number"
                        name="balance"
                        id="balance"
                        value={userFormData.balance}
                        onChange={handleFormInputChange}
                        required
                        step="0.01" // Allow decimal for currency
                        min="0"
                        className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                      />
                    </div>

                    <div className="mt-6 flex items-center justify-end space-x-3">
                      <button
                        type="button"
                        className="inline-flex justify-center rounded-md border border-transparent bg-gray-100 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-500 focus-visible:ring-offset-2"
                        onClick={closeModal}
                      >
                        取消
                      </button>
                      <button
                        type="submit"
                        disabled={isLoadingAction} // Use isLoadingAction here
                        className="inline-flex justify-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 focus-visible:ring-offset-2 disabled:opacity-50"
                      >
                        {isLoadingAction ? (
                          <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                          </svg>
                        ) : isAddUserModalOpen ? '确认新增' : '确认修改'}
                      </button>
                    </div>
                  </form>
                </Dialog.Panel>
              </Transition.Child>
            </div>
          </div>
        </Dialog>
      </Transition>

      <div className="bg-white shadow-md rounded-lg overflow-x-auto">
        <table className="min-w-full leading-normal">
          <thead>
            <tr>
              <th className="px-5 py-3 border-b-2 border-gray-200 bg-gray-100 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                ID
              </th>
              <th className="px-5 py-3 border-b-2 border-gray-200 bg-gray-100 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                用户名
              </th>
              <th className="px-5 py-3 border-b-2 border-gray-200 bg-gray-100 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                角色
              </th>
              <th className="px-5 py-3 border-b-2 border-gray-200 bg-gray-100 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                余额
              </th>
              <th className="px-5 py-3 border-b-2 border-gray-200 bg-gray-100 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                操作
              </th>
            </tr>
          </thead>
          <tbody>
            {users.length > 0 ? (
              users.map((u) => (
                <tr key={u.id} className="hover:bg-gray-50">
                  <td className="px-5 py-4 border-b border-gray-200 bg-white text-sm">
                    <p className="text-gray-900 whitespace-no-wrap">{u.id}</p>
                  </td>
                  <td className="px-5 py-4 border-b border-gray-200 bg-white text-sm">
                    <p className="text-gray-900 whitespace-no-wrap">{u.username}</p>
                  </td>
                  <td className="px-5 py-4 border-b border-gray-200 bg-white text-sm">
                    <span
                      className={`px-2 py-1 font-semibold leading-tight rounded-full text-xs
                        ${u.role === 'admin' ? 'bg-green-100 text-green-700' : ''}
                        ${u.role === 'user' ? 'bg-blue-100 text-blue-700' : ''}
                        ${u.role === 'ban' ? 'bg-red-100 text-red-700' : ''}
                      `}
                    >
                      {u.role}
                    </span>
                  </td>
                  <td className="px-5 py-4 border-b border-gray-200 bg-white text-sm">
                    <p className="text-gray-900 whitespace-no-wrap">¥{u.balance.toFixed(2)}</p>
                  </td>
                  <td className="px-5 py-4 border-b border-gray-200 bg-white text-sm">
                    <button 
                      onClick={() => handleOpenEditUserModal(u)}
                      className="text-indigo-600 hover:text-indigo-900 mr-3 disabled:opacity-50 disabled:cursor-not-allowed"
                      disabled={currentUser?.id === u.id && u.role === 'admin'} // 通常不允许管理员直接编辑自己（特别是角色），或者需要更复杂的逻辑
                    >
                      编辑
                    </button>
                    <button 
                      onClick={() => handleDeleteUser(u.id, u.username)}
                      className="text-red-600 hover:text-red-900 disabled:opacity-50 disabled:cursor-not-allowed"
                      disabled={currentUser?.id === u.id} 
                    >
                      删除
                    </button>
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={5} className="px-5 py-5 border-b border-gray-200 bg-white text-center text-sm">
                  {pageLoading ? '正在加载用户...' : (error ? '加载用户失败' : '没有找到用户数据')}
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default UserManagementPage; 