import { useEffect, useRef, useState } from 'react';
import {
  fetchAdminUsers,
  patchAdminUser,
  rechargeUser,
  createAdminUser,
  type AdminUser,
} from '../../api/admin';

type EditTarget = { user: AdminUser; mode: 'edit' | 'recharge' | 'create' };

const PAGE_SIZE = 20;

export function UsersPage() {
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [search, setSearch] = useState('');
  const [roleFilter, setRoleFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [editTarget, setEditTarget] = useState<EditTarget | null>(null);

  const load = async (p = page) => {
    setLoading(true);
    setError(null);
    try {
      const result = await fetchAdminUsers({
        page: p,
        pageSize: PAGE_SIZE,
        search: search.trim() || undefined,
        role: roleFilter || undefined,
        status: statusFilter || undefined,
      });
      setUsers(result.users);
      setTotal(result.total);
      setTotalPages(result.totalPages);
      setPage(p);
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void load(1);
  }, []);

  const handleSearch = () => void load(1);

  return (
    <div className="grid">
      {/* Filters */}
      <div className="card" style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
        <input
          type="search"
          placeholder="用户名 / 昵称 / 邮箱"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
          style={{ flex: '1 1 200px', padding: '8px 12px', borderRadius: 999, border: '1px solid #d6d0c3' }}
        />
        <select
          value={roleFilter}
          onChange={(e) => setRoleFilter(e.target.value)}
          style={{ padding: '8px 12px', borderRadius: 999, border: '1px solid #d6d0c3' }}
        >
          <option value="">全部角色</option>
          <option value="user">user</option>
          <option value="admin">admin</option>
        </select>
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          style={{ padding: '8px 12px', borderRadius: 999, border: '1px solid #d6d0c3' }}
        >
          <option value="">全部状态</option>
          <option value="active">active</option>
          <option value="suspended">suspended</option>
        </select>
        <button type="button" className="btn" onClick={handleSearch} disabled={loading}>
          搜索
        </button>
        <button
          type="button"
          className="btn secondary"
          onClick={() =>
            setEditTarget({
              user: { id: '', username: '', slug: '', email: '', displayName: '', role: 'user', status: 'active', balanceCents: 0, createdAt: '' },
              mode: 'create',
            })
          }
        >
          新建用户
        </button>
        <span style={{ color: '#68716c', fontSize: 13, marginLeft: 'auto' }}>共 {total} 个用户</span>
      </div>

      {error ? <p className="alert">{error}</p> : null}

      {/* Table */}
      <div className="card" style={{ overflowX: 'auto', padding: 0 }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: '#f5f0e5', borderBottom: '1px solid #d6d0c3' }}>
              {['用户名', '昵称', '角色', '状态', '余额', '注册时间', '操作'].map((h) => (
                <th key={h} style={{ padding: '10px 12px', textAlign: 'left', fontWeight: 600 }}>
                  {h}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {users.map((u) => (
              <tr key={u.id} style={{ borderBottom: '1px solid #ebe4d6' }}>
                <td style={{ padding: '10px 12px' }}>
                  <code style={{ fontSize: 12 }}>{u.username}</code>
                </td>
                <td style={{ padding: '10px 12px' }}>{u.displayName}</td>
                <td style={{ padding: '10px 12px' }}>
                  <span
                    style={{
                      padding: '2px 8px',
                      borderRadius: 999,
                      fontSize: 11,
                      background: u.role === 'admin' ? '#2f6f57' : '#ebe4d6',
                      color: u.role === 'admin' ? 'white' : 'inherit',
                    }}
                  >
                    {u.role}
                  </span>
                </td>
                <td style={{ padding: '10px 12px' }}>
                  <span style={{ color: u.status === 'suspended' ? '#b42318' : '#2f6f57', fontSize: 12 }}>
                    {u.status}
                  </span>
                </td>
                <td style={{ padding: '10px 12px' }}>{yuan(u.balanceCents)}</td>
                <td style={{ padding: '10px 12px', color: '#68716c', whiteSpace: 'nowrap' }}>
                  {u.createdAt ? new Date(u.createdAt).toLocaleDateString('zh-CN') : '—'}
                </td>
                <td style={{ padding: '10px 12px' }}>
                  <div style={{ display: 'flex', gap: 6 }}>
                    <button
                      type="button"
                      className="btn secondary"
                      style={{ padding: '4px 10px', fontSize: 12 }}
                      onClick={() => setEditTarget({ user: u, mode: 'edit' })}
                    >
                      编辑
                    </button>
                    <button
                      type="button"
                      className="btn secondary"
                      style={{ padding: '4px 10px', fontSize: 12 }}
                      onClick={() => setEditTarget({ user: u, mode: 'recharge' })}
                    >
                      充值
                    </button>
                  </div>
                </td>
              </tr>
            ))}
            {users.length === 0 && !loading ? (
              <tr>
                <td colSpan={7} style={{ padding: 24, textAlign: 'center', color: '#68716c' }}>
                  暂无用户
                </td>
              </tr>
            ) : null}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {totalPages > 1 ? (
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <button
            type="button"
            className="btn secondary"
            disabled={page <= 1}
            onClick={() => void load(page - 1)}
          >
            上一页
          </button>
          <span style={{ fontSize: 13, color: '#68716c' }}>
            第 {page} / {totalPages} 页
          </span>
          <button
            type="button"
            className="btn secondary"
            disabled={page >= totalPages}
            onClick={() => void load(page + 1)}
          >
            下一页
          </button>
        </div>
      ) : null}

      {/* Modal */}
      {editTarget ? (
        <EditModal
          target={editTarget}
          onClose={() => setEditTarget(null)}
          onSuccess={() => {
            setEditTarget(null);
            void load(page);
          }}
        />
      ) : null}
    </div>
  );
}

function EditModal({
  target,
  onClose,
  onSuccess,
}: {
  target: EditTarget;
  onClose: () => void;
  onSuccess: () => void;
}) {
  const { user, mode } = target;
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // edit fields
  const [role, setRole] = useState(user.role);
  const [status, setStatus] = useState(user.status ?? 'active');
  const [displayName, setDisplayName] = useState(user.displayName);
  const [password, setPassword] = useState('');

  // create fields
  const [newUsername, setNewUsername] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [newDisplayName, setNewDisplayName] = useState('');
  const [newRole, setNewRole] = useState('user');

  // recharge fields
  const [amountYuan, setAmountYuan] = useState('');
  const [note, setNote] = useState('');

  const dialogRef = useRef<HTMLDivElement>(null);

  const handleSubmit = async () => {
    setBusy(true);
    setError(null);
    try {
      if (mode === 'create') {
        if (!newUsername.trim() || !newPassword.trim()) {
          setError('用户名和密码必填');
          return;
        }
        await createAdminUser({ username: newUsername.trim(), password: newPassword, displayName: newDisplayName.trim() || undefined, role: newRole });
      } else if (mode === 'edit') {
        const patch: Record<string, string> = {};
        if (role !== user.role) patch.role = role;
        if (status !== user.status) patch.status = status;
        if (displayName !== user.displayName) patch.displayName = displayName;
        if (password) patch.password = password;
        if (Object.keys(patch).length === 0) { onClose(); return; }
        await patchAdminUser(user.id, patch);
      } else {
        const cents = Math.round(parseFloat(amountYuan) * 100);
        if (!cents || cents <= 0) { setError('请输入有效金额'); return; }
        await rechargeUser(user.id, cents, note.trim());
      }
      onSuccess();
    } catch (err) {
      setError(err instanceof Error ? err.message : '操作失败');
    } finally {
      setBusy(false);
    }
  };

  const titles: Record<EditTarget['mode'], string> = {
    edit: `编辑用户：${user.username}`,
    recharge: `充值：${user.username}（当前 ${yuan(user.balanceCents)}）`,
    create: '新建用户',
  };

  return (
    <div
      style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,.35)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100,
      }}
      onClick={(e) => e.target === e.currentTarget && onClose()}
    >
      <div
        ref={dialogRef}
        className="card grid"
        style={{ width: '100%', maxWidth: 480, margin: 16, maxHeight: '90vh', overflowY: 'auto' }}
      >
        <h3 style={{ margin: 0 }}>{titles[mode]}</h3>

        {mode === 'create' ? (
          <>
            <Field label="用户名">
              <input value={newUsername} onChange={(e) => setNewUsername(e.target.value)} placeholder="login username" />
            </Field>
            <Field label="密码">
              <input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} />
            </Field>
            <Field label="昵称（可选）">
              <input value={newDisplayName} onChange={(e) => setNewDisplayName(e.target.value)} />
            </Field>
            <Field label="角色">
              <select value={newRole} onChange={(e) => setNewRole(e.target.value)}>
                <option value="user">user</option>
                <option value="admin">admin</option>
              </select>
            </Field>
          </>
        ) : mode === 'edit' ? (
          <>
            <Field label="昵称">
              <input value={displayName} onChange={(e) => setDisplayName(e.target.value)} />
            </Field>
            <Field label="角色">
              <select value={role} onChange={(e) => setRole(e.target.value)}>
                <option value="user">user</option>
                <option value="admin">admin</option>
              </select>
            </Field>
            <Field label="状态">
              <select value={status} onChange={(e) => setStatus(e.target.value)}>
                <option value="active">active</option>
                <option value="suspended">suspended</option>
              </select>
            </Field>
            <Field label="新密码（不改留空）">
              <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="留空不修改" />
            </Field>
          </>
        ) : (
          <>
            <Field label="充值金额（元）">
              <input
                type="number"
                min="0.01"
                step="0.01"
                value={amountYuan}
                onChange={(e) => setAmountYuan(e.target.value)}
                placeholder="例：5.00"
              />
            </Field>
            <Field label="备注">
              <input value={note} onChange={(e) => setNote(e.target.value)} placeholder="管理员赠送" />
            </Field>
          </>
        )}

        {error ? <p className="alert">{error}</p> : null}

        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <button type="button" className="btn secondary" onClick={onClose} disabled={busy}>取消</button>
          <button type="button" className="btn" onClick={() => void handleSubmit()} disabled={busy}>
            {busy ? '处理中…' : '确认'}
          </button>
        </div>
      </div>
    </div>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div style={{ display: 'grid', gap: 4 }}>
      <label style={{ fontSize: 12, color: '#68716c' }}>{label}</label>
      <div
        style={{
          display: 'contents',
        }}
        // apply common input styles via CSS
      >
        {children}
      </div>
    </div>
  );
}

function yuan(cents: number) {
  return `¥${(cents / 100).toFixed(2)}`;
}
