import { Card, CardProps, LiveRegion } from '@wix/design-system';
import React, { ReactElement, ReactNode } from 'react';
import { observer } from 'mobx-react-lite';
import { FiltersMap } from '@wix/bex-core';
import { ToolbarCollectionState } from '../../state';
import { CollectionProvider } from '../CollectionContext';
import { MessageActionModal } from '../ActionModal';
import { ToolbarCollectionProvider } from '../ToolbarCollectionContext';
import { NavigationModal } from '../NavigationModal';
import { WixPatternsModalsContainer } from '../WixPatternsModalsContainer';
import { usePageContext } from '../../providers';
import { MultiCollectionSupportProvider } from '../MultiCollectionSupportProvider';
import { classes, st } from '../common.st.css.js';
import { ErrorState } from '../ErrorState';
import type { TagsElement } from '../Tags';
import { WixPatternsPanelModalsContainer } from '../WixPatternsPanelModalsContainer';
import { useWixPatternsContainer } from '@wix/bex-core/react';

export interface CollectionCardProps<T, F extends FiltersMap>
  extends CardProps {
  state: ToolbarCollectionState<T, F>;
  children?: ReactNode | ReactNode[];
  errorState?:
    | false
    | ((
        err: unknown,
        params: {
          isOnline: boolean;
          retry: () => void;
        },
      ) => ReactElement);
  tags?: TagsElement<T, F>;
}

function _CollectionCard<T, F extends FiltersMap>({
  state,
  errorState,
  children,
  tags,
  ...rest
}: CollectionCardProps<T, F>) {
  const page = usePageContext();

  const { isPanelLayout, useRelativeSidePanel } = useWixPatternsContainer();

  const { modalsContainerRef, stackingRootRef } = page;

  const {
    collection,
    initTask,
    bulk,
    AddApplyFiltersButton,
    collectionFieldsSource,
    tagsCollectionState,
  } = state;
  const { modals } = bulk;

  const { actionModal } = modals;

  const { status: initTaskStatus } = initTask;

  let child: ReactNode;

  if (initTaskStatus.isError && errorState !== false) {
    child = (
      <ErrorState
        errorStatus={initTaskStatus}
        errorState={errorState}
        dataHook="collection-card-error-state"
        state={state}
      />
    );
  } else {
    child = children;

    child = (
      <>
        {child}
        {actionModal.value && (
          <MessageActionModal state={actionModal} {...actionModal.value} />
        )}
      </>
    );
  }

  return (
    <ToolbarCollectionProvider value={state}>
      <MultiCollectionSupportProvider value={state.multi}>
        <Card className={st(classes.column, classes.fullHeight)} {...rest}>
          <CollectionProvider value={collection}>{child}</CollectionProvider>
        </Card>

        <NavigationModal />
        {collectionFieldsSource && (
          <collectionFieldsSource.components.FieldManagementModals
            source={collectionFieldsSource}
          />
        )}

        <CollectionProvider value={collection}>{tags}</CollectionProvider>
        {tagsCollectionState && <tagsCollectionState.components.ManageModal />}
        {AddApplyFiltersButton?.DiscardChangesModal && (
          <AddApplyFiltersButton.DiscardChangesModal />
        )}

        <LiveRegion
          dataHook="collection-live-region"
          ref={(ref) => {
            state.liveRegionRef.current = ref;
          }}
        />

        {isPanelLayout ? (
          <WixPatternsPanelModalsContainer state={state.panels} />
        ) : (
          <WixPatternsModalsContainer
            rootRef={stackingRootRef}
            anchorRef={
              useRelativeSidePanel ? stackingRootRef : modalsContainerRef
            }
            state={state.panels}
          />
        )}
      </MultiCollectionSupportProvider>
    </ToolbarCollectionProvider>
  );
}
export const CollectionCard = observer(_CollectionCard);
