import React, { JSX, useCallback } from 'react';
import { Box } from '@mui/material';
import { VectorVisualizer } from 'components/VectorVisualizer';
import { DocumentManager } from 'components/DocumentManager';

const ContentManager = (): JSX.Element => {
  const [filenames, setFilenames] = React.useState<string[]>([]);
  const [editPrompt, setEditPrompt] = React.useState<string>('');
  const [prompt, setPrompt] = React.useState<string>('');
  const [filenameFilter, setFilenameFilter] = React.useState<string[]>([]);

  const setFilter = useCallback(
    (newFilter: string) => {
      if (newFilter !== editPrompt) {
        console.log(`Setting edit prompt to: ${newFilter}`);
        setEditPrompt(newFilter);
      }
      if (newFilter !== prompt) {
        console.log(`Setting prompt to: ${newFilter}`);
        setPrompt(newFilter);
      }
      if (newFilter === '' && filenames.length > 0) {
        console.log('Clearing filename filter');
        setFilenames([]);
      }
    },
    [editPrompt, prompt, filenames.length]
  );

  const onDocumentSelect = useCallback(
    (document: { filename: string } | null): void => {
      if (document) {
        console.log(`Document selected: ${document.filename}`);
        setFilenameFilter([document.filename]);
      } else if (filenames.length > 0) {
        console.log('No document selected, clearing filename filter');
        setFilenameFilter([]);
      }
    },
    [setFilenameFilter, filenames]
  );

  return (
    <Box
      sx={{
        display: 'flex',
        width: '100%',
        flexDirection: 'column',
        position: 'relative',
        overflow: 'hidden',
      }}
    >
      <VectorVisualizer
        filenameFilter={filenameFilter}
        query={editPrompt}
        setQuery={(newPrompt: string) => {
          editPrompt !== newPrompt && setEditPrompt(newPrompt);
        }}
        onQueryResult={(newPrompt: string, newFilenames: string[]) => {
          if (newPrompt !== prompt) {
            console.log(`Setting prompt to: ${newPrompt}`);
            setPrompt(newPrompt);
          }
          let update = filenames.length !== newFilenames.length;
          if (!update) {
            for (let i = 0; i < filenames.length; i++) {
              if (filenames[i] !== newFilenames[i]) {
                update = true;
                break;
              }
            }
          }
          if (update) {
            console.log(`Updating filenames from ${filenames} to ${newFilenames}`);
            setFilenames(newFilenames);
          }
        }}
      />
      <DocumentManager
        {...{
          onDocumentSelect,
          filter: prompt,
          setFilter,
          filenames,
        }}
      />
    </Box>
  );
};

export { ContentManager };
