import { FiltersMap } from '@wix/bex-core';
import { PickerStandaloneState } from '../../state';
import {
  PickerStandaloneLayout,
  PickerStandaloneLayoutProps,
} from '../PickerStandaloneLayout';
import { Picker, PickerProps } from '../Picker';
import React, { ReactElement, useEffect, useState } from 'react';
import { SelectorListContentProps, TextButtonProps } from '@wix/design-system';
import { Splash } from '../Splash';
import { CollectionProvider } from '../CollectionContext';
import { PickerListItemProps } from '../PickerListItemProps';
import { PickerListContent } from '../PickerListContent';
import { PickerStandaloneTableListItem } from './PickerStandaloneTableListItem';
import { observer } from 'mobx-react-lite';
import { MultiCollectionSupportProvider } from '../MultiCollectionSupportProvider';

export interface PickerStandaloneProps<T, F extends FiltersMap>
  extends Partial<PickerStandaloneLayoutProps<T, F>> {
  dataHook?: string;

  /**
   * A picker standalone state instance created with [`usePickerStandalone`](./?path=/story/base-components-collections-picker-hooks--usepickerstandalone)
   */
  state: PickerStandaloneState<T, F>;

  /**
   * A function that renders an item row in the `SelectorList`
   */
  renderItem?: (
    item: T,
    index: number,
    options: { isMobileView?: boolean },
  ) => Partial<PickerListItemProps>;

  /**
   * A render function to be rendered when there're no items to show in the table.<br>
   * You can use the built in [`<CollectionEmptyState />`](./?path=/story/features-display-empty-states--collectionemptystate).<br>
   * The function accepts the following parameters
   *   * `hasAvailableItems`: Indicates whether other items might have been shown using other filtering / search
   *   * `query`: An instance of [`ComputedQuery`](./?path=/story/common-types--computedquery) that represents the query that resulted with an empty state
   */
  renderEmptyState?: PickerProps<T, F>['renderEmptyState'];

  renderError: PickerProps<T, F>['renderError'];

  /** Picker title if not provided via URL query parameter */
  defaultTitle?: string;

  /** Picker subtitle if not provided via URL query parameter */
  defaultSubtitle?: string;

  /** The text for the item primary button, if not provided via URL query parameter */
  defaultPrimaryButtonText?: string;

  /** Limits the number of lines for the title */
  titleMaxLines?: number;

  /** Hides the search input of the picker */
  hideSearch?: boolean;

  /**
   * Additional props to pass to [SelectorList](https://www.docs.wixdesignsystem.com/?path=/story/components-lists--selectorlist), i.e `imageSize`, `imageShape` etc.
   */
  selectorListProps?: Partial<SelectorListContentProps>;

  /**
   * The width of the primary action item.
   * can be fixed or using [minmax](https://developer.mozilla.org/en-US/docs/Web/CSS/minmax())
   */
  primaryActionWidth?: string;

  /**
   *  Adds side action TextButton to the footer, with Add icon. Only `TextButton` React element is supported.
   */
  createNewAction?: ReactElement<TextButtonProps>;

  minContentHeight?: number | string;
  /**
   * Height for mobile layout container
   * @default 100vh
   */
  mobileHeight?: number | string;
}

export function _PickerStandalone<T, F extends FiltersMap = FiltersMap>(
  props: PickerStandaloneProps<T, F>,
) {
  const {
    state,
    renderItem,
    renderEmptyState,
    renderError,
    selectorListProps,
    dataHook,
    height,
    mobileHeight,
    minContentHeight,
    primaryActionWidth,
    defaultPrimaryButtonText,
    ...rest
  } = props;

  const { picker, initTask, isMobileView } = state;

  const { collection } = picker;

  state._hasCreateNewAction = props.createNewAction != null;

  useState(() => {
    if (minContentHeight != null) {
      picker.minContentHeight = minContentHeight;
    }
  });

  useEffect(() => {
    return state.init();
  }, []);

  const { splashProps } = isMobileView
    ? {
        splashProps: {
          height: mobileHeight,
        },
      }
    : {
        splashProps: {
          paddingTop: 'SP8',
          paddingBottom: 'SP8',
          height,
        },
      };

  return (
    <CollectionProvider value={collection}>
      <MultiCollectionSupportProvider value={state.picker.multi}>
        <div data-patterns>
          <Splash
            renderError={renderError}
            dataHook={dataHook}
            state={initTask}
            {...splashProps}
          >
            <PickerStandaloneLayout
              renderError={renderError}
              state={state}
              {...rest}
            >
              <Picker
                dataHook="picker"
                state={picker}
                renderEmptyState={renderEmptyState}
                renderError={renderError}
              >
                <PickerListContent
                  {...selectorListProps}
                  state={picker}
                  spacing={94}
                  renderItem={(keyedItem, index) => (
                    <PickerStandaloneTableListItem
                      {...renderItem?.(keyedItem.item, index, { isMobileView })}
                      defaultPrimaryButtonText={defaultPrimaryButtonText}
                      state={state}
                      primaryActionWidth={primaryActionWidth}
                      keyedItem={keyedItem}
                    />
                  )}
                />
              </Picker>
            </PickerStandaloneLayout>
          </Splash>
        </div>
      </MultiCollectionSupportProvider>
    </CollectionProvider>
  );
}

export const PickerStandalone = observer(_PickerStandalone);
