import { useEffect, useState, useCallback } from 'react';
import { adminApi } from '../lib/api';
import type { AdminUser, AdminUserDetail, Team } from '../types';
import { showToast } from '../components/Toast';
import { ConfirmModal } from '../components/ConfirmModal';
import { Select } from '../components/Select';
import styles from './UsersPage.module.css';

export function UsersPage() {
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [teamFilter, setTeamFilter] = useState('');
  const [teams, setTeams] = useState<Team[]>([]);
  const [loading, setLoading] = useState(true);
  const pageSize = 20;

  // Quota edit modal
  const [editUser, setEditUser] = useState<AdminUser | null>(null);
  const [editDaily, setEditDaily] = useState('');
  const [editMonthly, setEditMonthly] = useState('');
  const [editSpendingLimit, setEditSpendingLimit] = useState('');

  // User detail drawer
  const [detailUser, setDetailUser] = useState<AdminUserDetail | null>(null);
  const [drawerOpen, setDrawerOpen] = useState(false);

  // Confirm toggle
  const [confirmUser, setConfirmUser] = useState<AdminUser | null>(null);

  // Reset password modal
  const [resetPwUser, setResetPwUser] = useState<AdminUser | null>(null);
  const [resetPwValue, setResetPwValue] = useState('');
  const [resetPwError, setResetPwError] = useState('');

  // Inline username edit
  const [editingUsernameId, setEditingUsernameId] = useState<number | null>(null);
  const [editingUsernameValue, setEditingUsernameValue] = useState('');

  // Create user modal
  const [createOpen, setCreateOpen] = useState(false);
  const [newUsername, setNewUsername] = useState('');
  const [newEmail, setNewEmail] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [newDaily, setNewDaily] = useState('50');
  const [newMonthly, setNewMonthly] = useState('500');
  const [newIsStaff, setNewIsStaff] = useState(false);
  const [createError, setCreateError] = useState('');

  // Load teams for filter dropdown
  useEffect(() => {
    adminApi.getTeams().then(({ data }) => setTeams(data.results)).catch(() => {});
  }, []);

  const fetchUsers = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await adminApi.getUsers({
        page, page_size: pageSize, search, status: statusFilter,
        team_id: teamFilter ? Number(teamFilter) : undefined,
      });
      setUsers(data.results);
      setTotal(data.total);
    } catch {
      showToast('加载用户列表失败');
    } finally {
      setLoading(false);
    }
  }, [page, search, statusFilter, teamFilter]);

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

  const handleSearch = () => {
    setPage(1);
    fetchUsers();
  };

  const handleToggleStatus = async (user: AdminUser) => {
    try {
      await adminApi.updateUserStatus(user.id, !user.is_active);
      showToast(user.is_active ? '已禁用用户' : '已启用用户');
      fetchUsers();
    } catch {
      showToast('操作失败');
    }
  };

  const openEditModal = (user: AdminUser) => {
    setEditUser(user);
    setEditDaily(String(user.daily_generation_limit ?? 50));
    setEditMonthly(String(user.monthly_generation_limit ?? 500));
    setEditSpendingLimit(String(user.spending_limit ?? -1));
  };

  const handleSaveQuota = async () => {
    if (!editUser) return;
    try {
      await adminApi.updateUserQuota(editUser.id, Number(editDaily), Number(editMonthly), Number(editSpendingLimit));
      showToast('配额已更新');
      setEditUser(null);
      fetchUsers();
    } catch {
      showToast('更新失败');
    }
  };

  const openDrawer = async (userId: number) => {
    try {
      const { data } = await adminApi.getUserDetail(userId);
      setDetailUser(data);
      setDrawerOpen(true);
    } catch {
      showToast('加载用户详情失败');
    }
  };

  const resetCreateForm = () => {
    setNewUsername(''); setNewEmail(''); setNewPassword('');
    setNewDaily('50'); setNewMonthly('500'); setNewIsStaff(false);
    setCreateError('');
  };

  const handleCreateUser = async () => {
    setCreateError('');
    if (!newUsername.trim()) { setCreateError('请输入用户名'); return; }
    if (!newEmail.trim()) { setCreateError('请输入邮箱'); return; }
    if (newPassword.length < 6) { setCreateError('密码至少6位'); return; }
    try {
      await adminApi.createUser({
        username: newUsername.trim(),
        email: newEmail.trim(),
        password: newPassword,
        daily_generation_limit: Number(newDaily),
        monthly_generation_limit: Number(newMonthly),
        is_staff: newIsStaff,
      });
      showToast('用户创建成功');
      setCreateOpen(false);
      resetCreateForm();
      fetchUsers();
    } catch (err: any) {
      const msg = err.response?.data?.error || err.response?.data?.username?.[0] || '创建失败';
      setCreateError(msg);
    }
  };

  const startEditUsername = (u: AdminUser) => {
    setEditingUsernameId(u.id);
    setEditingUsernameValue(u.username);
  };

  const cancelEditUsername = () => {
    setEditingUsernameId(null);
    setEditingUsernameValue('');
  };

  const handleSaveUsername = async (u: AdminUser) => {
    const newName = editingUsernameValue.trim();
    if (!newName) { showToast('请输入用户名'); return; }
    if (newName === u.username) { cancelEditUsername(); return; }
    try {
      await adminApi.updateUserUsername(u.id, newName);
      showToast(`已更新用户名为「${newName}」`);
      cancelEditUsername();
      fetchUsers();
    } catch (e: any) {
      showToast(e.response?.data?.error || '操作失败');
    }
  };

  const handleToggleObserver = async (u: AdminUser) => {
    try {
      const next = !u.is_observer;
      await adminApi.toggleUserObserver(u.id, next);
      showToast(
        next
          ? `已将「${u.username}」设为观察者（需该用户重新登录后生效）`
          : `已取消「${u.username}」的观察者标记`
      );
      fetchUsers();
    } catch (e: any) {
      showToast(e.response?.data?.error || '操作失败');
    }
  };

  const handleResetPassword = async () => {
    if (!resetPwUser) return;
    setResetPwError('');
    if (resetPwValue.length < 8) { setResetPwError('密码至少8位'); return; }
    try {
      await adminApi.resetUserPassword(resetPwUser.id, resetPwValue);
      showToast(`已重置 ${resetPwUser.username} 的密码`);
      setResetPwUser(null);
      setResetPwValue('');
    } catch {
      setResetPwError('重置失败');
    }
  };

  const totalPages = Math.ceil(total / pageSize);

  return (
    <div className={styles.page}>
      <h1 className={styles.title}>用户管理</h1>

      <div className={styles.filters}>
        <div className={styles.searchGroup}>
          <input
            type="text"
            className={styles.searchInput}
            placeholder="搜索用户名/邮箱..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
          />
          <Select
            value={statusFilter}
            onChange={(v) => { setStatusFilter(v); setPage(1); }}
            placeholder="全部状态"
            options={[
              { label: '全部状态', value: '' },
              { label: '启用', value: 'active' },
              { label: '禁用', value: 'disabled' },
            ]}
          />
          <Select
            value={teamFilter}
            onChange={(v) => { setTeamFilter(v); setPage(1); }}
            placeholder="全部团队"
            options={[{ label: '全部团队', value: '' }, ...teams.map((t) => ({ label: t.name, value: String(t.id) }))]}
          />
          <button className={styles.searchBtn} onClick={handleSearch}>查询</button>
        </div>
        <div className={styles.searchGroup}>
          <button className={styles.refreshBtn} onClick={fetchUsers}>刷新</button>
          <button className={styles.createBtn} onClick={() => { resetCreateForm(); setCreateOpen(true); }}>+ 新增用户</button>
        </div>
      </div>

      <div className={styles.tableWrapper}>
        <table className={styles.table}>
          <thead>
            <tr>
              <th>用户名</th>
              <th>团队</th>
              <th>邮箱</th>
              <th>注册时间</th>
              <th>状态</th>
              <th>日生成上限</th>
              <th>月生成上限</th>
              <th>总额度</th>
              <th>今日生成/消费</th>
              <th>本月生成/消费</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              Array.from({ length: 5 }).map((_, i) => (
                <tr key={i}>
                  {Array.from({ length: 11 }).map((_, j) => (
                    <td key={j}><div className={styles.skeletonCell} /></td>
                  ))}
                </tr>
              ))
            ) : users.length === 0 ? (
              <tr><td colSpan={11} className={styles.empty}>暂无数据</td></tr>
            ) : (
              users.map((u) => (
                <tr key={u.id}>
                  <td>
                    {editingUsernameId === u.id ? (
                      <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center', flexWrap: 'nowrap' }}>
                        <input
                          type="text"
                          value={editingUsernameValue}
                          onChange={(e) => setEditingUsernameValue(e.target.value)}
                          onKeyDown={(e) => {
                            if (e.key === 'Enter') handleSaveUsername(u);
                            else if (e.key === 'Escape') cancelEditUsername();
                          }}
                          autoFocus
                          style={{ width: 140, padding: '3px 6px', borderRadius: 4, border: '1px solid var(--color-border-card)', background: 'var(--color-bg-page)', color: 'var(--color-text-primary)', fontSize: 13 }}
                        />
                        <button className={styles.editBtn} onClick={() => handleSaveUsername(u)} style={{ fontSize: 12, padding: '4px 10px', whiteSpace: 'nowrap' }}>保存</button>
                        <button className={styles.editBtn} onClick={cancelEditUsername} style={{ fontSize: 12, padding: '4px 10px', whiteSpace: 'nowrap' }}>取消</button>
                      </span>
                    ) : (
                      <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center', flexWrap: 'nowrap' }}>
                        <button className={styles.usernameLink} onClick={() => openDrawer(u.id)}>
                          <span style={{
                            display: 'inline-block', width: 8, height: 8, borderRadius: '50%',
                            background: u.is_online ? '#00b894' : '#555', marginRight: 6,
                            verticalAlign: 'middle',
                          }} />
                          {u.username}
                        </button>
                        {u.username !== 'admin' && (
                          <button
                            className={styles.editBtn}
                            onClick={() => startEditUsername(u)}
                            title="修改用户名"
                            style={{ fontSize: 12, padding: '2px 8px', whiteSpace: 'nowrap' }}
                          >
                            改名
                          </button>
                        )}
                        {u.is_observer && (
                          <span
                            className={styles.statusBadge}
                            style={{ background: 'var(--color-info-bg)', color: 'var(--color-info)' }}
                            title="该团管被标记为观察者，可查看全局内容资产"
                          >
                            观察者
                          </span>
                        )}
                      </span>
                    )}
                  </td>
                  <td>{u.team_name || '-'}</td>
                  <td>{u.email}</td>
                  <td>{new Date(u.date_joined).toLocaleDateString('zh-CN')}</td>
                  <td>
                    <span className={`${styles.statusBadge} ${u.is_active ? styles.active : styles.disabled}`}>
                      {u.is_active ? '启用' : '禁用'}
                    </span>
                    {!u.is_active && u.disabled_by && (
                      <span style={{ fontSize: 11, color: 'var(--color-text-secondary)', marginLeft: 4 }}>
                        ({u.disabled_by === 'system' ? '系统' : '管理员'})
                      </span>
                    )}
                  </td>
                  <td>{(u.daily_generation_limit ?? -1) === -1 ? '不限' : u.daily_generation_limit + '次'}</td>
                  <td>{(u.monthly_generation_limit ?? -1) === -1 ? '不限' : u.monthly_generation_limit + '次'}</td>
                  <td>{(u.spending_limit ?? -1) === -1 ? '不限' : '¥' + (u.total_spent || 0).toFixed(2) + ' / ¥' + (u.spending_limit).toFixed(2)}</td>
                  <td>{(u.generations_today || 0) + '次 / ¥' + (u.spent_today || 0).toFixed(2)}</td>
                  <td>{(u.generations_this_month || 0) + '次 / ¥' + (u.spent_this_month || 0).toFixed(2)}</td>
                  <td>
                    <div className={styles.actions}>
                      <button className={styles.editBtn} onClick={() => openEditModal(u)}>编辑</button>
                      <button className={styles.editBtn} onClick={() => { setResetPwUser(u); setResetPwValue(''); setResetPwError(''); }}>重置密码</button>
                      {u.is_team_admin && u.team_id && (
                        <button
                          className={styles.editBtn}
                          onClick={() => handleToggleObserver(u)}
                          title={u.is_observer ? '取消该团管的观察者标记' : '把该团管标记为观察者(可看全局内容资产，无费用)'}
                        >
                          {u.is_observer ? '取消观察者' : '设为观察者'}
                        </button>
                      )}
                      <button
                        className={`${styles.toggleBtn} ${u.is_active ? styles.disableBtn : styles.enableBtn}`}
                        onClick={() => setConfirmUser(u)}
                      >
                        {u.is_active ? '禁用' : '启用'}
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {totalPages > 1 && (
        <div className={styles.pagination}>
          <span className={styles.pageInfo}>共 {total} 条</span>
          <div className={styles.pageButtons}>
            <button disabled={page <= 1} onClick={() => setPage(page - 1)}>&lt;</button>
            {Array.from({ length: Math.min(totalPages, 5) }, (_, i) => {
              let p: number;
              if (totalPages <= 5) p = i + 1;
              else if (page <= 3) p = i + 1;
              else if (page >= totalPages - 2) p = totalPages - 4 + i;
              else p = page - 2 + i;
              return (
                <button key={p} className={page === p ? styles.activePage : ''} onClick={() => setPage(p)}>
                  {p}
                </button>
              );
            })}
            <button disabled={page >= totalPages} onClick={() => setPage(page + 1)}>&gt;</button>
          </div>
        </div>
      )}

      <ConfirmModal
        open={!!confirmUser}
        title={confirmUser?.is_active ? '禁用用户' : '启用用户'}
        message={confirmUser?.is_active
          ? `确定要禁用用户「${confirmUser?.username}」吗？`
          : `确定要启用用户「${confirmUser?.username}」吗？`}
        confirmText={confirmUser?.is_active ? '禁用' : '启用'}
        danger={confirmUser?.is_active}
        onConfirm={() => { if (confirmUser) { handleToggleStatus(confirmUser); setConfirmUser(null); } }}
        onCancel={() => setConfirmUser(null)}
      />

      {/* Quota Edit Modal */}
      {editUser && (
        <div className={styles.modalOverlay} onMouseDown={(e) => { if (e.target === e.currentTarget) setEditUser(null); }}>
          <div className={styles.modal}>
            <h3 className={styles.modalTitle}>编辑配额 — {editUser.username}</h3>
            <div className={styles.formGroup}>
              <label>每日生成次数上限（-1 为不限）</label>
              <input type="number" value={editDaily} onChange={(e) => setEditDaily(e.target.value)} />
            </div>
            <div className={styles.formGroup}>
              <label>每月生成次数上限（-1 为不限）</label>
              <input type="number" value={editMonthly} onChange={(e) => setEditMonthly(e.target.value)} />
            </div>
            <div className={styles.formGroup}>
              <label>总消费额度（-1 为不限）</label>
              <input type="number" value={editSpendingLimit} onChange={(e) => setEditSpendingLimit(e.target.value)} />
            </div>
            <div className={styles.modalActions}>
              <button className={styles.cancelBtn} onClick={() => setEditUser(null)}>取消</button>
              <button className={styles.saveBtn} onClick={handleSaveQuota}>保存</button>
            </div>
          </div>
        </div>
      )}

      {/* Create User Modal */}
      {createOpen && (
        <div className={styles.modalOverlay} onMouseDown={(e) => { if (e.target === e.currentTarget) setCreateOpen(false); }}>
          <div className={styles.modal}>
            <h3 className={styles.modalTitle}>新增用户</h3>
            <div className={styles.formGroup}>
              <label>用户名</label>
              <input type="text" value={newUsername} onChange={(e) => setNewUsername(e.target.value)} placeholder="请输入用户名" />
            </div>
            <div className={styles.formGroup}>
              <label>邮箱</label>
              <input type="email" value={newEmail} onChange={(e) => setNewEmail(e.target.value)} placeholder="请输入邮箱" />
            </div>
            <div className={styles.formGroup}>
              <label>密码</label>
              <input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} placeholder="至少6位" />
            </div>
            <div className={styles.formRow}>
              <div className={styles.formGroup}>
                <label>每日生成次数上限</label>
                <input type="number" value={newDaily} onChange={(e) => setNewDaily(e.target.value)} />
              </div>
              <div className={styles.formGroup}>
                <label>每月生成次数上限</label>
                <input type="number" value={newMonthly} onChange={(e) => setNewMonthly(e.target.value)} />
              </div>
            </div>
            <div className={styles.formGroup}>
              <label className={styles.checkboxLabel}>
                <input type="checkbox" checked={newIsStaff} onChange={(e) => setNewIsStaff(e.target.checked)} />
                设为管理员
              </label>
            </div>
            {createError && <div className={styles.formError}>{createError}</div>}
            <div className={styles.modalActions}>
              <button className={styles.cancelBtn} onClick={() => setCreateOpen(false)}>取消</button>
              <button className={styles.saveBtn} onClick={handleCreateUser}>创建</button>
            </div>
          </div>
        </div>
      )}

      {/* Reset Password Modal */}
      {resetPwUser && (
        <div className={styles.modalOverlay} onMouseDown={(e) => { if (e.target === e.currentTarget) setResetPwUser(null); }}>
          <div className={styles.modal}>
            <h3 className={styles.modalTitle}>重置密码 — {resetPwUser.username}</h3>
            <div className={styles.formGroup}>
              <label>新密码</label>
              <input type="password" value={resetPwValue} onChange={(e) => setResetPwValue(e.target.value)}
                placeholder="至少8位" onKeyDown={(e) => e.key === 'Enter' && handleResetPassword()} />
            </div>
            {resetPwError && <div className={styles.formError}>{resetPwError}</div>}
            <div className={styles.modalActions}>
              <button className={styles.cancelBtn} onClick={() => setResetPwUser(null)}>取消</button>
              <button className={styles.saveBtn} onClick={handleResetPassword}>确认重置</button>
            </div>
          </div>
        </div>
      )}

      {/* User Detail Drawer */}
      {drawerOpen && detailUser && (
        <div className={styles.drawerOverlay} onClick={() => setDrawerOpen(false)}>
          <div className={styles.drawer} onClick={(e) => e.stopPropagation()}>
            <div className={styles.drawerHeader}>
              <h3>用户详情</h3>
              <button className={styles.drawerClose} onClick={() => setDrawerOpen(false)}>×</button>
            </div>
            <div className={styles.drawerBody}>
              <div className={styles.detailGrid}>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>用户名</span>
                  <span className={styles.detailValue}>{detailUser.username}</span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>邮箱</span>
                  <span className={styles.detailValue}>{detailUser.email}</span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>状态</span>
                  <span className={`${styles.statusBadge} ${detailUser.is_active ? styles.active : styles.disabled}`}>
                    {detailUser.is_active ? '启用' : '禁用'}
                  </span>
                  {!detailUser.is_active && detailUser.disabled_by && (
                    <span style={{ fontSize: 12, color: 'var(--color-text-secondary)', marginLeft: 6 }}>
                      {detailUser.disabled_by === 'system' ? '系统自动禁用' : '管理员手动禁用'}
                    </span>
                  )}
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>注册时间</span>
                  <span className={styles.detailValue}>{new Date(detailUser.date_joined).toLocaleString('zh-CN')}</span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>今日生成/上限</span>
                  <span className={styles.detailValue}>{(detailUser.generations_today || 0)}次 / {(detailUser.daily_generation_limit ?? -1) === -1 ? '不限' : detailUser.daily_generation_limit + '次'}</span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>本月生成/上限</span>
                  <span className={styles.detailValue}>{(detailUser.generations_this_month || 0)}次 / {(detailUser.monthly_generation_limit ?? -1) === -1 ? '不限' : detailUser.monthly_generation_limit + '次'}</span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>今日消费</span>
                  <span className={styles.detailValue}>¥{(detailUser.spent_today || 0).toFixed(2)}</span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>本月消费</span>
                  <span className={styles.detailValue}>¥{(detailUser.spent_this_month || 0).toFixed(2)}</span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>累计消费</span>
                  <span className={styles.detailValue}>¥{(detailUser.total_spent || 0).toFixed(2)}</span>
                </div>
              </div>

              <h4 className={styles.recordsTitle}>近期消费记录</h4>
              <div className={styles.recordsList}>
                {detailUser.recent_records.length === 0 ? (
                  <div className={styles.empty}>暂无记录</div>
                ) : (
                  detailUser.recent_records.map((r) => (
                    <div key={r.id} className={styles.recordItem}>
                      <div className={styles.recordTime}>{new Date(r.created_at).toLocaleString('zh-CN')}</div>
                      <div className={styles.recordMeta}>
                        <span className={styles.recordSeconds}>¥{(r.cost_amount || 0).toFixed(2)}</span>
                        <span className={styles.recordMode}>{r.mode === 'universal' ? '全能参考' : '首尾帧'}</span>
                        <span className={`${styles.recordStatus} ${styles[r.status]}`}>{
                          { queued: '排队中', processing: '生成中', completed: '已完成', failed: '失败' }[r.status]
                        }</span>
                      </div>
                      {r.prompt && <div className={styles.recordPrompt}>{r.prompt.slice(0, 60)}{r.prompt.length > 60 ? '...' : ''}</div>}
                    </div>
                  ))
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
