import type {
  CodeWalkthroughFile,
  CodeWalkthroughStepAttr,
  CodeWalkthroughAttr,
} from '@redocly/config';
import type { WalkthroughStepsState } from '../../types/code-walkthrough';

import {
  useCodeWalkthroughControls,
  type WalkthroughControlsState,
} from './use-code-walkthrough-controls';
import { useCodeWalkthroughSteps } from './use-code-walkthrough-steps';

export type WalkthroughState = {
  stepsState: WalkthroughStepsState;
  controlsState: WalkthroughControlsState;
  downloadAssociatedFiles: CodeWalkthroughFile[];
  files: CodeWalkthroughFile[];
};

type Params = {
  steps: CodeWalkthroughStepAttr[];
  attributes: Omit<CodeWalkthroughAttr, 'steps' | 'preview'>;
  root: React.RefObject<HTMLDivElement | null>;
};

export function useCodeWalkthrough({ steps, attributes, root }: Params): WalkthroughState {
  const { filters, filesets, inputs, toggles, __idx } = attributes;
  /*
    We only enable deep linking for the first CodeWalkthrough, 
    because we don't expect more than one on the same page. 
    Any subsequent walkthroughs have it disabled to avoid 
    collisions/conflicts in the URL.
  */
  const enableDeepLink = __idx === 1;

  const stepsState = useCodeWalkthroughSteps({ steps, enableDeepLink, root });
  const controlsState = useCodeWalkthroughControls(filters, inputs, toggles, enableDeepLink);

  const files: CodeWalkthroughFile[] = filesets
    .filter((fileset) => controlsState.areConditionsMet(fileset))
    .flatMap((fileset) => fileset.files || []);

  const downloadAssociatedFiles: CodeWalkthroughFile[] = filesets
    .filter((fileset) => controlsState.areConditionsMet(fileset))
    .flatMap((fileset) => fileset.downloadAssociatedFiles || []);

  return {
    stepsState,
    controlsState,
    downloadAssociatedFiles,
    files,
  };
}
