'use client';

import { Empty } from 'antd';
import { memo, useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import urlJoin from 'url-join';
import { useRouter } from 'next/navigation';
import { DiscoverModelItem } from '@/types/discover';
import { Grid } from '@lobehub/ui';
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?: DiscoverModelItem[];
  mobile?: boolean;
  searchKeywords?: string;
}
const getUserId = (s: { user?: { id?: any } }) => s.user?.id

const List = memo<ListProps>(({ category, searchKeywords, items = [] }) => {
  const { t } = useTranslation('discover');
  const router = useRouter()
  const userId = getUserId(useUserStore.getState())
  const [stData, setStData] = useState(items)

  useEffect(() => {
    const fetchData = async() => {
      if(category === "collect") {
        const res = await request({
          method: "get",
          params: {
            userid: userId
          },
          url: "/flxai/api/robot/appaimodel/getAllAiModel",
        })
        setStData(res?.data.map((item)=> {
          item.classify = 'collect';
          return item
        }))
        // items = res.data;
        // items = items.map((item)=> {
        //     item.classify = 'collect';
        //     return item
        // })
      } else {
        const res = await request({
          method: "get",
          params: {
            userid: userId
          },
          url: "/flxai/api/robot/appaimodel/getAllAiModel",
        })
        const array2Object = {};
        res?.data?.forEach(item => {
          array2Object[item.identifier] = item;
        });
        setStData(stData.map((item)=> {
          const matchingItem = array2Object[item.identifier];
          if (matchingItem) {
            matchingItem.status = '1';
            return matchingItem
          } else {
            item.status = '0';
            return item
          }
        }))
      }
    };
    fetchData();
  }, []); // 空数组[]意味着仅在组件挂载时调用一次

  const handleClickCard = (item) => {
    console.log(item)
    // console.log(router)
    router.push(urlJoin('/discover/model/', item.identifier))
  }

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

  return (
    <div style={{ marginLeft: '200px'}}>
      {category === "collect"?(
        <>
          <Title tag={stData.length}>收藏列表</Title>
          <Grid maxItemWidth={280} rows={4}>
            {stData.map((item) => (
              // <Link href={urlJoin('/discover/assistant/', item.identifier)} key={item.identifier}>
              // <Card style={{boxShadow: "1px 0px 12px 0px rgba(42, 77, 255, 0.19)"}} key={item.identifier} onClick={() => handleClickCard(item)} showCategory={!category} {...item} />
              <div onClick={() => handleClickCard(item)} key={item.identifier}>
                <Card key={item.identifier}  showCategory={!category} {...item} />
              </div>
              // </Link>
            ))}
          </Grid>
        </>
      ):(
        <>
          <Title tag={stData.length}>{t('models.list')}</Title>
          <VirtuosoGridList
            data={stData}
            initialItemCount={24}
            itemContent={(_, item) => (
              // <Link href={urlJoin('/discover/model/', item.identifier)} key={item.identifier}>
              //   <Card style={{boxShadow: "1px 0px 12px 0px rgba(42, 77, 255, 0.19)"}} onClick={() => handleClickCard(item)} key={item.identifier} showCategory={!category} {...item} />
              <div onClick={() => handleClickCard(item)} key={item.identifier}>
                <Card key={item.identifier}  showCategory={!category} {...item} />
              </div>
              // </Link>
            )}
            style={{
              minHeight: '75vh',
            }}
          />
        </>
      )}
    </div>
  );
});

export default List;
