import React, { memo, useEffect } from "react";
import { proxy, useSnapshot } from "valtio";

import { pullDecks } from "@/api";
import { MdproDeck } from "@/api/mdproDeck/schema";
import { IconFont } from "@/ui/Shared";

import styles from "./index.module.scss";

interface Props {
  query: string;
  page: number;
  decks: MdproDeck[];
  pages: number;
}

// TODO: useConfig
const PAGE_SIZE = 20;

const store = proxy<Props>({ query: "", page: 1, decks: [], pages: 0 });

export const DeckResults: React.FC = memo(() => {
  const snap = useSnapshot(store);

  useEffect(() => {
    const update = async () => {
      const resp = await pullDecks({
        page: snap.page,
        size: PAGE_SIZE,
        keyWord: snap.query !== "" ? snap.query : undefined,
        sortLike: true,
      });

      if (resp?.data) {
        const { pages, records: newDecks } = resp.data;
        store.pages = pages;
        store.decks = newDecks;
      } else {
        store.decks = [];
      }
    };

    update();
  }, [snap.query, snap.page]);

  return (
    <>
      {snap.decks.length ? (
        <div></div>
      ) : (
        <div className={styles.empty}>
          <IconFont type="icon-empty" size={40} />
          <div>找不到相应卡组</div>
        </div>
      )}
    </>
  );
});

export const freshMdrpoDecks = (query: string) => (store.query = query);
