import { useEffect, useState, useCallback } from 'react';
import { teamApi } from '../lib/api';
import type { TeamMember } from '../types';
import { showToast } from '../components/Toast';
import { ConfirmModal } from '../components/ConfirmModal';
import { useAuthStore } from '../store/auth';
import styles from './UsersPage.module.css';

export function TeamMembersPage() {
  const currentUser = useAuthStore((s) => s.user);
  const [members, setMembers] = useState<TeamMember[]>([]);
  const [loading, setLoading] = useState(true);

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

  // Confirm toggle
  const [confirmMember, setConfirmMember] = useState<TeamMember | null>(null);

  // Edit quota modal
  const [editMember, setEditMember] = useState<TeamMember | null>(null);
  const [editDaily, setEditDaily] = useState('');
  const [editMonthly, setEditMonthly] = useState('');
  const [editSpendingLimit, setEditSpendingLimit] = useState('');

  // Reset password result modal — 显示新生成的随机密码 + 复制按钮
  const [resetResult, setResetResult] = useState<{ username: string; newPassword: string } | null>(null);

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

  // 权限矩阵:
  // 主管(is_team_owner)  → 可重置「副管 + 成员」(不可重置主管/自己)
  // 副管(is_team_admin)  → 只能重置「成员」(不可重置副管/主管/自己)
  // 成员                 → 看不到此按钮(不在管理员路由)
  const canResetPasswordFor = (m: TeamMember): boolean => {
    if (!currentUser) return false;
    if (m.id === currentUser.id) return false;     // 自己不能重置自己
    if (m.is_team_owner) return false;             // 主管密码只能超管重置
    if (m.is_team_admin && !currentUser.is_team_owner) return false; // 副管只有主管能重置
    return true;
  };

  // 权限矩阵(用户名修改): 同 canResetPasswordFor 但额外拒绝 admin 账号
  const canEditUsernameFor = (m: TeamMember): boolean => {
    if (!currentUser) return false;
    if (m.id === currentUser.id) return false;
    if (m.username === 'admin') return false;
    if (m.is_team_owner) return false;
    if (m.is_team_admin && !currentUser.is_team_owner) return false;
    return true;
  };

  const startEditUsername = (m: TeamMember) => {
    setEditingUsernameId(m.id);
    setEditingUsernameValue(m.username);
  };

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

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

  const handleResetPassword = async (m: TeamMember) => {
    if (!window.confirm(`重置「${m.username}」的密码?\n成员下次登录需要修改新密码。`)) return;
    try {
      const { data } = await teamApi.resetMemberPassword(m.id);
      setResetResult({ username: data.username, newPassword: data.new_password });
    } catch (e: any) {
      showToast(e?.response?.data?.error || '重置失败');
    }
  };

  const handleCopyPassword = () => {
    if (!resetResult) return;
    navigator.clipboard.writeText(resetResult.newPassword).then(() => showToast('已复制密码'));
  };

  const fetchMembers = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await teamApi.getMembers();
      setMembers(data.results);
    } catch {
      showToast('加载成员列表失败');
    } finally {
      setLoading(false);
    }
  }, []);

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

  const formatLimit = (v: number) => v === -1 ? '不限' : v + '次';
  const fmtMoney = (val: number) => '¥' + (val || 0).toFixed(2);

  const handleToggleStatus = async (member: TeamMember) => {
    try {
      await teamApi.updateMemberStatus(member.id, !member.is_active);
      showToast(member.is_active ? '已禁用成员' : '已启用成员');
      fetchMembers();
    } catch {
      showToast('操作失败');
    }
  };

  const openEditModal = (member: TeamMember) => {
    setEditMember(member);
    setEditDaily(String(member.daily_generation_limit ?? 50));
    setEditMonthly(String(member.monthly_generation_limit ?? 500));
    setEditSpendingLimit(String(member.spending_limit ?? -1));
  };

  const handleSaveQuota = async () => {
    if (!editMember) return;
    try {
      await teamApi.updateMemberQuota(editMember.id, Number(editDaily), Number(editMonthly), Number(editSpendingLimit));
      showToast('配额已更新');
      setEditMember(null);
      fetchMembers();
    } catch {
      showToast('更新失败');
    }
  };

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

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

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

      <div className={styles.filters}>
        <div className={styles.searchGroup}>
          <button className={styles.refreshBtn} onClick={fetchMembers}>刷新</button>
        </div>
        <div className={styles.searchGroup}>
          <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>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              Array.from({ length: 5 }).map((_, i) => (
                <tr key={i}>
                  {Array.from({ length: 9 }).map((_, j) => (
                    <td key={j}><div className={styles.skeletonCell} /></td>
                  ))}
                </tr>
              ))
            ) : members.length === 0 ? (
              <tr><td colSpan={9} className={styles.empty}>暂无成员</td></tr>
            ) : (
              members.map((m) => (
                <tr key={m.id}>
                  <td>
                    {editingUsernameId === m.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(m);
                            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(m)} 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' }}>
                        <span style={{
                          display: 'inline-block', width: 8, height: 8, borderRadius: '50%',
                          background: m.is_online ? 'var(--color-success)' : 'var(--color-text-quaternary)',
                          verticalAlign: 'middle',
                        }} />
                        <span>{m.username}</span>
                        {canEditUsernameFor(m) && (
                          <button
                            className={styles.editBtn}
                            onClick={() => startEditUsername(m)}
                            title="修改用户名"
                            style={{ fontSize: 12, padding: '2px 8px', whiteSpace: 'nowrap' }}
                          >
                            改名
                          </button>
                        )}
                      </span>
                    )}
                  </td>
                  <td>
                    {m.is_team_owner ? (
                      <span className={styles.statusBadge} style={{ background: 'var(--color-info-bg)', color: 'var(--color-info)' }}>主管理员</span>
                    ) : m.is_team_admin ? (
                      <span className={styles.statusBadge} style={{ background: 'var(--color-purple-bg)', color: 'var(--color-purple-accent)' }}>副管理员</span>
                    ) : (
                      <span style={{ color: 'var(--color-text-secondary)', fontSize: 12 }}>成员</span>
                    )}
                  </td>
                  <td>
                    <span className={`${styles.statusBadge} ${m.is_active ? styles.active : styles.disabled}`}>
                      {m.is_active ? '启用' : '禁用'}
                    </span>
                  </td>
                  <td>{formatLimit(m.daily_generation_limit)}</td>
                  <td>{formatLimit(m.monthly_generation_limit)}</td>
                  <td>{m.spending_limit === -1 ? '不限' : `¥${m.total_spent.toFixed(2)} / ¥${m.spending_limit.toFixed(2)}`}</td>
                  <td>{(m.generations_today || 0) + '次 / ' + fmtMoney(m.spent_today)}</td>
                  <td>{(m.generations_this_month || 0) + '次 / ' + fmtMoney(m.spent_this_month)}</td>
                  <td>
                    <div className={styles.actions}>
                      <button className={styles.editBtn} onClick={() => openEditModal(m)}>编辑配额</button>
                      {currentUser?.is_team_owner && !m.is_team_owner && (
                        m.is_team_admin ? (
                          <button className={styles.editBtn} onClick={async () => {
                            try { await teamApi.setMemberRole(m.id, false); showToast('已取消副管理员'); fetchMembers(); } catch { showToast('操作失败'); }
                          }}>取消副管理员</button>
                        ) : (
                          <button className={styles.editBtn} onClick={async () => {
                            try { await teamApi.setMemberRole(m.id, true); showToast('已设为副管理员'); fetchMembers(); } catch { showToast('操作失败'); }
                          }}>设为副管理员</button>
                        )
                      )}
                      {canResetPasswordFor(m) && (
                        <button className={styles.editBtn} onClick={() => handleResetPassword(m)}>
                          重置密码
                        </button>
                      )}
                      <button
                        className={`${styles.toggleBtn} ${m.is_active ? styles.disableBtn : styles.enableBtn}`}
                        onClick={() => setConfirmMember(m)}
                      >
                        {m.is_active ? '禁用' : '启用'}
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

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

      {/* Edit Quota Modal */}
      {editMember && (
        <div className={styles.modalOverlay} onMouseDown={(e) => { if (e.target === e.currentTarget) setEditMember(null); }}>
          <div className={styles.modal}>
            <h3 className={styles.modalTitle}>编辑配额 — {editMember.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={() => setEditMember(null)}>取消</button>
              <button className={styles.saveBtn} onClick={handleSaveQuota}>保存</button>
            </div>
          </div>
        </div>
      )}

      {/* Create Member 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="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>
            {createError && <div className={styles.formError}>{createError}</div>}
            <div className={styles.modalActions}>
              <button className={styles.cancelBtn} onClick={() => setCreateOpen(false)}>取消</button>
              <button className={styles.saveBtn} onClick={handleCreateMember}>创建</button>
            </div>
          </div>
        </div>
      )}

      {/* 重置密码结果 modal — 显示一次新密码 + 复制按钮(关闭后再也看不到了) */}
      {resetResult && (
        <div style={{ position: 'fixed', inset: 0, background: 'var(--color-overlay-strong)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 10001 }}
             onClick={() => setResetResult(null)}>
          <div style={{ background: 'var(--color-bg-modal)', borderRadius: 12, padding: 24,
                        width: 380, border: '1px solid var(--color-border-modal)',
                        boxShadow: '0 8px 24px var(--color-shadow-modal)' }}
               onClick={(e) => e.stopPropagation()}>
            <h3 style={{ margin: '0 0 12px', color: 'var(--color-text-light)', fontSize: 16 }}>
              密码重置成功
            </h3>
            <div style={{ fontSize: 13, color: 'var(--color-text-tertiary)', marginBottom: 16, lineHeight: 1.6 }}>
              已重置 <strong style={{ color: 'var(--color-text-light)' }}>{resetResult.username}</strong> 的密码。
              请把新密码告知该成员,他下次登录会被要求修改新密码。
            </div>
            <div style={{ background: 'var(--color-bg-elevated)', borderRadius: 8, padding: 14,
                          fontFamily: "'JetBrains Mono', ui-monospace, Menlo, Consolas, monospace",
                          fontSize: 16, color: 'var(--color-text-light)', letterSpacing: 1.5,
                          textAlign: 'center', marginBottom: 12 }}>
              {resetResult.newPassword}
            </div>
            <div style={{ fontSize: 11, color: 'var(--color-danger)', marginBottom: 16, lineHeight: 1.5 }}>
              ⚠ 关闭后无法再次查看,请立即复制并妥善保管。
            </div>
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
              <button onClick={handleCopyPassword}
                      style={{ padding: '6px 16px', borderRadius: 6,
                               border: '1px solid var(--color-border-modal)',
                               background: 'var(--color-bg-elevated)',
                               color: 'var(--color-text-light)', cursor: 'pointer', fontSize: 13 }}>
                复制密码
              </button>
              <button onClick={() => setResetResult(null)}
                      style={{ padding: '6px 16px', borderRadius: 6, border: 'none',
                               background: 'var(--color-primary)', color: 'var(--color-on-primary)',
                               cursor: 'pointer', fontSize: 13 }}>
                关闭
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
