import * as React from "react";
import { buildLatestItems } from "./LatestItems.adapter";
import LatestItemsView from "./LatestItems.view";
import { LatestItemsProps } from "./LatestItems.props";

export default function LatestItems(props: LatestItemsProps) {
  const {
    reportData,
    state,
    stateSetters,
    isFetching,
  } = props;

  const { flow, selectedPeriodId, selectedGroupKey } = state;
  const [visibleCount, setVisibleCount] = React.useState(5);

  // Reset count when flow changes to start clean
  React.useEffect(() => {
    setVisibleCount(5);
  }, [flow]);

  const allItems = React.useMemo(() => {
    return buildLatestItems(reportData, selectedPeriodId, selectedGroupKey, flow);
  }, [reportData, selectedPeriodId, selectedGroupKey, flow]);

  const visibleItems = React.useMemo(() => {
    return allItems.slice(0, visibleCount);
  }, [allItems, visibleCount]);

  const canExpand = visibleCount < allItems.length;

  return (
    <LatestItemsView
      {...props}
      items={visibleItems}
      canExpand={canExpand}
      onExpand={() => setVisibleCount((prev) => prev + 5)}
    />
  );
}
