import { useEffect, useMemo, useState } from 'react';
import { runInAction } from 'mobx';
import { TableColumn } from '../model';
import { ToolbarCollectionState } from '../state';
import { FiltersMap } from '@wix/bex-core';
import { CustomColumnsElement } from '../components/assertComponentType';
import { usePageContext } from '@wix/bex-core/react';
import { useWixPatternsRouter } from '../providers/WixPatternsRouterProvider';

export interface UseColumnsSyncPropsParams<T, F extends FiltersMap> {
  customColumns?: CustomColumnsElement | null;
  columns: TableColumn<T>[];
  toolbar: ToolbarCollectionState<T, F>;
}

export function useColumnsSyncProps<T, F extends FiltersMap>(
  props: UseColumnsSyncPropsParams<T, F>,
) {
  const { toolbar, customColumns, columns: tableColumns } = props;
  const { modalsContainerRef } = usePageContext();
  const router = useWixPatternsRouter();

  const customColumnsProps = useMemo(() => {
    if (customColumns == null) {
      return null;
    }

    const { onColumnClick } = customColumns.props;

    return {
      onColumnClick,
      dragAndDrop: customColumns.type.dragAndDrop,
    };
  }, [customColumns]);

  useState(() =>
    customColumns?.type.setCustomColumnsState({
      toolbar,
      customColumnsProps: {
        dragAndDrop: customColumnsProps?.dragAndDrop,
      },
      modalsContainerRef,
    }),
  );

  useEffect(() => {
    runInAction(() => {
      toolbar.customColumnsProps = customColumnsProps;
    });
  }, [customColumnsProps]);

  useEffect(() => {
    if (router?.isUsingCache) {
      return;
    }

    toolbar._adjustSortWithNewColumns(tableColumns);
  }, [tableColumns.map((e, i) => e.id ?? i).join('')]);

  useEffect(() => {
    toolbar.setNewColumns(tableColumns);
  }, [
    tableColumns,
    customColumnsProps != null,
    toolbar.customColumnsStateInitialized,
  ]);

  const customColumnsDependency = useMemo(
    () =>
      JSON.stringify(
        tableColumns.map(
          (
            { id, reorderDisabled, hiddenFromCustomColumnsSelection, hideable },
            i,
          ) => ({
            id: id ?? i,
            reorderDisabled,
            hiddenFromCustomColumnsSelection,
            hideable,
          }),
        ),
      ),
    [tableColumns],
  );

  useEffect(() => {
    toolbar._adjustSelectedColumns();
  }, [
    customColumnsDependency,
    customColumnsProps != null,
    toolbar.customColumnsStateInitialized,
  ]);
}
