import { Suspense, useEffect, useRef } from 'react';
import { FiFileText, FiRefreshCw } from 'react-icons/fi';
import { useToggle } from '@react-hookz/web';
import { useDataContext } from '../providers/DataProvider';
import EntityList from './EntityList';
import styles from './Explorer.module.css';
import { EXPLORER_ID, focusLast, focusNext } from './utils';
import { indexOf } from 'lodash';
import  HsdsProvider   from '../providers/hsds/HsdsProvider'; 
import type { DataProviderApi } from '../../src/providers/api';

interface Props {
  selectedPath: string;
  fileIndex:number;
  onSelect: (path: string) => void;
  onSelectFile: (path: string) => void;
  onSelectFileIndex: (index:number) => void;
}


function SingleFile(props: Props) {
  const { selectedPath,fileIndex, onSelect, onSelectFile,onSelectFileIndex } = props;
  const { filename,filepath } = useDataContext();
  console.log(filename)

  const ref = useRef<HTMLDivElement>(null);
  const btnRef = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    btnRef.current?.focus();
  }, [btnRef]);

  return (
    <div ref={ref} className={styles.explorer}  role="tree" id={EXPLORER_ID}>
      <button
        ref={btnRef}
        className={styles.fileBtn}
        type="button"
        role="treeitem"
        aria-selected={selectedPath === filepath}
        data-path="/"
        onClick={() =>
            {onSelect('/'),onSelectFile(filepath),onSelectFileIndex(fileIndex)}}
        onKeyDown={(e) => {
          if (e.key === 'End') {
            focusLast(e);
            return;
          }

          if (e.key === 'ArrowDown' || e.key === 'ArrowRight') {
            focusNext(e);
          }
        }}
       
      >
        <FiFileText className={styles.fileIcon} />
        <span className={styles.name}>{filename}</span>
      </button>

      <Suspense
        fallback={
          <FiRefreshCw
            className={styles.spinner}
            aria-label="Loading root metadata..."
          />
        }
      >
        <EntityList
          level={0}
          parentPath="/"
          selectedPath={selectedPath}
          fileIndex={fileIndex}
          onSelect={onSelect}
          onSelectFile={onSelectFile}
          onSelectFileIndex={onSelectFileIndex}
       
        />
      </Suspense>
    </div>
  );
}

export default SingleFile;



 