"use client";

import * as React from 'react';
import MeetHeader from './MeetHeader';
import MeetList from './MeetList';
import { useState } from 'react';
import { useCreateDict } from '@/hooks/create';
import { useGetMeetList } from '@/hooks/useHome';
import { useHomeData } from '../../context/HomeDataContext';
import { GetMeetListRequest, GetMeetListResponse } from '@/services/home/types';
import { useRouter } from 'next/navigation';
import { FilterOptions } from './FilterDrawer';

const MoreType = () => {
  const router = useRouter();
  const { data: dictData } = useCreateDict();
  const { recommendExcludeList, isRecommendDataReady } = useHomeData();
  const [selectedRole, setSelectedRole] = useState<string>('');
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [filters, setFilters] = useState<FilterOptions>({
    gender: [],
    age: [],
    type: []
  });

  const { characterDictList } = dictData || {};

  // 构建 useGetMeetList 的参数
  const meetListParams = React.useMemo(() => {
    // 判断是否有任何筛选条件
    const hasAnyFilter = selectedTags.length > 0 || 
                        filters.gender.length > 0 || 
                        filters.age.length > 0 || 
                        filters.type.length > 0;
    
    const result: any = {
      characterCodeList: selectedRole && selectedRole !== 'ALL' ? [selectedRole] : [],
      tagCodeList: selectedTags,
      roleCodeList: filters.type, // 使用类型筛选作为 tagCodeList
      ps: 20, // 每页20条数据
      ...(filters.gender.length > 0 ? { sexList: filters.gender } : {}),
      ...(filters.age.length > 0 ? { ageList: filters.age } : {}),
      // 只有当选择 ALL 且没有任何筛选条件时，才添加排除列表
      ...(selectedRole === 'ALL' && !hasAnyFilter && recommendExcludeList.length > 0 ? { exList: recommendExcludeList } : {}),
    };
    
    // 过滤掉空字符串和空数组字段
    const filteredResult = Object.fromEntries(
      Object.entries(result).filter(([key, value]) => {
        if (Array.isArray(value)) {
          return value.length > 0;
        }
        if (typeof value === 'string') {
          return value !== '';
        }
        return value !== undefined && value !== null;
      })
    );
    return filteredResult;
  }, [selectedRole, selectedTags, filters, recommendExcludeList]);

  // 使用 useGetMeetList hook，只有在 selectedRole 有值且满足条件时才启用查询
  const shouldEnableQuery = React.useMemo(() => {
    if (!selectedRole) return false;
    
    // 如果不是 ALL，直接启用查询
    if (selectedRole !== 'ALL') return true;
    
    // 判断是否有任何筛选条件
    const hasAnyFilter = selectedTags.length > 0 || 
                        filters.gender.length > 0 || 
                        filters.age.length > 0 || 
                        filters.type.length > 0;
    
    // 如果是 ALL 且有筛选条件，直接启用查询（不需要等待 Recommend 数据）
    if (hasAnyFilter) return true;
    
    // 如果是 ALL 且没有筛选条件，需要等待 Recommend 数据准备好
    return isRecommendDataReady;
  }, [selectedRole, selectedTags, filters, isRecommendDataReady]);

  const {
    data: meetData,
    fetchNextPage,
    hasNextPage,
    isLoading,
    isFetchingNextPage,
    error,
    refetch
  } = useGetMeetList(
    meetListParams as unknown as Omit<GetMeetListRequest, 'pn'>, 
    shouldEnableQuery
  );

  // 扁平化所有页面的数据
  const allMeetItems = React.useMemo(() => {
    if (!meetData?.pages) return [];
    return meetData.pages.flat();
  }, [meetData]);

  // 当角色数据加载后，默认选中ALL
  React.useEffect(() => {
    if (characterDictList && characterDictList.length > 0 && !selectedRole) {
      setSelectedRole('ALL');
    }
  }, [characterDictList, selectedRole]);

  // 计算当前选中角色的快速标签
  const quickTags = React.useMemo(() => {
    if (selectedRole === 'ALL') {
      return []; // ALL选项不显示快速标签
    }
    const findCharacter = characterDictList?.find((item) => item.code === selectedRole);
    if (findCharacter) {
      return findCharacter.childDictList || []
    }
    return []
  }, [characterDictList, selectedRole]);

  const handleRoleChange = (roleCode: string) => {
    setSelectedRole(roleCode);
    // 切换角色时清空已选标签
    setSelectedTags([]);
  };
  
  const handleTagsChange = (tagCodes: string[]) => {
    setSelectedTags(tagCodes);
  };

  const handleFilterClick = () => {
    console.log('Filter clicked');
  };

  const handleFiltersChange = (newFilters: FilterOptions) => {
    setFilters(newFilters);
  };

  // 处理角色卡片点击
  const handleCharacterClick = (character: GetMeetListResponse) => {
    if (character.aiId) {
      router.push(`/chat/${character.aiId}`);
    }
  };

  return (
    <div className="pb-[200px]">
      <MeetHeader
        selectedRole={selectedRole}
        selectedTags={selectedTags}
        roles={characterDictList || []}
        quickTags={quickTags}
        onRoleChange={handleRoleChange}
        onTagsChange={handleTagsChange}
        onFilterClick={handleFilterClick}
        filters={filters}
        onFiltersChange={handleFiltersChange}
      />
      <div className="w-full">
        <MeetList
          items={allMeetItems}
          hasNextPage={!!hasNextPage}
          isLoading={isLoading || isFetchingNextPage}
          fetchNextPage={fetchNextPage}
          onCharacterClick={handleCharacterClick}
        />
      </div>
    </div>
  );
}
 
export default MoreType;