import { CollectionState, FiltersMap } from '@wix/bex-core';
import { computed, makeObservable, observable } from 'mobx';
import { GridState, ToolbarCollectionState } from '../../state';
import type { Section, RenderSection } from '../CollectionSectionHeader';

export interface SectionRange {
  section: Section;
  range: {
    start: number;
    length: number;
  };
}

export interface GridSectionsStateParams<T, F extends FiltersMap> {
  readonly collection: CollectionState<T, F>;
  readonly toolbar: ToolbarCollectionState<T, F>;
  readonly renderSection?: RenderSection<T>;
  readonly parentState: GridState<T, F>;
}

export class GridSectionsState<T, F extends FiltersMap> {
  renderSection?: RenderSection<T>;
  readonly toolbar;
  readonly collection;
  readonly parentState;

  constructor(params: GridSectionsStateParams<T, F>) {
    this.collection = params.collection;
    this.toolbar = params.toolbar;
    this.renderSection = params.renderSection;
    this.parentState = params.parentState;

    makeObservable(this, {
      sections: computed,
      renderSection: observable.ref,
    });
  }

  get sections() {
    const { collection, renderSection } = this;

    if (!renderSection) {
      return [];
    }

    return Object.values(
      collection.result.items.reduce((acc, item, index) => {
        const section = renderSection(item);
        if (!acc[section.id]) {
          acc[section.id] = {
            section,
            range: {
              start: index,
              length: 0,
            },
          };
        }
        acc[section.id].range.length++;
        return acc;
      }, {} as Record<string, SectionRange>),
    );
  }
}
