'use client';

import { Grid } from '@lobehub/ui';
import { Empty } from 'antd';
// import Link from 'next/link';
import {memo, useMemo, useEffect, useState} from 'react';
import { useTranslation } from 'react-i18next';
import urlJoin from 'url-join';
import { useRouter } from 'next/navigation';
import { DiscoverAssistantItem } from '@/types/discover';

import SearchResultCount from '../../../components/SearchResultCount';
import Title from '../../../components/Title';
import VirtuosoGridList from '../../../components/VirtuosoGridList';
import Card from './Card';
import request from '@/app/api/request';
import { useUserStore } from '@/store/user';

export interface ListProps {
  category?: string;
  items?: DiscoverAssistantItem[];
  mobile?: boolean;
  searchKeywords?: string;
}
const getUserId = (s: { user?: { id?: any } }) => s.user?.id

const List = memo<ListProps>(({ category, mobile, searchKeywords, items = [] }) => {
  const { t } = useTranslation('discover');
  const router = useRouter()
  const [stData, setStData] = useState(items)
  const recentLength = mobile ? 4 : 8;
  const userId = getUserId(useUserStore.getState())
  // console.log(userId,'zhushou---3837373266262266')
  // console.log('zhushou--------------',items)
  const { all, recent, last } = useMemo(() => {
    return {
      all: stData,
      last: stData.slice(recentLength),
      recent: stData.slice(0, recentLength),
    };
  }, [stData, mobile]);
  useEffect(() => {
    const fetchData = async() => {
      if(category === "collect") {
        const res = await request({
            method: "get",
            params: {
              userid: userId
            },
            url: "/flxai/api/robot/appaiassistant/getAllAiAssistant"
        })
        setStData(res?.data.map((item)=> {
            item.classify = 'collect';
            return item
        }))
      } else {
        const res = await request({
            method: "get",
            params: {
              userid: userId
            },
            url: "/flxai/api/robot/appaiassistant/getAllAiAssistant"
        })
        const array2Object = {};
        res?.data?.forEach((item) => {
          array2Object[item.identifier] = item;
        });
        // console.log('chajian22222222222222222222222222222--------------')
        setStData(stData.map((item)=> {
            const matchingItem = array2Object[item.identifier];
            if (matchingItem) {
              matchingItem.status = '1';
              return matchingItem
            } else {
              item.status = '0';
              return item
            }
        }))
      }
    };
    fetchData();
  }, []); // 空数组[]意味着仅在组件挂载时调用一次
  // console.log(category,recent,last,"92929292")
  const handleClickCard = (item) => {
    console.log(item)
    router.push(urlJoin('/discover/assistant/', item.identifier))
  }

  if (searchKeywords) {
    if (!items || items?.length === 0) return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;
    return (
      <>
        <SearchResultCount count={all.length} keyword={searchKeywords} />
        <VirtuosoGridList
          data={all}
          initialItemCount={24}
          itemContent={(_, item) => (
            // <Link href={urlJoin('/discover/assistant/', item.identifier)} key={item.identifier}>
              <Card onClick={() => handleClickCard(item)} showCategory variant={'compact'} {...item} />
            // </Link>
          )}
          style={{
            minHeight: '75vh',
          }}
        />
      </>
    );
  }

  return (
  <div>
      {category === "collect"?(
        <>
          <Title tag={all.length}>收藏列表</Title>
          <Grid maxItemWidth={280} rows={4}>
            {all.map((item) => (
              // <Link href={urlJoin('/discover/assistant/', item.identifier)} key={item.identifier}>
                <Card key={item.identifier} onClick={() => handleClickCard(item)} showCategory={!category} {...item} />
              // </Link>
            ))}
          </Grid>
        </>
      ):(
        <>
          <Title tag={recent.length}>{t('assistants.recentSubmits')}</Title>
          <Grid maxItemWidth={280} rows={4}>
            {recent.map((item) => (
              // <Link href={urlJoin('/discover/assistant/', item.identifier)} key={item.identifier}>
                <Card key={item.identifier} onClick={() => handleClickCard(item)} showCategory={!category} {...item} />
              // </Link>
            ))}
          </Grid>
          {last && last?.length > 0 && (
            <>
              <Title tag={last.length}>{t('assistants.list')}</Title>
              <VirtuosoGridList
                data={last}
                initialItemCount={12}
                itemContent={(_, item) => (
                  <Card onClick={() => handleClickCard(item)} showCategory={!category} variant={'compact'} {...item} />
                )}
                style={{
                  minHeight: '75vh',
                  overflowY: 'visible'
                }}
              />
            </>
          )}
        </>
      )}
      </div>
  );
});

export default List;
