import { FC, useState } from 'react';
import { useQuery } from 'react-query';
import { useNavigate, useParams } from 'react-router-dom';

import HuBreadcrumbs from '@material-hu/components/design-system/Breadcrumbs';

import useGeneralError from 'src/hooks/useGeneralError';
import { filesKeys } from 'src/pages/dashboard/files/queries';
import { getFileTree } from 'src/services/files';
import { FileLeaf } from 'src/types/files';
import { getBreadcrumbs } from 'src/utils/breadcrumbs';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { filesRoutes } from '../routes';

const FolderBreadcrumbs: FC = () => {
  const [folders, setFolders] = useState<FileLeaf[]>([]);
  const navigate = useNavigate();
  const { t } = useLokaliseTranslation('files');
  const { id } = useParams();
  const showGeneralError = useGeneralError();

  useQuery(
    filesKeys.tree(Number(id)),
    () => {
      if (id) {
        return getFileTree(id);
      }
    },
    {
      onSuccess: data => {
        if (data?.data) {
          setFolders(getBreadcrumbs<FileLeaf>(data.data));
        } else {
          setFolders([]);
        }
      },
      onError: err => {
        setFolders([]);
        if (id) {
          showGeneralError(err, t('ERROR_LOADING_BREADCRUMBS'));
        }
      },
    },
  );

  const setRoute = (fileId: number | null) => {
    return fileId
      ? navigate(filesRoutes.detail(fileId))
      : navigate(filesRoutes.files());
  };

  const childs = [{ name: t('HOME'), id: null }, ...folders].map(folder => {
    return {
      title: folder.name,
      onClick: () => setRoute(folder.id),
    };
  });

  return folders.length > 0 ? <HuBreadcrumbs links={childs} /> : null;
};

export default FolderBreadcrumbs;
