import { useEffect, useMemo, useState } from 'react';
import { fetchReviewQueue, reviewPost, batchReviewPosts, type ReviewPost } from '../api/client';
import { plazaPreviewUrl } from '../lib/site';

const TABS = [
  { key: 'pending_review', label: '待审核' },
  { key: 'published', label: '已通过' },
  { key: 'rejected', label: '已拒绝' },
] as const;

type TabKey = (typeof TABS)[number]['key'];

export function ReviewPage() {
  const [tab, setTab] = useState<TabKey>('pending_review');
  const [posts, setPosts] = useState<ReviewPost[]>([]);
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [error, setError] = useState<string | null>(null);
  const [busyId, setBusyId] = useState<string | null>(null);
  const [batchBusy, setBatchBusy] = useState(false);
  const [keyword, setKeyword] = useState('');

  const load = async (status: TabKey = tab, search = keyword) => {
    setError(null);
    try {
      const query = new URLSearchParams({ status });
      if (search.trim()) query.set('keyword', search.trim());
      const data = await fetchReviewQueue(query.toString());
      setPosts(data.posts);
      setSelected(new Set());
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载失败');
    }
  };

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

  const pendingCount = useMemo(
    () => (tab === 'pending_review' ? posts.length : null),
    [tab, posts.length],
  );

  const allSelected = useMemo(
    () => posts.length > 0 && posts.every((post) => selected.has(post.id)),
    [posts, selected],
  );

  const toggleSelect = (id: string) => {
    setSelected((current) => {
      const next = new Set(current);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const toggleSelectAll = () => {
    if (allSelected) {
      setSelected(new Set());
      return;
    }
    setSelected(new Set(posts.map((post) => post.id)));
  };

  const handleReview = async (id: string, action: 'approve' | 'reject') => {
    setBusyId(id);
    try {
      const reason =
        action === 'reject'
          ? window.prompt('拒绝原因（必填）', '低质内容') ?? undefined
          : undefined;
      if (action === 'reject' && !reason) return;
      await reviewPost(id, action, reason);
      await load(tab);
    } catch (err) {
      setError(err instanceof Error ? err.message : '操作失败');
    } finally {
      setBusyId(null);
    }
  };

  const handleBatchApprove = async () => {
    const ids = [...selected];
    if (ids.length === 0) return;
    if (!window.confirm(`确认批量通过 ${ids.length} 条帖子？`)) return;
    setBatchBusy(true);
    setError(null);
    try {
      await batchReviewPosts(ids, 'approve');
      await load(tab);
    } catch (err) {
      setError(err instanceof Error ? err.message : '批量操作失败');
    } finally {
      setBatchBusy(false);
    }
  };

  return (
    <div className="grid">
      <div className="card" style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
        {TABS.map((item) => (
          <button
            key={item.key}
            type="button"
            className={tab === item.key ? 'btn' : 'btn secondary'}
            onClick={() => setTab(item.key)}
          >
            {item.label}
            {item.key === 'pending_review' && tab === 'pending_review' && pendingCount != null
              ? ` (${pendingCount})`
              : ''}
          </button>
        ))}
        <input
          type="search"
          placeholder="搜索标题 / 作者"
          value={keyword}
          onChange={(event) => setKeyword(event.target.value)}
          onKeyDown={(event) => {
            if (event.key === 'Enter') void load(tab, keyword);
          }}
          style={{ flex: '1 1 200px', minWidth: 180, padding: '8px 12px', borderRadius: 999, border: '1px solid #d6d0c3' }}
        />
        <button type="button" className="btn secondary" onClick={() => void load(tab, keyword)}>
          搜索
        </button>
        {tab === 'pending_review' && posts.length > 0 ? (
          <>
            <button type="button" className="btn secondary" onClick={toggleSelectAll}>
              {allSelected ? '取消全选' : '全选'}
            </button>
            <button
              type="button"
              className="btn"
              disabled={batchBusy || selected.size === 0}
              onClick={() => void handleBatchApprove()}
            >
              {batchBusy ? '处理中…' : `批量通过 (${selected.size})`}
            </button>
          </>
        ) : null}
      </div>
      {error ? <p className="alert">{error}</p> : null}
      {posts.length === 0 ? <div className="card">暂无{tab === 'pending_review' ? '待审核' : ''}帖子</div> : null}
      {posts.map((post) => (
        <div key={post.id} className="card grid">
          <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12 }}>
            <div style={{ display: 'flex', gap: 10, alignItems: 'start' }}>
              {tab === 'pending_review' ? (
                <input
                  type="checkbox"
                  checked={selected.has(post.id)}
                  onChange={() => toggleSelect(post.id)}
                  aria-label={`选择 ${post.title}`}
                />
              ) : null}
              <div>
                <h3>{post.title}</h3>
                <p style={{ color: '#68716c' }}>
                  {post.category.icon} {post.category.name} · @{post.author.slug}
                </p>
                {post.sla_warning ? <p className="warn">已超过 2 小时未审核</p> : null}
              </div>
            </div>
            {tab === 'pending_review' ? (
              <div style={{ display: 'flex', gap: 8, alignItems: 'start' }}>
                <button
                  type="button"
                  className="btn"
                  disabled={busyId === post.id}
                  onClick={() => void handleReview(post.id, 'approve')}
                >
                  通过
                </button>
                <button
                  type="button"
                  className="btn secondary"
                  disabled={busyId === post.id}
                  onClick={() => void handleReview(post.id, 'reject')}
                >
                  拒绝
                </button>
                <a
                  className="btn secondary"
                  href={plazaPreviewUrl(post.id)}
                  target="_blank"
                  rel="noreferrer"
                >
                  预览
                </a>
              </div>
            ) : (
              <a
                className="btn secondary"
                href={plazaPreviewUrl(post.id)}
                target="_blank"
                rel="noreferrer"
              >
                查看
              </a>
            )}
          </div>
          {post.summary ? <p>{post.summary}</p> : null}
        </div>
      ))}
    </div>
  );
}
