import { useEffect, useState } from 'react';
import type { TemplateGeneration } from '@/lib/api/template-generations';
import { getTemplateGenerations } from '@/lib/api/template-generations';

type TabKey = 'all' | 'image' | 'video';

export function useProfileData(activeTab: TabKey) {
  const [generations, setGenerations] = useState<TemplateGeneration[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [isTabSwitching, setIsTabSwitching] = useState(false);

  useEffect(() => {
    setCurrentPage(1);
    setHasMore(true);
    setIsTabSwitching(true);
    loadGenerations(1, false, true);
  }, [activeTab]);

  const loadGenerations = async (page = 1, isRefresh = false, isTabSwitch = false) => {
    try {
      if (isRefresh) {
        setIsRefreshing(true);
      } else if (page === 1 && !isTabSwitch) {
        setIsLoading(true);
      } else if (page > 1) {
        setIsLoadingMore(true);
      }
      setError(null);

      const response = await getTemplateGenerations({
        page,
        limit: 20,
        type: activeTab === 'all' ? undefined : activeTab === 'image' ? 'IMAGE' : 'VIDEO'
      });

      if (response.success) {
        const newGenerations = response.data.generations;
        const totalPages = Math.ceil(response.data.total / response.data.limit);

        if (isRefresh || page === 1) {
          setGenerations(newGenerations);
        } else {
          setGenerations(prev => [...prev, ...newGenerations]);
        }

        setHasMore(page < totalPages);
        setCurrentPage(page);
      }
    } catch (err) {
      console.error('Failed to load generations:', err);
      const errorMessage = err instanceof Error ? err.message : 'Failed to load content';
      // 401 错误由 AuthProvider 处理,不显示错误页面
      if (!errorMessage.includes('401')) {
        setError(errorMessage);
      }
    } finally {
      setIsLoading(false);
      setIsRefreshing(false);
      setIsLoadingMore(false);
      setIsTabSwitching(false);
    }
  };

  const handleRefresh = () => {
    loadGenerations(1, true);
  };

  const handleLoadMore = () => {
    if (!isLoadingMore && hasMore) {
      loadGenerations(currentPage + 1, false);
    }
  };

  return {
    generations,
    isLoading,
    error,
    isRefreshing,
    isLoadingMore,
    hasMore,
    isTabSwitching,
    handleRefresh,
    handleLoadMore,
  };
}
