import { useState, useEffect, useMemo } from "react";
import { CardDataState, CardState, InfiniteCardProps } from "./type";

const getInitialDataState = (props: InfiniteCardProps): CardState => {
  return {
    sort: props.sortConfig?.defaultSortFields ?? [],
    filter: { logic: "and", filters: [] },
    group: props.groupConfig?.defaultGroupFields ?? [],
    skip: props.paginationConfig?.defaultPagination?.skip ?? 0,
    take: props.paginationConfig?.defaultPagination?.take ?? -1,
  };
};

const useCardState = (props: InfiniteCardProps) => {
  const [baseData, setBaseData] = useState<CardDataState>({
    records: [],
    total: 0,
  });

  const [gridState, setGridState] = useState<CardState>(
    getInitialDataState(props)
  );

  useEffect(() => {
    let uiElementGroupData = props?.uiElementGroupData ?? {};

    uiElementGroupData = {
      ...uiElementGroupData,
      dataFilters: {
        ...(uiElementGroupData?.dataFilters ?? {}),
        processing: false,
        defaultFilterCriteria: props.filterConfig?.defaultFilterCriteria,
        defaultSkip: props.paginationConfig?.defaultPagination?.skip ?? 0,
        defaultTake: props.paginationConfig?.defaultPagination?.take ?? -1,
        defaultSort: props.sortConfig?.defaultSortFields ?? [],
        defaultGroup: props.groupConfig?.defaultGroupFields ?? [],
      },
    };
    props?.onModelUpdate?.(null, props.screenDataField || "", {
      records: [],
      total: 0,
    });

    setTimeout(() => {
      props?.onModelUpdate?.(
        null,
        props?.config?.uiElementGroupId,
        uiElementGroupData
      );
    }, 300);
  }, []);

  useEffect(() => {
    setBaseData({
      records: props.value?.records ?? [],
      total: props.value?.total ?? props.value?.records?.length ?? 0,
    });
  }, [props.value]);

  return {
    baseData,
    dataState: gridState,
    setDataState: setGridState,
  };
};

export default useCardState;
