import { defineComponent, inject, ref, watch, unref } from "vue";
import { FormConfig, PageSearch } from "../../PageSearch";
import type { Events, Hooks } from "./types";
import { ActionType } from "/@/components/PageContent/src/types";
import {
  ContentConfig,
  PageContent,
  type PageContentInstance
} from "../../PageContent";

const PageContainer = defineComponent({
  name: "PageContainer",
  props: {
    pageName: {
      type: String,
      default: ""
    },
    contentConfig: {
      type: Object as PropType<ContentConfig>
    },
    searchConfig: {
      type: Object as PropType<FormConfig>
    },
    getContentRef: {
      type: Function as PropType<(ref: PageContentInstance) => any>
    },
    hooks: {
      type: Object as PropType<Hooks>,
      default: () => ({})
    },
    events: {
      type: Object as PropType<Events>,
      default: () => ({})
    }
  },
  setup(props, { slots }) {
    const { pageSearchHook } = props.hooks as Hooks;
    const { handleResetClick, handleSearchClick, pageContentRef } =
      pageSearchHook ? pageSearchHook() : ({} as any);

    const innerContentRef = pageContentRef ? pageContentRef : ref(null);

    const { permissions } = inject<AuthProvide>("Auth", {
      permissions: ref([])
    });
    function renderPageContent() {
      const { contentConfig, events } = props;
      const { content: contentEvents = {} } = events as any;
      if (!contentConfig) return;

      return (
        <PageContent
          class="h-full"
          ref={innerContentRef}
          contentConfig={contentConfig}
          powers={permissions.value}
          onPreviewBtnClick={contentEvents.preview}
          onCreateBtnClick={contentEvents.create}
          onUpdateBtnClick={contentEvents.update}
          v-slots={{
            header: () => slots.content_header && slots.content_header()
          }}
        />
      );
    }

    function renderPageSearch() {
      const { searchConfig } = props;
      if (!searchConfig) return null;

      return (
        <PageSearch
          formConfig={searchConfig}
          onResetBtnClick={handleResetClick}
          onSearchBtnClick={handleSearchClick}
        />
      );
    }
    watch(
      () => innerContentRef,
      () => {
        const contentRef = unref(innerContentRef);
        const { getContentRef } = props;
        if (contentRef && getContentRef) getContentRef(contentRef);
      },
      {
        deep: true
      }
    );

    return () => {
      return (
        <div class="w-full h-full">
          {renderPageSearch()}
          {renderPageContent()}
        </div>
      );
    };
  }
});

export default PageContainer;
