import { useMemo } from 'react';

import type { CodeWalkthroughFile } from '@redocly/config';
import type { IconProps } from '@redocly/theme/icons/types';

import {
  getFileIconByExt,
  removeLeadingSlash,
  findClosestCommonDirectory,
} from '@redocly/theme/core/utils';

export type RenderableFile = CodeWalkthroughFile & {
  FileIcon: React.FunctionComponent<IconProps>;
  parentFolder: string;
  isNameDuplicate: boolean;
  inRootDir: boolean;
};

export function useRenderableFiles(files: CodeWalkthroughFile[]): RenderableFile[] {
  return useMemo(
    function () {
      const filePaths = files.map(({ path }) => path);
      const rootDir = findClosestCommonDirectory(filePaths);

      const renderableFiles = files.map((file) => {
        const FileIcon = getFileTypeIcon(file.basename);
        const parentFolder = file.path.split('/').slice(-2, -1)[0];
        const isNameDuplicate = files.some(
          (_file) => file.basename === _file.basename && file.path !== _file.path,
        );
        const inRootDir = file.path === `${removeLeadingSlash(rootDir)}/${file.basename}`;

        return {
          ...file,
          FileIcon,
          inRootDir,
          parentFolder,
          isNameDuplicate,
        };
      });

      return renderableFiles;
    },
    [files],
  );
}

function getFileTypeIcon(basename: string) {
  const extension = basename.split('.').pop()?.toLowerCase() || '';
  return getFileIconByExt(extension);
}
