import { useState } from 'react';
import { useParams } from 'react-router-dom';
import { useQuery, gql } from '@apollo/client';
import {
  CollectionWithChildrenQuery,
  CollectionWithChildrenQueryVariables,
} from 'types/graphql';

import { Box, Spinner } from 'components/common';
import { ErrorBoundary } from 'components/ErrorBoundary';
import { ErrorScreen } from 'components/ErrorScreen';
import { SidebarPanel } from 'components/sidebar/SidebarPanel';
import { DatasetSidebar } from './DatasetSidebar';
import { DatasetContent } from './DatasetContent';

import { PATHS as WORKSPACE } from '../index';

export const collection = gql`
  fragment collection on Collection {
    id
    parentId
    name
    status
    totalProfiles
    dateCreated
  }
`;

const COLLECTION_WITH_CHILDREN = gql`
  query COLLECTION_WITH_CHILDREN($collectionId: ID!) {
    dataset: getCollection(collectionId: $collectionId) {
      ...collection
    }
    children: getCollections(parentId: $collectionId) {
      ...collection
    }
  }
  ${collection}
`;

export const DatasetPage = () => {
  const { [WORKSPACE.collectionId]: collectionId } = useParams();
  const [sidebar, showSidebar] = useState(true);

  const dataset = useQuery<
    CollectionWithChildrenQuery,
    CollectionWithChildrenQueryVariables
  >(COLLECTION_WITH_CHILDREN, {
    variables: { collectionId: collectionId! },
  });

  if (dataset.loading) {
    return <Spinner show />;
  }

  if (dataset.error || dataset.data?.dataset === null) {
    return (
      <ErrorScreen message="Not found">
        Could not find dataset with id <b>{collectionId}</b>
      </ErrorScreen>
    );
  }

  return (
    <Box display="flex" height="100%">
      <SidebarPanel
        width={260}
        side="left"
        show={sidebar}
        onToggle={() => showSidebar((s) => !s)}
      >
        <ErrorBoundary>
          <DatasetSidebar />
        </ErrorBoundary>
      </SidebarPanel>
      <Box position="relative" height="100%" flex="grow" overflow="hidden">
        <ErrorBoundary>
          <DatasetContent />
        </ErrorBoundary>
      </Box>
    </Box>
  );
};
