'use client';
import { useState, useEffect } from 'react';
import { useUser } from '../layout';
import { authFetch, ROLE_NAMES } from '@/lib/auth-client';

export default function UsersPage() {
  const user = useUser();
  const [users, setUsers] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [toast, setToast] = useState(null);

  // Modal
  const [modalOpen, setModalOpen] = useState(false);
  const [editingUser, setEditingUser] = useState(null);
  const [form, setForm] = useState({
    username: '',
    password: '',
    real_name: '',
    role: 'employee',
    department_id: '',
  });
  const [submitting, setSubmitting] = useState(false);
  const [deleteConfirm, setDeleteConfirm] = useState(null);

  const showToast = (message, type = 'success') => {
    setToast({ message, type });
    setTimeout(() => setToast(null), 3000);
  };

  const fetchUsers = async () => {
    try {
      const res = await authFetch('/api/users');
      const data = await res.json();
      setUsers(data.users || data || []);
    } catch {
      showToast('加载用户列表失败', 'error');
    } finally {
      setLoading(false);
    }
  };

  const fetchDepartments = async () => {
    try {
      const res = await authFetch('/api/departments');
      const data = await res.json();
      setDepartments(data.departments || data || []);
    } catch {
      // ignore
    }
  };

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

  const openCreateModal = () => {
    setEditingUser(null);
    setForm({ username: '', password: '', real_name: '', role: 'employee', department_id: '' });
    setModalOpen(true);
  };

  const openEditModal = (u) => {
    setEditingUser(u);
    setForm({
      username: u.username,
      password: '',
      real_name: u.real_name,
      role: u.role,
      department_id: u.department_id || '',
    });
    setModalOpen(true);
  };

  const handleSubmit = async () => {
    if (!form.username.trim()) { showToast('请输入用户名', 'error'); return; }
    if (!editingUser && !form.password) { showToast('请输入密码', 'error'); return; }
    if (!form.real_name.trim()) { showToast('请输入姓名', 'error'); return; }
    if (!form.role) { showToast('请选择角色', 'error'); return; }

    setSubmitting(true);
    try {
      const body = { ...form };
      if (editingUser && !body.password) {
        delete body.password;
      }
      if (body.department_id === '') {
        body.department_id = null;
      }

      const url = editingUser ? `/api/users/${editingUser.id}` : '/api/users';
      const method = editingUser ? 'PUT' : 'POST';

      const res = await authFetch(url, {
        method,
        body: JSON.stringify(body),
      });
      const data = await res.json();

      if (!res.ok) {
        showToast(data.error || '操作失败', 'error');
      } else {
        showToast(editingUser ? '用户已更新' : '用户已创建');
        setModalOpen(false);
        fetchUsers();
      }
    } catch {
      showToast('操作失败，请重试', 'error');
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (userId) => {
    try {
      const res = await authFetch(`/api/users/${userId}`, { method: 'DELETE' });
      const data = await res.json();
      if (!res.ok) {
        showToast(data.error || '删除失败', 'error');
      } else {
        showToast('用户已删除');
        fetchUsers();
      }
    } catch {
      showToast('删除失败', 'error');
    }
    setDeleteConfirm(null);
  };

  const toggleStatus = async (targetUser) => {
    const newStatus = targetUser.status === 1 ? 0 : 1;
    try {
      const res = await authFetch(`/api/users/${targetUser.id}`, {
        method: 'PUT',
        body: JSON.stringify({ status: newStatus }),
      });
      const data = await res.json();
      if (!res.ok) {
        showToast(data.error || '操作失败', 'error');
      } else {
        showToast(newStatus === 1 ? '用户已启用' : '用户已停用');
        fetchUsers();
      }
    } catch {
      showToast('操作失败，请重试', 'error');
    }
  };

  const getDepartmentName = (deptId) => {
    const dept = departments.find(d => d.id === deptId);
    return dept ? dept.name : '-';
  };

  if (loading) {
    return (
      <div className="loading-overlay">
        <div className="loading-spinner"></div>
      </div>
    );
  }

  return (
    <div className="animate-fadeIn">
      {/* Toast */}
      {toast && (
        <div className="toast-container">
          <div className={`toast toast-${toast.type}`}>
            {toast.type === 'success' ? '✅' : '❌'} {toast.message}
          </div>
        </div>
      )}

      {/* Header */}
      <div className="page-header">
        <div>
          <h1 className="page-title">用户管理</h1>
          <p className="page-subtitle">管理系统用户和角色权限</p>
        </div>
        <button className="btn btn-primary" onClick={openCreateModal}>
          + 新增用户
        </button>
      </div>

      {/* Table */}
      <div className="card">
        <div className="table-container">
          <table className="data-table">
            <thead>
              <tr>
                <th>用户名</th>
                <th>姓名</th>
                <th>角色</th>
                <th>部门</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {users.length === 0 ? (
                <tr>
                  <td colSpan="6">
                    <div className="empty-state">
                      <div className="empty-state-icon">👥</div>
                      <div className="empty-state-text">暂无用户数据</div>
                    </div>
                  </td>
                </tr>
              ) : (
                users.map(u => (
                  <tr key={u.id}>
                    <td style={{ fontWeight: 500 }}>{u.username}</td>
                    <td>{u.real_name}</td>
                    <td>
                      <span className="status-badge" style={{
                        background: u.role === 'admin' ? '#fef3c7' : '#eef2ff',
                        color: u.role === 'admin' ? '#d97706' : '#6366f1',
                      }}>
                        {ROLE_NAMES[u.role] || u.role}
                      </span>
                    </td>
                    <td>{getDepartmentName(u.department_id)}</td>
                    <td>
                      <span
                        className="status-badge"
                        style={{
                          background: u.status === 1 || u.status === 'active' ? 'var(--success-light)' : 'var(--gray-100)',
                          color: u.status === 1 || u.status === 'active' ? 'var(--success)' : 'var(--gray-400)',
                        }}
                      >
                        {u.status === 1 || u.status === 'active' ? '启用' : '停用'}
                      </span>
                    </td>
                    <td>
                      <div style={{ display: 'flex', gap: 8 }}>
                        <button className="btn btn-sm btn-outline" onClick={() => openEditModal(u)}>
                          编辑
                        </button>
                        {u.id !== user?.id && (
                          <>
                            <button
                              className="btn btn-sm btn-outline"
                              style={{
                                color: u.status === 1 ? '#ef4444' : '#10b981',
                                borderColor: u.status === 1 ? '#fecaca' : '#a7f3d0',
                              }}
                              onClick={() => toggleStatus(u)}
                            >
                              {u.status === 1 ? '🚫 停用' : '✅ 启用'}
                            </button>
                            <button
                              className="btn btn-sm btn-danger"
                              onClick={() => setDeleteConfirm(u)}
                            >
                              删除
                            </button>
                          </>
                        )}
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Create/Edit Modal */}
      {modalOpen && (
        <div className="modal-overlay" onClick={() => setModalOpen(false)}>
          <div className="modal-content" onClick={e => e.stopPropagation()}>
            <div className="modal-header">
              <h3 className="modal-title">{editingUser ? '编辑用户' : '新增用户'}</h3>
              <button className="modal-close" onClick={() => setModalOpen(false)}>✕</button>
            </div>
            <div className="modal-body">
              <div className="form-group">
                <label className="form-label">用户名 <span className="required">*</span></label>
                <input
                  type="text"
                  className="form-input"
                  placeholder="请输入用户名"
                  value={form.username}
                  onChange={e => setForm(prev => ({ ...prev, username: e.target.value }))}
                  disabled={!!editingUser}
                />
              </div>
              <div className="form-group">
                <label className="form-label">
                  密码 {!editingUser && <span className="required">*</span>}
                </label>
                <input
                  type="password"
                  className="form-input"
                  placeholder={editingUser ? '留空则不修改' : '请输入密码'}
                  value={form.password}
                  onChange={e => setForm(prev => ({ ...prev, password: e.target.value }))}
                />
                {editingUser && <div className="form-hint">留空则不修改密码</div>}
              </div>
              <div className="form-group">
                <label className="form-label">姓名 <span className="required">*</span></label>
                <input
                  type="text"
                  className="form-input"
                  placeholder="请输入姓名"
                  value={form.real_name}
                  onChange={e => setForm(prev => ({ ...prev, real_name: e.target.value }))}
                />
              </div>
              <div className="form-group">
                <label className="form-label">角色 <span className="required">*</span></label>
                <select
                  className="form-select"
                  value={form.role}
                  onChange={e => setForm(prev => ({ ...prev, role: e.target.value }))}
                >
                  <option value="employee">员工</option>
                  <option value="supervisor">部门主管</option>
                  <option value="finance">财务部</option>
                  <option value="secretary">秘书长</option>
                  <option value="admin">系统管理员</option>
                </select>
              </div>
              <div className="form-group">
                <label className="form-label">部门</label>
                <select
                  className="form-select"
                  value={form.department_id}
                  onChange={e => setForm(prev => ({ ...prev, department_id: e.target.value }))}
                >
                  <option value="">请选择部门</option>
                  {departments.map(d => (
                    <option key={d.id} value={d.id}>{d.name}</option>
                  ))}
                </select>
              </div>
            </div>
            <div className="modal-footer">
              <button className="btn btn-ghost" onClick={() => setModalOpen(false)}>取消</button>
              <button className="btn btn-primary" disabled={submitting} onClick={handleSubmit}>
                {submitting ? '保存中...' : '保存'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {deleteConfirm && (
        <div className="modal-overlay" onClick={() => setDeleteConfirm(null)}>
          <div className="modal-content" onClick={e => e.stopPropagation()} style={{ maxWidth: 420 }}>
            <div className="modal-header">
              <h3 className="modal-title">确认删除</h3>
              <button className="modal-close" onClick={() => setDeleteConfirm(null)}>✕</button>
            </div>
            <div className="modal-body">
              <p style={{ fontSize: 15, color: 'var(--text-dark-secondary)' }}>
                确定要删除用户 <strong>{deleteConfirm.real_name}</strong>（{deleteConfirm.username}）吗？
                此操作无法撤销。
              </p>
            </div>
            <div className="modal-footer">
              <button className="btn btn-ghost" onClick={() => setDeleteConfirm(null)}>取消</button>
              <button className="btn btn-danger" onClick={() => handleDelete(deleteConfirm.id)}>
                确认删除
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
