"use client";

import { useGetMeetList } from "@/hooks/useHome";
import { useHomeData } from "../../context/HomeDataContext";
import AIStandardCard from "@/components/features/ai-standard-card";
import { useEffect, useState, useMemo } from "react";
import { Skeleton } from "@/components/ui/skeleton";

const Recommend = () => {
  const { setRecommendExcludeList, setIsRecommendDataReady } = useHomeData();
  
  // 获取 ALL 分类的数据，只获取第一页的10条数据
  const { data, isLoading } = useGetMeetList({
    characterCodeList: [],
    ps: 10,
  });

  // 获取第一页前10条数据
  const firstPageData = useMemo(() => {
    return data?.pages[0]?.slice(0, 10) || [];
  }, [data]);

  // 当数据加载完成后，更新排除列表并标记数据已准备好
  useEffect(() => {
    if (firstPageData.length > 0) {
      const excludeIds = firstPageData
        .map(item => item.aiId)
        .filter((id): id is number => id !== undefined);
      setRecommendExcludeList(excludeIds);
      setIsRecommendDataReady(true);
    }
  }, [firstPageData, setRecommendExcludeList, setIsRecommendDataReady]);

  // 计算当前屏幕宽度下的列数
  const getColumnsCount = () => {
    if (typeof window === 'undefined') return 4;
    const width = window.innerWidth;
    if (width < 640) return 1; // 移动端: 2列
    if (width < 1024) return 2; // sm-lg: 3列
    if (width < 1280) return 3; // lg-xl: 4列
    if (width < 1440) return 4; // 2xl: 5列
    if (width < 1536) return 4; // 2xl: 5列
    return 5; // xl+: 5列
  };

  const [columnsCount, setColumnsCount] = useState(getColumnsCount());

  // 监听窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      setColumnsCount(getColumnsCount());
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // 计算需要显示的数据（只显示完整的行）
  const getDisplayData = () => {
    const fullRows = Math.floor(firstPageData.length / columnsCount);
    return firstPageData.slice(0, fullRows * columnsCount);
  };

  const displayData = getDisplayData();

  return (
    <div className="mt-12">
      {/* 标题栏 */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-2">
          <span className="text-2xl">✨</span>
          <h2 className="txt-headline-s">Recommended</h2>
        </div>
      </div>

      {/* 卡片网格 */}
      {isLoading ? (
        <div 
          className="grid gap-6"
          style={{
            gridTemplateColumns: `repeat(${columnsCount}, minmax(0, 1fr))`
          }}
        >
          {Array.from({ length: columnsCount * 2 }).map((_, index) => (
            <div key={index} className="flex flex-col gap-3">
              <Skeleton className="aspect-[3/4] rounded-[16px]" />
            </div>
          ))}
        </div>
      ) : displayData.length > 0 ? (
        <div 
          className="grid gap-6"
          style={{
            gridTemplateColumns: `repeat(${columnsCount}, minmax(0, 1fr))`
          }}
        >
          {displayData.map((character) => (
            <AIStandardCard
              key={character.aiId}
              character={character}
            />
          ))}
        </div>
      ) : (
        <div className="flex items-center justify-center py-12 text-txt-secondary-normal">
          No recommendations available
        </div>
      )}
    </div>
  );
};

export default Recommend;