import { useRef, useEffect, useState, useMemo, useCallback } from 'react';
import { Sidebar } from './Sidebar';
import { InputBar } from './InputBar';
import { GenerationCard } from './GenerationCard';
import { VideoDetailModal } from './VideoDetailModal';
import { useGenerationStore } from '../store/generation';
import { useAuthStore } from '../store/auth';
import type { GenerationTask } from '../types';
import styles from './VideoGenerationPage.module.css';

export function VideoGenerationPage() {
  const tasks = useGenerationStore((s) => s.tasks);
  const loadTasks = useGenerationStore((s) => s.loadTasks);
  const loadMore = useGenerationStore((s) => s.loadMore);
  const isLoadingMore = useGenerationStore((s) => s.isLoadingMore);
  const teamDisabled = useAuthStore((s) => s.teamDisabled);
  const reEdit = useGenerationStore((s) => s.reEdit);
  const regenerate = useGenerationStore((s) => s.regenerate);
  const removeTask = useGenerationStore((s) => s.removeTask);
  const scrollRef = useRef<HTMLDivElement>(null);
  const prevLastIdRef = useRef<string | null>(null);
  const initialLoadRef = useRef(true);
  // 防重入 flag：loadMore + anchor 期间，handleScroll 多次触发不再 schedule 多个 rAF，
  // 避免 anchor 累加把页面推到底（慢速滚轮 / 慢拖滑动条场景）。
  const loadMoreInFlightRef = useRef(false);
  const savedScrollTop = useGenerationStore((s) => s.savedScrollTop);
  const saveScrollPosition = useGenerationStore((s) => s.saveScrollPosition);
  const [detailTaskId, setDetailTaskId] = useState<string | null>(null);
  const [showScrollBottom, setShowScrollBottom] = useState(false);
  const detailTask = useMemo(() => detailTaskId ? tasks.find((t) => t.id === detailTaskId) || null : null, [detailTaskId, tasks]);
  const setDetailTask = useCallback((t: GenerationTask | null) => setDetailTaskId(t?.id || null), []);

  // Load tasks from backend on mount (persist across page refresh)
  useEffect(() => {
    loadTasks();
  }, [loadTasks]);

  // Restore scroll position after initial load, or scroll to bottom ONLY when a new task
  // is appended at the tail. 通过比较末尾 task 的 id 来判断 —— 头部加载历史（prepend）、
  // 任务状态更新（如轮询完成）、删除某条都不会改变末尾 id，因此不会触发滚动，
  // 避免用户往上翻时被突然拽回底部。
  useEffect(() => {
    if (tasks.length === 0) return;
    const currentLastId = tasks[tasks.length - 1]?.id ?? null;

    if (initialLoadRef.current) {
      initialLoadRef.current = false;
      // Use requestAnimationFrame to ensure DOM has rendered
      const restoreTop = savedScrollTop;
      requestAnimationFrame(() => {
        if (restoreTop !== null && scrollRef.current) {
          scrollRef.current.scrollTop = restoreTop;
        } else if (scrollRef.current) {
          scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
        }
      });
      prevLastIdRef.current = currentLastId;
      return;
    }

    if (currentLastId !== prevLastIdRef.current && scrollRef.current) {
      scrollRef.current.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' });
    }
    prevLastIdRef.current = currentLastId;
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tasks]);

  // Save scroll position + auto-load older tasks when scrolled near top
  const handleScroll = useCallback(() => {
    if (!scrollRef.current) return;
    saveScrollPosition(scrollRef.current.scrollTop);

    // Show "scroll to bottom" button when not near bottom
    const el = scrollRef.current;
    const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
    setShowScrollBottom(distanceFromBottom > 300);

    // Trigger loadMore when scrolled within 100px of the top.
    // ref flag 守卫：只有第一次进入分支时才 schedule loadMore + anchor；
    // 后续 handleScroll（慢速操作下持续触发）直接跳过，避免多次 rAF 排队累加 +diff。
    if (scrollRef.current.scrollTop < 100 && !loadMoreInFlightRef.current) {
      loadMoreInFlightRef.current = true;
      const el = scrollRef.current;
      const prevHeight = el.scrollHeight;
      loadMore().then(() => {
        // After older tasks are prepended, restore visual position so user doesn't jump.
        // CSS overflow-anchor: none 已禁用浏览器自动 anchor，由这里独立完成。
        requestAnimationFrame(() => {
          const diff = el.scrollHeight - prevHeight;
          if (diff > 0) el.scrollTop += diff;
          loadMoreInFlightRef.current = false;
        });
      });
    }
  }, [saveScrollPosition, loadMore]);

  const handleReEdit = (id: string) => {
    reEdit(id);
    setDetailTask(null);
  };

  const handleRegenerate = (id: string) => {
    regenerate(id);
    setDetailTask(null);
  };

  const handleDelete = (id: string) => {
    removeTask(id);
    setDetailTask(null);
  };

  const completedTasks = useMemo(
    () => tasks.filter((t) => t.status === 'completed' && t.resultUrl),
    [tasks],
  );
  const detailIdx = detailTask ? completedTasks.findIndex((t) => t.id === detailTask.id) : -1;

  if (teamDisabled) {
    return (
      <div className={styles.layout}>
        <Sidebar />
        <main className={styles.main}>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            height: '100%', flexDirection: 'column', gap: 16,
            color: 'var(--color-text-secondary)',
          }}>
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="var(--color-text-secondary)" strokeWidth="1.5">
              <circle cx="12" cy="12" r="10" />
              <path d="M4.93 4.93l14.14 14.14" />
            </svg>
            <p style={{ fontSize: 18, color: 'var(--color-text-primary)' }}>您的团队已被停用</p>
            <p>请联系管理员</p>
          </div>
        </main>
      </div>
    );
  }

  return (
    <div className={styles.layout}>
      <Sidebar />
      <main className={styles.main}>
        {/* 旧的右上角公告小喇叭已删 — 公告统一走 sidebar 大铃铛 → 消息中心 */}
        <div className={styles.contentArea} ref={scrollRef} onScroll={handleScroll}>
          {tasks.length === 0 ? (
            <div className={styles.emptyArea}>
              <p className={styles.emptyHint}>Every frame was once just air.</p>
            </div>
          ) : (
            <div className={styles.taskList}>
              {isLoadingMore && (
                <div className={styles.loadMoreWrap}>
                  <span className={styles.loadMoreText}>加载中…</span>
                </div>
              )}
              {tasks.map((task) => (
                <GenerationCard
                  key={task.id}
                  task={task}
                  onOpenDetail={setDetailTask}
                />
              ))}
            </div>
          )}
        </div>
        <InputBar scrollBottomBtn={showScrollBottom ? (
          <button
            onClick={() => scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' })}
            style={{
              marginLeft: 'auto',
              background: 'var(--color-bg-card)',
              backdropFilter: 'blur(24px) saturate(180%)',
              WebkitBackdropFilter: 'blur(24px) saturate(180%)',
              border: '1px solid var(--color-border-card)',
              boxShadow: '0 0 0 1px var(--color-inset-highlight) inset, 0 4px 16px var(--color-overlay-medium)',
              borderRadius: 6, padding: '4px 12px', fontSize: 12,
              color: 'var(--color-text-secondary)', cursor: 'pointer',
              transition: 'all 0.15s', whiteSpace: 'nowrap',
            }}
            onMouseEnter={(e) => { (e.currentTarget as HTMLElement).style.background = 'var(--color-bg-hover)'; (e.currentTarget as HTMLElement).style.color = 'var(--color-text-primary)'; }}
            onMouseLeave={(e) => { (e.currentTarget as HTMLElement).style.background = 'var(--color-bg-card)'; (e.currentTarget as HTMLElement).style.color = 'var(--color-text-secondary)'; }}
          >
            回到底部 ↓
          </button>
        ) : null} />
      </main>
      <VideoDetailModal
        task={detailTask}
        onClose={() => setDetailTask(null)}
        onReEdit={handleReEdit}
        onRegenerate={handleRegenerate}
        onDelete={handleDelete}
        onToggleFavorite={(id) => { useGenerationStore.getState().toggleFavorite(id); }}
        hasPrev={detailIdx > 0}
        hasNext={detailIdx >= 0 && detailIdx < completedTasks.length - 1}
        onPrev={() => detailIdx > 0 && setDetailTask(completedTasks[detailIdx - 1])}
        onNext={() => detailIdx < completedTasks.length - 1 && setDetailTask(completedTasks[detailIdx + 1])}
      />
      {/* 公告弹窗已搬到 App.tsx 顶层 GlobalAnnouncementGate(任意路由有未读公告自动强弹) */}
      {/* 重看历史公告 → 走 sidebar 大铃铛 → 消息中心页 */}
    </div>
  );
}
