'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import type { PlanListItem } from '@pac/types';
import { plansApi } from './plans-api';

const PAGE_SIZE = 20;

export interface UseMyTasks {
  items: PlanListItem[];
  total: number;
  loading: boolean;
  hasMore: boolean;
  error: string | null;
  /** 触底分页:加载下一页(累加到 items)*/
  loadMore: () => void;
  /** 重置重新拉第一页 */
  reset: () => void;
}

/**
 * 我的任务 — view=mine 服务端分页 + 触底累加(infinite scroll)。
 * 状态筛选 / 搜索由调用方在 items 上客户端做(跟设计抽屉一致)。
 */
export function useMyTasks(): UseMyTasks {
  const [items, setItems] = useState<PlanListItem[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const loadingRef = useRef(false);

  const fetchPage = useCallback(async (p: number) => {
    if (loadingRef.current) return;
    loadingRef.current = true;
    setLoading(true);
    setError(null);
    try {
      const data = await plansApi.list({ view: 'mine', page: p, pageSize: PAGE_SIZE });
      setTotal(data.total);
      setItems((prev) => {
        if (p === 1) return data.items;
        // 去重累加(幂等防重复 enqueue / 快速滚动)
        const seen = new Set(prev.map((x) => x.id));
        return [...prev, ...data.items.filter((x) => !seen.has(x.id))];
      });
      setPage(p);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      loadingRef.current = false;
      setLoading(false);
    }
  }, []);

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

  const hasMore = items.length < total;

  const loadMore = useCallback(() => {
    if (loadingRef.current || !hasMore) return;
    void fetchPage(page + 1);
  }, [fetchPage, hasMore, page]);

  const reset = useCallback(() => {
    setItems([]);
    setTotal(0);
    setPage(1);
    void fetchPage(1);
  }, [fetchPage]);

  return { items, total, loading, hasMore, error, loadMore, reset };
}
