'use client';

import { Grid } from '@lobehub/ui';
import { Empty } from 'antd';
import { memo, useMemo, useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import urlJoin from 'url-join';
import { useRouter } from 'next/navigation';
import { DiscoverPlugintem } 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/request';
import { useUserStore } from '@/store/user';
export interface ListProps {
  category?: string;
  items: DiscoverPlugintem[];
  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())
  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/appaiplugin/getAllAiPlugin",
        })
        setStData(res?.data.map((item)=> {
          item.classify = 'collect';
          return item
        }))
      } else {
        const res = await request({
          method: "get",
          params: {
            userid: userId
          },
          url: "/flxai/api/robot/appaiplugin/getAllAiPlugin",
        })
        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('chajian999999999999999--------------',stData)

  const handleClickCard = (item) => {
    console.log(item)
    router.push(urlJoin('/discover/plugin/', 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) => (
            <div onClick={() => handleClickCard(item)} key={item.identifier}>
              <Card
                showCategory
                variant={'compact'}
                {...item}
                key={item.identifier}
              />
            </div>
          )}
          style={{
            minHeight: '75vh',
          }}
        />
      </>
    );
  }

  return (
    <div style={{ marginLeft: '200px'}}>
      {category === "collect"?(
        <>
          <Title tag={all.length}>收藏列表</Title>
          <Grid maxItemWidth={280} rows={4}>
            {all?.map((item,index) => (
                // <div onClick={() => handleClickCard(item)}>测试接口</div>
              <div onClick={() => handleClickCard(item)} key={item.identifier}>
                <Card key={item.identifier}  showCategory={!category} {...item} />
              </div>
            ))}
          </Grid>
        </>
      ):(
        <>
          <Title>{t('plugins.recentSubmits')}</Title>
          <Grid maxItemWidth={280} rows={4}>
            {recent?.map((item) => (
              // <Card key={item.identifier} onClick={() => handleClickCard(item)} showCategory={!category} {...item} />
              <div onClick={() => handleClickCard(item)} key={item.identifier}>
                <Card key={item.identifier}  showCategory={!category} {...item} />
              </div>
            ))}
          </Grid>
          {last && last?.length > 0 && (
            <>
              <Title tag={last.length}>{t('plugins.list')}</Title>
              <VirtuosoGridList
                data={last}
                initialItemCount={12}
                itemContent={(_, item) => (
                  // <Card key={item.identifier} onClick={() => handleClickCard(item)} showCategory={!category} variant={'compact'} {...item} />
                  <div onClick={() => handleClickCard(item)} key={item.identifier}>
                    <Card key={item.identifier}  showCategory={!category} {...item} />
                  </div>
                )}
                style={{
                  minHeight: '75vh',
                }}
              />
            </>
          )}
        </>
      )}
    </div>
  );
});

export default List;
