import type { SlotsType } from 'vue';

import type { CardListProps, ExtendedCardListApi } from './types';

import { defineComponent, h, onBeforeUnmount } from 'vue';

import { useStore } from '@vben-core/shared/store';

import { CardListApiInstance } from './api';
import CardList from './card-list.vue';

export function useCardList<T extends Record<string, any> = any>(options: CardListProps<T>) {
  const api = new CardListApiInstance<T>(options);
  const extendedApi = api as any as ExtendedCardListApi<T>;

  extendedApi.useStore = (selector) => {
    return useStore(api.store, selector);
  };

  const CardListComponent = defineComponent(
    (props: CardListProps<T>, { attrs, slots }) => {
      onBeforeUnmount(() => {
        api.unmount();
      });

      api.setState({ ...props, ...attrs });
      return () => h(CardList, { ...props, ...attrs, api: extendedApi }, slots);
    },
    {
      name: 'CardList',
      inheritAttrs: false,
      slots: Object as SlotsType<{
        [key: string]: { field: string; index: number; row: T; value: any };
      }>,
    },
  );

  return [CardListComponent, extendedApi] as const;
}

export type useCardList = typeof useCardList;
