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

function fmtMoney(val: number): string {
  if (val === -1) return '不限';
  return '¥' + (val || 0).toFixed(2);
}

function fmtSec(s: number): string {
  return Math.round(s).toLocaleString() + 's';
}

export function TeamsPage() {
  const [teams, setTeams] = useState<Team[]>([]);
  const [loading, setLoading] = useState(true);

  // Create team modal
  const [createOpen, setCreateOpen] = useState(false);
  const [newName, setNewName] = useState('');
  const [newMonthlyLimit, setNewMonthlyLimit] = useState('10000');
  const [newDailyMemberLimit, setNewDailyMemberLimit] = useState('50');
  const [newExpectedRegions, setNewExpectedRegions] = useState('');
  const [newMarkup, setNewMarkup] = useState('30');
  const [createError, setCreateError] = useState('');

  // Top-up modal
  const [topupTeam, setTopupTeam] = useState<Team | null>(null);
  const [topupAmount, setTopupAmount] = useState('1000');

  // Create admin modal
  const [adminTeam, setAdminTeam] = useState<Team | null>(null);
  const [adminUsername, setAdminUsername] = useState('');
  const [adminEmail, setAdminEmail] = useState('');
  const [adminPassword, setAdminPassword] = useState('');
  const [adminError, setAdminError] = useState('');

  // Team detail drawer
  const [detailTeam, setDetailTeam] = useState<TeamDetail | null>(null);
  const [drawerOpen, setDrawerOpen] = useState(false);

  // Edit pool modal
  const [editPoolOpen, setEditPoolOpen] = useState(false);
  const [editPoolValue, setEditPoolValue] = useState('');
  const [editPoolError, setEditPoolError] = useState('');

  // Confirm toggle
  const [confirmTeam, setConfirmTeam] = useState<Team | null>(null);

  const fetchTeams = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await adminApi.getTeams();
      setTeams(data.results);
    } catch {
      showToast('加载团队列表失败');
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleToggleStatus = async (team: Team) => {
    try {
      await adminApi.updateTeam(team.id, { is_active: !team.is_active });
      showToast(team.is_active ? '已禁用团队' : '已启用团队');
      fetchTeams();
    } catch {
      showToast('操作失败');
    }
  };

  // Auto-learn state
  const [learnLoading, setLearnLoading] = useState(false);
  const [learnedCities, setLearnedCities] = useState<string[]>([]);
  const [learnOpen, setLearnOpen] = useState(false);
  const [editingRegions, setEditingRegions] = useState(false);
  const [editRegionsValue, setEditRegionsValue] = useState('');
  const [editingMonthlyLimit, setEditingMonthlyLimit] = useState(false);
  const [editMonthlyLimitValue, setEditMonthlyLimitValue] = useState('');
  const [editingMarkup, setEditingMarkup] = useState(false);
  const [editMarkupValue, setEditMarkupValue] = useState('');
  const [editingAnomalyConfig, setEditingAnomalyConfig] = useState(false);
  const [anomalyConfigDraft, setAnomalyConfigDraft] = useState<Record<string, any>>({});
  const [editingMaxConcurrent, setEditingMaxConcurrent] = useState(false);
  const [editMaxConcurrentValue, setEditMaxConcurrentValue] = useState('');

  const resetCreateForm = () => {
    setNewName(''); setNewMonthlyLimit('10000'); setNewDailyMemberLimit('50');
    setNewExpectedRegions(''); setNewMarkup('30'); setCreateError('');
  };

  const handleCreateTeam = async () => {
    setCreateError('');
    if (!newName.trim()) { setCreateError('请输入团队名称'); return; }
    if (!newExpectedRegions.trim()) { setCreateError('请输入预期登录城市'); return; }
    try {
      await adminApi.createTeam({
        name: newName.trim(),
        monthly_spending_limit: Number(newMonthlyLimit),
        daily_member_limit_default: Number(newDailyMemberLimit),
        expected_regions: newExpectedRegions.trim(),
        markup_percentage: Number(newMarkup),
      });
      showToast('团队创建成功');
      setCreateOpen(false);
      resetCreateForm();
      fetchTeams();
    } catch (err: any) {
      const msg = err.response?.data?.error || err.response?.data?.name?.[0] || '创建失败';
      setCreateError(msg);
    }
  };

  const handleTopUp = async () => {
    if (!topupTeam) return;
    const amount = Number(topupAmount);
    if (!amount || amount <= 0) { showToast('请输入有效的金额'); return; }
    try {
      await adminApi.topUpTeam(topupTeam.id, amount);
      showToast(`已为 ${topupTeam.name} 充值 ${fmtMoney(amount)}`);
      setTopupTeam(null);
      fetchTeams();
    } catch {
      showToast('充值失败');
    }
  };

  const handleSetPool = async () => {
    if (!detailTeam) return;
    const newBalance = Number(editPoolValue);
    if (isNaN(newBalance) || newBalance < 0) { setEditPoolError('请输入有效的非负数'); return; }
    try {
      await adminApi.setTeamPool(detailTeam.id, newBalance);
      showToast(`已将 ${detailTeam.name} 余额修改为 ${fmtMoney(newBalance)}`);
      setEditPoolOpen(false);
      // Refresh detail
      const { data } = await adminApi.getTeamDetail(detailTeam.id);
      setDetailTeam(data);
      fetchTeams();
    } catch (err: any) {
      const msg = err.response?.data?.error || '修改失败';
      setEditPoolError(msg);
    }
  };

  const resetAdminForm = () => {
    setAdminUsername(''); setAdminEmail(''); setAdminPassword('');
    setAdminError('');
  };

  const handleCreateAdmin = async () => {
    if (!adminTeam) return;
    setAdminError('');
    if (!adminUsername.trim()) { setAdminError('请输入用户名'); return; }
    if (!adminEmail.trim()) { setAdminError('请输入邮箱'); return; }
    if (adminPassword.length < 6) { setAdminError('密码至少6位'); return; }
    try {
      await adminApi.createTeamAdmin(adminTeam.id, {
        username: adminUsername.trim(),
        email: adminEmail.trim(),
        password: adminPassword,
      });
      showToast('团队管理员创建成功');
      setAdminTeam(null);
      resetAdminForm();
      fetchTeams();
    } catch (err: any) {
      const msg = err.response?.data?.error || err.response?.data?.username?.[0] || '创建失败';
      setAdminError(msg);
    }
  };

  const handleAutoLearn = async () => {
    if (!detailTeam) return;
    setLearnLoading(true);
    try {
      const { data } = await adminApi.teamAutoLearn(detailTeam.id);
      setLearnedCities(data.learned_cities);
      setLearnOpen(true);
    } catch {
      showToast('自动学习失败');
    } finally {
      setLearnLoading(false);
    }
  };

  const handleApplyLearnedRegions = async () => {
    if (!detailTeam) return;
    try {
      await adminApi.teamApplyLearnedRegions(detailTeam.id, learnedCities);
      showToast('预期地区已更新');
      setLearnOpen(false);
      const { data } = await adminApi.getTeamDetail(detailTeam.id);
      setDetailTeam(data);
      fetchTeams();
    } catch {
      showToast('应用失败');
    }
  };

  const openDrawer = async (teamId: number) => {
    try {
      const { data } = await adminApi.getTeamDetail(teamId);
      setDetailTeam(data);
      setDrawerOpen(true);
    } catch {
      showToast('加载团队详情失败');
    }
  };

  const colCount = 10;

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

      <div className={styles.filters}>
        <div className={styles.searchGroup}>
          <span style={{ color: 'var(--color-text-secondary)', fontSize: 13 }}>共 {teams.length} 个团队</span>
        </div>
        <div className={styles.searchGroup}>
          <button className={styles.refreshBtn} onClick={fetchTeams}>刷新</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>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              Array.from({ length: 5 }).map((_, i) => (
                <tr key={i}>
                  {Array.from({ length: colCount }).map((_, j) => (
                    <td key={j}><div className={styles.skeletonCell} /></td>
                  ))}
                </tr>
              ))
            ) : teams.length === 0 ? (
              <tr><td colSpan={colCount} className={styles.empty}>暂无数据</td></tr>
            ) : (
              teams.map((t) => (
                <tr key={t.id}>
                  <td>
                    <button className={styles.teamNameLink} onClick={() => openDrawer(t.id)}>
                      {t.name}
                    </button>
                  </td>
                  <td>{fmtMoney(t.balance)}</td>
                  <td>{fmtMoney(t.total_spent)}</td>
                  <td>{fmtMoney(t.available_balance)}</td>
                  <td>{fmtMoney(t.monthly_spending_limit)}</td>
                  <td>{fmtMoney(t.monthly_spent)}</td>
                  <td>{t.member_count}</td>
                  <td>{t.current_processing ?? 0}/{t.max_concurrent_tasks}</td>
                  <td>
                    <span className={`${styles.statusBadge} ${t.is_active ? styles.active : styles.disabled}`}>
                      {t.is_active ? '启用' : '禁用'}
                    </span>
                    {!t.is_active && t.disabled_by && (
                      <span style={{ fontSize: 11, color: 'var(--color-text-secondary)', marginLeft: 4 }}>
                        ({t.disabled_by === 'system' ? '系统' : '管理员'})
                      </span>
                    )}
                  </td>
                  <td>
                    <div className={styles.actions}>
                      <button className={styles.topupBtn} onClick={() => { setTopupTeam(t); setTopupAmount('1000'); }}>充值</button>
                      <button className={styles.adminBtn} onClick={() => { setAdminTeam(t); resetAdminForm(); }}>添加管理员</button>
                      <button
                        className={`${styles.toggleBtn} ${t.is_active ? styles.disableBtn : styles.enableBtn}`}
                        onClick={() => setConfirmTeam(t)}
                      >
                        {t.is_active ? '禁用' : '启用'}
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Create Team 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={newName} onChange={(e) => setNewName(e.target.value)} placeholder="请输入团队名称" />
            </div>
            <div className={styles.formRow}>
              <div className={styles.formGroup}>
                <label>每月消费限额(元)</label>
                <input type="number" value={newMonthlyLimit} onChange={(e) => setNewMonthlyLimit(e.target.value)} />
              </div>
              <div className={styles.formGroup}>
                <label>成员日生成次数(默认)</label>
                <input type="number" value={newDailyMemberLimit} onChange={(e) => setNewDailyMemberLimit(e.target.value)} />
              </div>
            </div>
            <div className={styles.formGroup}>
              <label>加价率(%)</label>
              <input type="number" value={newMarkup} onChange={(e) => setNewMarkup(e.target.value)} placeholder="如 30 表示加价 30%" />
            </div>
            <div className={styles.formGroup}>
              <label>预期登录城市（必填，逗号分隔）</label>
              <input type="text" value={newExpectedRegions} onChange={(e) => setNewExpectedRegions(e.target.value)} placeholder="广州,深圳,北京" />
            </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={handleCreateTeam}>创建</button>
            </div>
          </div>
        </div>
      )}

      {/* Top-up Modal */}
      {topupTeam && (
        <div className={styles.modalOverlay} onMouseDown={(e) => { if (e.target === e.currentTarget) setTopupTeam(null); }}>
          <div className={styles.modal}>
            <h3 className={styles.modalTitle}>充值金额 — {topupTeam.name}</h3>
            <div className={styles.formGroup}>
              <label>充值金额(元)</label>
              <input type="number" value={topupAmount} onChange={(e) => setTopupAmount(e.target.value)} placeholder="输入金额" />
              <div className={styles.formHint}>
                当前余额: {fmtMoney(topupTeam.balance)} | 充值后: {fmtMoney((topupTeam.balance || 0) + (Number(topupAmount) || 0))}
              </div>
            </div>
            <div className={styles.modalActions}>
              <button className={styles.cancelBtn} onClick={() => setTopupTeam(null)}>取消</button>
              <button className={styles.saveBtn} onClick={handleTopUp}>确认充值</button>
            </div>
          </div>
        </div>
      )}

      {/* Create Team Admin Modal */}
      {adminTeam && (
        <div className={styles.modalOverlay} onMouseDown={(e) => { if (e.target === e.currentTarget) setAdminTeam(null); }}>
          <div className={styles.modal}>
            <h3 className={styles.modalTitle}>添加管理员 — {adminTeam.name}</h3>
            <div className={styles.formGroup}>
              <label>用户名</label>
              <input type="text" value={adminUsername} onChange={(e) => setAdminUsername(e.target.value)} placeholder="请输入用户名" />
            </div>
            <div className={styles.formGroup}>
              <label>邮箱</label>
              <input type="email" value={adminEmail} onChange={(e) => setAdminEmail(e.target.value)} placeholder="请输入邮箱" />
            </div>
            <div className={styles.formGroup}>
              <label>密码</label>
              <input type="password" value={adminPassword} onChange={(e) => setAdminPassword(e.target.value)} placeholder="至少6位" />
            </div>
            {adminError && <div className={styles.formError}>{adminError}</div>}
            <div className={styles.modalActions}>
              <button className={styles.cancelBtn} onClick={() => setAdminTeam(null)}>取消</button>
              <button className={styles.saveBtn} onClick={handleCreateAdmin}>创建</button>
            </div>
          </div>
        </div>
      )}

      <ConfirmModal
        open={!!confirmTeam}
        title={confirmTeam?.is_active ? '禁用团队' : '启用团队'}
        message={confirmTeam?.is_active
          ? `确定要禁用团队「${confirmTeam?.name}」吗？禁用后该团队所有成员将无法生成视频。`
          : `确定要启用团队「${confirmTeam?.name}」吗？`}
        confirmText={confirmTeam?.is_active ? '禁用' : '启用'}
        danger={confirmTeam?.is_active}
        onConfirm={() => { if (confirmTeam) { handleToggleStatus(confirmTeam); setConfirmTeam(null); } }}
        onCancel={() => setConfirmTeam(null)}
      />

      {/* Team Detail Modal */}
      {drawerOpen && detailTeam && (
        <div className={styles.detailOverlay} onMouseDown={(e) => { if (e.target === e.currentTarget) setDrawerOpen(false); }}>
          <div className={styles.detailModal}>
            <div className={styles.detailHeader}>
              <h3>
                团队详情 — {detailTeam.name}
                <span className={`${styles.statusBadge} ${detailTeam.is_active ? styles.active : styles.disabled}`}>
                  {detailTeam.is_active ? '启用' : '禁用'}
                </span>
                {!detailTeam.is_active && detailTeam.disabled_by && (
                  <span style={{ fontSize: 12, color: 'var(--color-text-secondary)', fontWeight: 400, marginLeft: 8 }}>
                    ({detailTeam.disabled_by === 'system' ? '系统自动禁用' : '管理员手动禁用'})
                  </span>
                )}
              </h3>
              <button className={styles.detailClose} onClick={() => setDrawerOpen(false)}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M18 6L6 18M6 6l12 12" />
                </svg>
              </button>
            </div>
            <div className={styles.detailBody}>
              <div className={styles.detailGrid}>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>余额</span>
                  <span className={styles.detailValue}>
                    {fmtMoney(detailTeam.balance)}
                    <button
                      className={styles.editPoolBtn}
                      onClick={() => { setEditPoolValue(String(detailTeam.balance || 0)); setEditPoolError(''); setEditPoolOpen(true); }}
                      title="修改余额"
                    >
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                        <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
                        <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
                      </svg>
                    </button>
                  </span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>累计消费</span>
                  <span className={styles.detailValue}>{fmtMoney(detailTeam.total_spent)}</span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>月消费限额</span>
                  <span className={styles.detailValue}>
                    {editingMonthlyLimit ? (
                      <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center', flexWrap: 'nowrap' }}>
                        <input
                          type="number"
                          value={editMonthlyLimitValue}
                          onChange={(e) => setEditMonthlyLimitValue(e.target.value)}
                          style={{ width: 80, 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.topupBtn}
                          onClick={async () => {
                            const val = Number(editMonthlyLimitValue);
                            if (isNaN(val) || (val < 0 && val !== -1)) { showToast('请输入有效金额，-1为不限制'); return; }
                            try {
                              await adminApi.updateTeam(detailTeam.id, { monthly_spending_limit: val });
                              setDetailTeam({ ...detailTeam, monthly_spending_limit: val });
                              setTeams(teams.map(t => t.id === detailTeam.id ? { ...t, monthly_spending_limit: val } : t));
                              setEditingMonthlyLimit(false);
                              showToast('月消费限额已更新');
                            } catch (e: any) {
                              showToast(e.response?.data?.error || '保存失败');
                            }
                          }}
                          style={{ fontSize: 12, padding: '4px 10px', whiteSpace: 'nowrap' }}
                        >
                          保存
                        </button>
                        <button
                          className={styles.topupBtn}
                          onClick={() => setEditingMonthlyLimit(false)}
                          style={{ fontSize: 12, padding: '4px 10px', whiteSpace: 'nowrap' }}
                        >
                          取消
                        </button>
                      </span>
                    ) : (
                      <>
                        {fmtMoney(detailTeam.monthly_spending_limit)}
                        <button
                          className={styles.topupBtn}
                          onClick={() => { setEditingMonthlyLimit(true); setEditMonthlyLimitValue(String(detailTeam.monthly_spending_limit || 0)); }}
                          style={{ fontSize: 12, padding: '4px 10px', marginLeft: 8 }}
                        >
                          编辑
                        </button>
                      </>
                    )}
                  </span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>可用余额</span>
                  <span className={styles.detailValue}>{fmtMoney(detailTeam.available_balance)}</span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>冻结金额</span>
                  <span className={styles.detailValue}>{fmtMoney(detailTeam.frozen_amount)}</span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>本月消费</span>
                  <span className={styles.detailValue}>{fmtMoney(detailTeam.monthly_spent)}</span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>加价率</span>
                  <span className={styles.detailValue}>
                    {editingMarkup ? (
                      <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center', flexWrap: 'nowrap' }}>
                        <input
                          type="number"
                          value={editMarkupValue}
                          onChange={(e) => setEditMarkupValue(e.target.value)}
                          style={{ width: 80, padding: '3px 6px', borderRadius: 4, border: '1px solid var(--color-border-card)', background: 'var(--color-bg-page)', color: 'var(--color-text-primary)', fontSize: 13 }}
                        />
                        <span style={{ fontSize: 13, color: 'var(--color-text-secondary)' }}>%</span>
                        <button
                          className={styles.topupBtn}
                          onClick={async () => {
                            const val = Number(editMarkupValue);
                            if (isNaN(val) || val < 0) { showToast('请输入有效的加价百分比'); return; }
                            try {
                              await adminApi.updateTeam(detailTeam.id, { markup_percentage: val });
                              setDetailTeam({ ...detailTeam, markup_percentage: val });
                              setTeams(teams.map(t => t.id === detailTeam.id ? { ...t, markup_percentage: val } : t));
                              setEditingMarkup(false);
                              showToast('加价率已更新');
                            } catch (e: any) {
                              showToast(e.response?.data?.error || '保存失败');
                            }
                          }}
                          style={{ fontSize: 12, padding: '4px 10px', whiteSpace: 'nowrap' }}
                        >
                          保存
                        </button>
                        <button
                          className={styles.topupBtn}
                          onClick={() => setEditingMarkup(false)}
                          style={{ fontSize: 12, padding: '4px 10px', whiteSpace: 'nowrap' }}
                        >
                          取消
                        </button>
                      </span>
                    ) : (
                      <>
                        {(detailTeam.markup_percentage || 0)}%
                        <button
                          className={styles.topupBtn}
                          onClick={() => { setEditingMarkup(true); setEditMarkupValue(String(detailTeam.markup_percentage || 0)); }}
                          style={{ fontSize: 12, padding: '4px 10px', marginLeft: 8 }}
                        >
                          编辑
                        </button>
                      </>
                    )}
                  </span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>成员数</span>
                  <span className={styles.detailValue}>{detailTeam.member_count}</span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>并发上限</span>
                  <span className={styles.detailValue}>
                    {editingMaxConcurrent ? (
                      <span style={{ display: 'inline-flex', gap: 6, alignItems: 'center', flexWrap: 'nowrap' }}>
                        <input
                          type="number"
                          value={editMaxConcurrentValue}
                          onChange={(e) => setEditMaxConcurrentValue(e.target.value)}
                          style={{ width: 80, 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.topupBtn}
                          onClick={async () => {
                            const val = Number(editMaxConcurrentValue);
                            if (isNaN(val) || val < 1) { showToast('请输入大于0的整数'); return; }
                            try {
                              await adminApi.updateTeam(detailTeam.id, { max_concurrent_tasks: val });
                              setDetailTeam({ ...detailTeam, max_concurrent_tasks: val });
                              setTeams(teams.map(t => t.id === detailTeam.id ? { ...t, max_concurrent_tasks: val } : t));
                              setEditingMaxConcurrent(false);
                              showToast('并发上限已更新');
                            } catch (e: any) {
                              showToast(e.response?.data?.error || '保存失败');
                            }
                          }}
                          style={{ fontSize: 12, padding: '4px 10px', whiteSpace: 'nowrap' }}
                        >
                          保存
                        </button>
                        <button
                          className={styles.topupBtn}
                          onClick={() => setEditingMaxConcurrent(false)}
                          style={{ fontSize: 12, padding: '4px 10px', whiteSpace: 'nowrap' }}
                        >
                          取消
                        </button>
                      </span>
                    ) : (
                      <>
                        {detailTeam.max_concurrent_tasks}
                        <button
                          className={styles.topupBtn}
                          onClick={() => { setEditingMaxConcurrent(true); setEditMaxConcurrentValue(String(detailTeam.max_concurrent_tasks || 1)); }}
                          style={{ fontSize: 12, padding: '4px 10px', marginLeft: 8 }}
                        >
                          编辑
                        </button>
                      </>
                    )}
                  </span>
                </div>
                <div className={styles.detailItem}>
                  <span className={styles.detailLabel}>创建时间</span>
                  <span className={styles.detailValue}>{new Date(detailTeam.created_at).toLocaleDateString('zh-CN')}</span>
                </div>
              </div>

              <div style={{ marginTop: 16, marginBottom: 16 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
                  <span className={styles.detailLabel} style={{ marginBottom: 0 }}>预期登录城市</span>
                  {!editingRegions && (
                    <button
                      className={styles.topupBtn}
                      onClick={() => { setEditingRegions(true); setEditRegionsValue(detailTeam.expected_regions || ''); }}
                      style={{ fontSize: 12, padding: '4px 10px' }}
                    >
                      编辑
                    </button>
                  )}
                  <button
                    className={styles.topupBtn}
                    onClick={handleAutoLearn}
                    disabled={learnLoading}
                    style={{ fontSize: 12, padding: '4px 10px' }}
                  >
                    {learnLoading ? '学习中...' : '自动学习'}
                  </button>
                </div>
                {editingRegions ? (
                  <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                    <input
                      type="text"
                      value={editRegionsValue}
                      onChange={(e) => setEditRegionsValue(e.target.value)}
                      placeholder="多个城市用逗号分隔，如：广州,深圳,北京"
                      style={{ flex: 1, padding: '6px 10px', borderRadius: 6, border: '1px solid var(--color-border-card)', background: 'var(--color-bg-page)', color: 'var(--color-text-primary)', fontSize: 13 }}
                    />
                    <button
                      className={styles.topupBtn}
                      onClick={async () => {
                        try {
                          await adminApi.updateTeam(detailTeam.id, { expected_regions: editRegionsValue.trim() });
                          setDetailTeam({ ...detailTeam, expected_regions: editRegionsValue.trim() });
                          setEditingRegions(false);
                        } catch (e: any) {
                          alert(e.response?.data?.error || '保存失败');
                        }
                      }}
                      style={{ fontSize: 12, padding: '4px 10px', whiteSpace: 'nowrap' }}
                    >
                      保存
                    </button>
                    <button
                      className={styles.topupBtn}
                      onClick={() => setEditingRegions(false)}
                      style={{ fontSize: 12, padding: '4px 10px', whiteSpace: 'nowrap' }}
                    >
                      取消
                    </button>
                  </div>
                ) : (
                  <span style={{ color: 'var(--color-text-primary)', fontSize: 13 }}>
                    {detailTeam.expected_regions || '（未设置）'}
                  </span>
                )}
              </div>

              {/* 团队级异常检测阈值 */}
              <div style={{ marginTop: 16, padding: '12px 16px', background: 'var(--color-bg-page)', borderRadius: 8, border: '1px solid var(--color-border-card)' }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                  <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--color-text-primary)' }}>异常检测阈值（留空 = 用全局默认）</span>
                  {!editingAnomalyConfig ? (
                    <button className={styles.topupBtn} onClick={() => { setEditingAnomalyConfig(true); setAnomalyConfigDraft(detailTeam.anomaly_config || {}); }} style={{ fontSize: 12, padding: '4px 10px' }}>编辑</button>
                  ) : (
                    <div style={{ display: 'flex', gap: 6 }}>
                      <button className={styles.topupBtn} onClick={async () => {
                        try {
                          await adminApi.updateTeam(detailTeam.id, { anomaly_config: anomalyConfigDraft });
                          setDetailTeam({ ...detailTeam, anomaly_config: anomalyConfigDraft as any });
                          setEditingAnomalyConfig(false);
                          showToast('已保存');
                        } catch { showToast('保存失败'); }
                      }} style={{ fontSize: 12, padding: '4px 10px' }}>保存</button>
                      <button className={styles.topupBtn} onClick={() => setEditingAnomalyConfig(false)} style={{ fontSize: 12, padding: '4px 10px' }}>取消</button>
                    </div>
                  )}
                </div>
                {editingAnomalyConfig ? (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 0, fontSize: 12 }}>
                    {[
                      { title: 'R1 登录地区异常', desc: '单账号从非预期城市登录时告警', items: [
                        { key: 'r1_enabled', label: '启用', type: 'bool' },
                      ]},
                      { title: 'R2 不可能的旅行', desc: '单账号短时间内从两个不同城市登录，自动封禁该用户', items: [
                        { key: 'r2_enabled', label: '启用', type: 'bool' },
                        { key: 'r2_window_seconds', label: '时间窗口(秒)', type: 'num' },
                      ]},
                      { title: 'R3 登录太频繁', desc: '单账号短时间内登录次数过多时告警', items: [
                        { key: 'r3_enabled', label: '启用', type: 'bool' },
                        { key: 'r3_window_seconds', label: '时间窗口(秒)', type: 'num' },
                        { key: 'r3_max_count', label: '最大次数', type: 'num' },
                      ]},
                      { title: 'R4 团队遍地开花', desc: '整个团队短时间内出现大量异地登录，自动封禁整个团队', items: [
                        { key: 'r4_enabled', label: '启用', type: 'bool' },
                        { key: 'r4_window_seconds', label: '时间窗口(秒)', type: 'num' },
                        { key: 'r4_city_count', label: '城市数阈值', type: 'num' },
                      ]},
                      { title: 'R5 海外IP太杂', desc: '整个团队短期内出现大量不同国家的登录时告警', items: [
                        { key: 'r5_enabled', label: '启用', type: 'bool' },
                        { key: 'r5_days', label: '统计天数', type: 'num' },
                        { key: 'r5_country_count', label: '国家数阈值', type: 'num' },
                      ]},
                    ].map((group, gi) => (
                      <div key={group.title}>
                        {gi > 0 && <div style={{ height: 1, background: 'var(--color-border-card)', margin: '8px 0' }} />}
                        <div style={{ marginBottom: 6 }}>
                          <span style={{ color: 'var(--color-text-primary)', fontWeight: 500, fontSize: 12 }}>{group.title}</span>
                          <span style={{ color: 'var(--color-text-secondary)', fontSize: 11, marginLeft: 8 }}>{group.desc}</span>
                        </div>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px 16px', paddingLeft: 8 }}>
                          {group.items.map((item) => (
                            <div key={item.key} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                              <span style={{ color: 'var(--color-text-secondary)', minWidth: 80 }}>{item.label}</span>
                              <div style={{ width: 90 }}>
                                {item.type === 'bool' ? (
                                  <div style={{ display: 'flex', borderRadius: 4, overflow: 'hidden', border: '1px solid var(--color-border-card)', width: '100%' }}>
                                    {([['', '默认'], ['true', '开'], ['false', '关']] as const).map(([val, label]) => {
                                      const cur = anomalyConfigDraft[item.key];
                                      const selected = val === '' ? (cur === null || cur === undefined) : String(cur) === val;
                                      return (
                                        <button
                                          key={val}
                                          onClick={() => setAnomalyConfigDraft({ ...anomalyConfigDraft, [item.key]: val === '' ? null : val === 'true' })}
                                          style={{ flex: 1, padding: '3px 0', fontSize: 11, border: 'none', cursor: 'pointer', background: selected ? 'var(--color-primary)' : 'var(--color-bg-card)', color: selected ? 'var(--color-on-primary)' : 'var(--color-text-secondary)', transition: 'all 0.15s' }}
                                        >
                                          {label}
                                        </button>
                                      );
                                    })}
                                  </div>
                                ) : (
                                  <input
                                    type="number"
                                    value={anomalyConfigDraft[item.key] ?? ''}
                                    onChange={(e) => setAnomalyConfigDraft({ ...anomalyConfigDraft, [item.key]: e.target.value === '' ? null : Number(e.target.value) })}
                                    placeholder="默认"
                                    style={{ width: '100%', padding: '3px 6px', borderRadius: 4, border: '1px solid var(--color-border-card)', background: 'var(--color-bg-card)', color: 'var(--color-text-primary)', fontSize: 12, boxSizing: 'border-box' }}
                                  />
                                )}
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div style={{ fontSize: 12, color: 'var(--color-text-secondary)', lineHeight: 1.8 }}>
                    {(() => {
                      const c = detailTeam.anomaly_config;
                      if (!c) return '全部使用全局默认值';
                      const items: string[] = [];
                      if (c.r1_enabled !== null) items.push(`R1: ${c.r1_enabled ? '开' : '关'}`);
                      if (c.r2_enabled !== null) items.push(`R2: ${c.r2_enabled ? '开' : '关'}`);
                      if (c.r2_window_seconds !== null) items.push(`R2窗口: ${c.r2_window_seconds}秒`);
                      if (c.r3_enabled !== null) items.push(`R3: ${c.r3_enabled ? '开' : '关'}`);
                      if (c.r3_window_seconds !== null) items.push(`R3窗口: ${c.r3_window_seconds}秒`);
                      if (c.r3_max_count !== null) items.push(`R3次数: ${c.r3_max_count}`);
                      if (c.r4_enabled !== null) items.push(`R4: ${c.r4_enabled ? '开' : '关'}`);
                      if (c.r4_window_seconds !== null) items.push(`R4窗口: ${c.r4_window_seconds}秒`);
                      if (c.r4_city_count !== null) items.push(`R4城市: ${c.r4_city_count}`);
                      if (c.r5_enabled !== null) items.push(`R5: ${c.r5_enabled ? '开' : '关'}`);
                      if (c.r5_days !== null) items.push(`R5天数: ${c.r5_days}`);
                      if (c.r5_country_count !== null) items.push(`R5国家: ${c.r5_country_count}`);
                      return items.length ? items.join(' / ') : '全部使用全局默认值';
                    })()}
                  </div>
                )}
              </div>

              <h4 className={styles.membersTitle}>成员列表 ({detailTeam.members.length})</h4>
              {detailTeam.members.length === 0 ? (
                <div className={styles.empty}>暂无成员</div>
              ) : (
                <div className={styles.memberTableWrapper}>
                  <table className={styles.memberTable}>
                    <thead>
                      <tr>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>角色</th>
                        <th>状态</th>
                        <th>日生成上限</th>
                        <th>月限额(次)</th>
                        <th>今日生成/消费</th>
                        <th>本月生成/消费</th>
                      </tr>
                    </thead>
                    <tbody>
                      {detailTeam.members.map((m) => (
                        <tr key={m.id}>
                          <td>
                            <span style={{
                              display: 'inline-block', width: 8, height: 8, borderRadius: '50%',
                              background: m.is_online ? 'var(--color-success)' : 'var(--color-text-quaternary)', marginRight: 6,
                              verticalAlign: 'middle',
                            }} />
                            {m.username}
                          </td>
                          <td>{m.email}</td>
                          <td>
                            {m.is_team_owner ? (
                              <span className={styles.ownerBadge} style={{ cursor: 'pointer' }} title="点击撤销主管理员身份(变回普通成员)" onClick={async () => {
                                if (!window.confirm(`撤销 ${m.username} 的主管理员身份?\n确认后将变回普通成员。`)) return;
                                try {
                                  // 后端 admin_team_member_role_view 收到 is_team_admin=false 会同时清 is_team_owner
                                  await adminApi.setMemberRole(detailTeam!.id, m.id, false);
                                  showToast('已撤销主管理员');
                                  const { data: refreshed } = await adminApi.getTeamDetail(detailTeam!.id); setDetailTeam(refreshed);
                                } catch { showToast('操作失败'); }
                              }}>主管理员</span>
                            ) : m.is_team_admin ? (
                              <>
                                <span className={styles.adminBadge} style={{ cursor: 'pointer' }} title="点击取消副管理员(变回普通成员)" onClick={async () => {
                                  try {
                                    await adminApi.setMemberRole(detailTeam!.id, m.id, false);
                                    showToast('已取消副管理员');
                                    const { data: refreshed } = await adminApi.getTeamDetail(detailTeam!.id); setDetailTeam(refreshed);
                                  } catch { showToast('操作失败'); }
                                }}>副管理员</span>
                                <button
                                  type="button"
                                  style={{ marginLeft: 6, fontSize: 11, color: 'var(--color-text-tertiary)',
                                           background: 'none', border: 'none', cursor: 'pointer', padding: 0, textDecoration: 'underline' }}
                                  title="升为主管理员(原主管不会自动降级,如需保持唯一主管请先撤销原主管)"
                                  onClick={async () => {
                                    if (!window.confirm(`将 ${m.username} 设为主管理员?\n\n注意:不会自动降级现有主管。如果想换主管,请先撤销原主管再升新主管。`)) return;
                                    try {
                                      await adminApi.setMemberAsOwner(detailTeam!.id, m.id);
                                      showToast('已升为主管理员');
                                      const { data: refreshed } = await adminApi.getTeamDetail(detailTeam!.id); setDetailTeam(refreshed);
                                    } catch { showToast('操作失败'); }
                                  }}
                                >→主管</button>
                              </>
                            ) : (
                              <>
                                <span style={{ cursor: 'pointer', color: 'var(--color-text-secondary)' }} title="点击设为副管理员" onClick={async () => {
                                  try {
                                    await adminApi.setMemberRole(detailTeam!.id, m.id, true);
                                    showToast('已设为副管理员');
                                    const { data: refreshed } = await adminApi.getTeamDetail(detailTeam!.id); setDetailTeam(refreshed);
                                  } catch { showToast('操作失败'); }
                                }}>成员</span>
                                <button
                                  type="button"
                                  style={{ marginLeft: 6, fontSize: 11, color: 'var(--color-text-tertiary)',
                                           background: 'none', border: 'none', cursor: 'pointer', padding: 0, textDecoration: 'underline' }}
                                  title="直接升为主管理员(原主管不会自动降级)"
                                  onClick={async () => {
                                    if (!window.confirm(`将 ${m.username} 设为主管理员?\n\n注意:不会自动降级现有主管。如果想换主管,请先撤销原主管再升新主管。`)) return;
                                    try {
                                      await adminApi.setMemberAsOwner(detailTeam!.id, m.id);
                                      showToast('已升为主管理员');
                                      const { data: refreshed } = await adminApi.getTeamDetail(detailTeam!.id); setDetailTeam(refreshed);
                                    } catch { showToast('操作失败'); }
                                  }}
                                >→主管</button>
                              </>
                            )}
                          </td>
                          <td>
                            <span className={`${styles.statusBadge} ${m.is_active ? styles.active : styles.disabled}`}>
                              {m.is_active ? '启用' : '禁用'}
                            </span>
                            {!m.is_active && m.disabled_by && (
                              <span style={{ fontSize: 10, color: 'var(--color-text-secondary)', marginLeft: 2 }}>
                                ({m.disabled_by === 'system' ? '系统' : '管理员'})
                              </span>
                            )}
                          </td>
                          <td>{m.daily_generation_limit === -1 ? '不限' : (m.daily_generation_limit || 0) + '次'}</td>
                          <td>{m.monthly_generation_limit === -1 ? '不限' : (m.monthly_generation_limit || 0) + '次'}</td>
                          <td>{(m.generations_today || 0) + '次 / ' + fmtMoney(m.spent_today)}</td>
                          <td>{(m.generations_this_month || 0) + '次 / ' + fmtMoney(m.spent_this_month)}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Auto-Learn Result Modal */}
      {learnOpen && detailTeam && (
        <div className={styles.modalOverlay} onMouseDown={(e) => { if (e.target === e.currentTarget) setLearnOpen(false); }}>
          <div className={styles.modal}>
            <h3 className={styles.modalTitle}>自动学习结果 — {detailTeam.name}</h3>
            {learnedCities.length === 0 ? (
              <p style={{ color: 'var(--color-text-secondary)', fontSize: 13 }}>近 30 天无足够登录数据</p>
            ) : (
              <>
                <p style={{ color: 'var(--color-text-secondary)', fontSize: 13, marginBottom: 12 }}>
                  以下城市在近 30 天内登录 3 次以上，确认后将覆盖当前预期地区设置：
                </p>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 16 }}>
                  {learnedCities.map((city) => (
                    <span key={city} style={{
                      padding: '4px 10px', borderRadius: 12, fontSize: 12,
                      background: 'var(--color-bg-page)', border: '1px solid var(--color-border-card)',
                      color: 'var(--color-text-primary)',
                    }}>{city}</span>
                  ))}
                </div>
              </>
            )}
            <div className={styles.modalActions}>
              <button className={styles.cancelBtn} onClick={() => setLearnOpen(false)}>取消</button>
              {learnedCities.length > 0 && (
                <button className={styles.saveBtn} onClick={handleApplyLearnedRegions}>应用</button>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Edit Pool Modal */}
      {editPoolOpen && detailTeam && (
        <div className={styles.modalOverlay} onMouseDown={(e) => { if (e.target === e.currentTarget) setEditPoolOpen(false); }}>
          <div className={styles.modal}>
            <h3 className={styles.modalTitle}>修改余额 — {detailTeam.name}</h3>
            {editPoolError && <div className={styles.formError}>{editPoolError}</div>}
            <div className={styles.formGroup}>
              <label>余额（元）</label>
              <input type="number" value={editPoolValue} onChange={(e) => setEditPoolValue(e.target.value)} placeholder="输入余额" />
              <div className={styles.formHint}>
                当前余额: {fmtMoney(detailTeam.balance)} | 累计消费: {fmtMoney(detailTeam.total_spent)}
              </div>
            </div>
            <div className={styles.modalActions}>
              <button className={styles.cancelBtn} onClick={() => setEditPoolOpen(false)}>取消</button>
              <button className={styles.saveBtn} onClick={handleSetPool}>确认修改</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
