import React, { useState, useEffect } from 'react';
import { useAuth } from '../../contexts/AuthContext';
import { userAPI } from '../../services/user';

const UserList = () => {
  const { user } = useAuth();
  const [list, setList] = useState([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  const [modalVisible, setModalVisible] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [form, setForm] = useState({
    username: '',
    password: '',
    real_name: '',
    department: '',
    role: 'other',
    email: '',
    phone: '',
  });

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

  const fetchUsers = async (params = {}) => {
    try {
      setLoading(true);
      const result = await userAPI.getList({
        page: pagination.current,
        page_size: pagination.pageSize,
        ...params,
      });
      setList(result.items || []);
      setTotal(result.total || 0);
    } catch (error) {
      console.error('Failed to fetch users:', error);
      alert('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handlePageChange = (page) => {
    setPagination({ ...pagination, current: page });
    fetchUsers({ page });
  };

  const handleCreate = () => {
    setEditingId(null);
    setForm({
      username: '',
      password: '',
      real_name: '',
      department: '',
      role: 'other',
      email: '',
      phone: '',
    });
    setModalVisible(true);
  };

  const handleEdit = async (id) => {
    try {
      const user = await userAPI.getDetail(id);
      setForm({ ...user, password: '' });
      setEditingId(id);
      setModalVisible(true);
    } catch (error) {
      console.error('Failed to fetch user detail:', error);
      alert('获取用户详情失败');
    }
  };

  const handleDelete = async (id) => {
    if (!window.confirm('确定要删除该用户吗？')) {
      return;
    }

    try {
      await userAPI.delete(id);
      alert('用户删除成功');
      fetchUsers();
    } catch (error) {
      console.error('Failed to delete user:', error);
      alert('删除用户失败');
    }
  };

  const handleResetPassword = async (id) => {
    const newPassword = window.prompt('请输入新密码：');
    if (!newPassword) return;

    if (newPassword.length < 6) {
      alert('密码至少6个字符');
      return;
    }

    try {
      await userAPI.resetPassword(id, newPassword);
      alert('密码重置成功');
    } catch (error) {
      console.error('Failed to reset password:', error);
      alert('密码重置失败');
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    const requiredFields = ['username', 'password', 'real_name', 'department', 'role'];
    const missingFields = requiredFields.filter(field => !form[field]);

    if (missingFields.length > 0) {
      alert(`请填写必填字段: ${missingFields.join(', ')}`);
      return;
    }

    if (form.username.length < 3) {
      alert('用户名至少3个字符');
      return;
    }

    if (form.password.length < 6) {
      alert('密码至少6个字符');
      return;
    }

    try {
      if (editingId) {
        await userAPI.update(editingId, form);
        alert('用户更新成功');
      } else {
        await userAPI.create(form);
        alert('用户创建成功');
      }

      setModalVisible(false);
      fetchUsers();
    } catch (error) {
      console.error('Failed to save user:', error);
      alert('保存用户失败');
    }
  };

  const handleCancel = () => {
    setModalVisible(false);
    setEditingId(null);
    setForm({
      username: '',
      password: '',
      real_name: '',
      department: '',
      role: 'other',
      email: '',
      phone: '',
    });
  };

  return (
    <div>
      <h1 style={{ fontSize: '24px', marginBottom: '24px' }}>
        用户管理
      </h1>

      <div style={{ marginBottom: '16px' }}>
        <input
          type="text"
          placeholder="搜索用户名、真实姓名、邮箱..."
          style={{
            padding: '8px 12px',
            border: '1px solid #d9d9d9d9',
            borderRadius: '4px',
            fontSize: '14px',
            width: '300px',
          }}
        />
        <button
          className="btn btn-primary"
          onClick={handleCreate}
        >
          新建用户
        </button>
      </div>

      {loading ? (
        <div style={{ textAlign: 'center', padding: '40px' }}>加载中...</div>
      ) : list.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
          暂无用户
        </div>
      ) : (
        <>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ background: '#fafafa' }}>
                <th style={{ padding: '12px 16px', textAlign: 'left', fontSize: '14px', fontWeight: 600, borderBottom: '1px solid #e8e8e8' }}>
                  用户名
                </th>
                <th style={{ padding: '12px 16px', textAlign: 'left', fontSize: '14px', fontWeight: 600', borderBottom: '1px solid #e8e8e8' }}>
                  真实姓名
                </th>
                <th style={{ padding: '12px 16px', textAlign: 'left', fontSize: '14px', fontWeight: 600', borderBottom: '1px solid #e8e8e8' }}>
                  部门
                </th>
                <th style={{ padding: '12px 16px', textAlign: 'left', fontSize: '14px', fontWeight: 600', borderBottom: '1px solid #e8e8e8' }}>
                  角色
                </th>
                <th style={{ padding: '12px 16px', textAlign: 'center', fontSize: '14px', fontWeight: 600', borderBottom: '1px solid #e8e8e8' }}>
                  操作
                </th>
              </tr>
            </thead>
            <tbody>
              {list.map((user) => (
                <tr
                  key={user.id}
                  style={{
                    borderBottom: '1px solid #f0f0f0',
                  }}
                >
                  <td style={{ padding: '12px 16px', fontSize: '14px', color: '#666' }}>
                    {user.username}
                  </td>
                  <td style={{ padding: '12px 16px', fontSize: '14px', color: '#333' }}>
                    {user.real_name}
                  </td>
                  <td style={{ padding: '12px 16px', fontSize: '14px', color: '#666' }}>
                    {user.department}
                  </td>
                  <td style={{ padding: '12px 16px', fontSize: '14px', color: '#666' }}>
                    {user.role === 'admin' ? '管理员' : user.role === 'market' ? '市场部' : '其他'}
                  </td>
                  <td style={{ padding: '12px 16px', fontSize: '14px', textAlign: 'center' }}>
                    <button className="btn btn-link" onClick={() => handleEdit(user.id)}>
                      编辑
                    </button>
                    <button className="btn btn-danger" onClick={() => handleDelete(user.id)}>
                      删除
                    </button>
                    <button className="btn btn-link" onClick={() => handleResetPassword(user.id)}>
                      重置密码
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          <div
            style={{
              marginTop: '24px',
              display: 'flex',
              justifyContent: 'center',
              gap: '12px',
            }}
          >
            {total > pagination.pageSize && (
              <>
                <button
                  className="btn btn-default"
                  disabled={pagination.current === 1}
                  onClick={() => handlePageChange(pagination.current - 1)}
                >
                  上一页
                </button>
                <span>
                  {pagination.current} / {Math.ceil(total / pagination.pageSize)}
                </span>
                <button
                  className="btn btn-default"
                  disabled={pagination.current >= Math.ceil(total / pagination.pageSize)}
                  onClick={() => handlePageChange(pagination.current + 1)}
                >
                  下一页
                </button>
              </>
            )}
          </div>
        </>
      )}
      {modalVisible && (
        <div
          style={{
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            background: 'rgba(0, 0, 0, 0.45)',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            zIndex: 1000,
          }}
          onClick={handleCancel}
        >
          <div
            style={{
              background: '#ffffff',
              width: '800px',
              maxWidth: '90vw',
              maxHeight: '90vh',
              borderRadius: '8px',
              boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <div
              style={{
                padding: '16px 24px',
                borderBottom: '1px solid #e8e8e8',
                fontSize: '16px',
                fontWeight: 600',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}
            >
              {editingId ? '编辑用户' : '新建用户'}
              <button
                style={{
                  background: 'transparent',
                  border: 'none',
                  fontSize: '20px',
                  cursor: 'pointer',
                  color: '#999',
                }}
                onClick={handleCancel}
              >
                ×
              </button>
            </div>
            <form onSubmit={handleSubmit}>
              <div style={{ padding: '24px' }}>
                <div style={{ marginBottom: '20px' }}>
                  <label
                    style={{
                      display: 'block',
                      marginBottom: '8px',
                      color: '#333',
                      fontSize: '14px',
                      fontWeight: '500',
                    }}
                  >
                    用户名 *
                  </label>
                  <input
                    type="text"
                    name="username"
                    value={form.username}
                    onChange={handleChange}
                    required
                    disabled={!!editingId}
                    style={{
                      width: '100%',
                      height: '32px',
                      padding: '4px 12px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '4px',
                      fontSize: '14px',
                    }}
                  />
                </div>
                <div style={{ marginBottom: '20px' }}>
                  <label
                    style={{
                      display: 'block',
                      marginBottom: '8px',
                      color: '#333',
                      fontSize: '14px',
                      fontWeight: '500',
                    }}
                  >
                    密码 *
                  </label>
                  <input
                    type="password"
                    name="password"
                    value={form.password}
                    onChange={handleChange}
                    required={!editingId}
                    placeholder={editingId ? '留空不修改' : '请输入密码'}
                    style={{
                      width: '100%',
                      height: '32px',
                      padding: '4px 12px',
                      border: '1px solid #d9d9d9d9',
                      borderRadius: '4px',
                      fontSize: '14px',
                    }}
                  />
                </div>
                <div style={{ marginBottom: '20px' }}>
                  <label
                    style={{
                      display: 'block',
                      marginBottom: '8px',
                      color: '#333',
                      fontSize: '14px',
                      fontWeight: '500',
                    }}
                  >
                    真实姓名 *
                  </label>
                  <input
                    type="text"
                    name="real_name"
                    value={form.real_name}
                    onChange={handleChange}
                    required
                    style={{
                      width: '100%',
                      height: '32px',
                      padding: '4px 12px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '4px',
                      fontSize: '14px',
                    }}
                  />
                </div>
                <div style={{ marginBottom: '20px' }}>
                  <label
                    style={{
                      display: 'block',
                      marginBottom: '8px',
                      color: '#333',
                      fontSize: '14px',
                      fontWeight: '500',
                    }}
                  >
                    部门 *
                  </label>
                  <select
                    name="department"
                    value={form.department}
                    onChange={handleChange}
                    required
                    style={{
                      width: '100%',
                      height: '32px',
                      padding: '4px 12px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '4px',
                      fontSize: '14px',
                    }}
                  >
                    <option value="">请选择部门</option>
                    <option value="管理部">管理部</option>
                    <option value="市场部">市场部</option>
                    <option value="技术部">技术部</option>
                    <option value="财务部">财务部</option>
                    <option value="项目部">项目部</option>
                  </select>
                </div>
                <div style={{ marginBottom: '20px' }}>
                  <label
                    style={{
                      display: 'block',
                      marginBottom: '8px',
                      color: '#333',
                      fontSize: '14px',
                      fontWeight: '500',
                    }}
                  >
                    角色 *
                  </label>
                  <select
                    name="role"
                    value={form.role}
                    onChange={handleChange}
                    required
                    style={{
                      width: '100%',
                      height: '32px',
                      padding: '4px 12px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '4px',
                      fontSize: '14px',
                    }}
                  >
                    <option value="">请选择角色</option>
                    <option value="admin">管理员</option>
                    <option value="market">市场部</option>
                    <option value="other">其他</option>
                  </select>
                </div>
                <div style={{ marginBottom: '20px' }}>
                  <label
                    style={{
                      display: 'block',
                      marginBottom: '8px',
                      color: '#333',
                      fontSize: '14px',
                      fontWeight: '500',
                    }}
                  >
                    邮箱
                  </label>
                  <input
                    type="email"
                    name="email"
                    value={form.email}
                    onChange={handleChange}
                    placeholder="example@example.com"
                    style={{
                      width: '100%',
                      height: '32px',
                      padding: '4px 12px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '4px',
                      fontSize: '14px',
                    }}
                  />
                </div>
                <div style={{ marginBottom: '20px' }}>
                  <label
                    style={{
                      display: 'block',
                      marginBottom: '8px',
                      color: '#333',
                      fontSize: '14px',
                      fontWeight: '500',
                    }}
                  >
                    电话
                  </label>
                  <input
                    type="tel"
                    name="phone"
                    value={form.phone}
                    onChange={handleChange}
                    placeholder="请输入手机号"
                    style={{
                      width: '100%',
                      height: '32px',
                      padding: '4px 12px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '4px',
                      fontSize: '14px',
                    }}
                  />
                </div>
                <div
                  style={{
                    marginTop: '24px',
                    padding: '16px 24px',
                    borderTop: '1px solid #e8e8e8',
                    display: 'flex',
                    justifyContent: 'flex',
                    gap: '12px',
                  }}
                >
                  <button
                    className="btn btn-default"
                    onClick={handleCancel}
                  >
                    取消
                  </button>
                  <button
                    type="submit"
                    className="btn btn-primary"
                  >
                    保存
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default UserList;
