Hi, I am working on a system for the interaction of various neural networks (text, image recognition, sound generation, etc.) I want my system to allow neural networks to interact with each other, which in turn would provide a unique user experience. To do this, I started writing the skeleton of the site. Now I have a chat layout, let's make the following changes to the code. I would like the chat folders to be displayed as a tree structure. I'm attaching the code of several files, if you need any more, tell me about it
chat.tsx
import React, { useState, useEffect, useRef } from 'react';
import {
  Box,
  Paper,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Button,
  List,
  ListItem,
  ListItemText,
  ListItemIcon,
  Collapse,
  IconButton,
  TextField,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import ExpandLess from '@mui/icons-material/ExpandLess';
import ExpandMore from '@mui/icons-material/ExpandMore';
import FolderIcon from '@mui/icons-material/Folder';
import DescriptionIcon from '@mui/icons-material/Description';
import axios from 'axios';
import { Folder, Message } from './types';
import ChatList from './ChatList.tsx';
import FolderList from './FolderList.tsx';
import MessageList from './MessageList.tsx';
import NewChatForm from './NewChatForm.tsx';
import NewFolderForm from './NewFolderForm.tsx';
import MessageInput from './MessageInput.tsx';
import RightPanel from './RightPanel.tsx';

const ChatComponent: React.FC = () => {
  const [folders, setFolders] = useState<Folder[]>([{ name: 'Folder 1', chats: { 'Chat 1': [] } }]);
  const [selectedFolder, setSelectedFolder] = useState<string>('Folder 1');
  const [selectedChat, setSelectedChat] = useState<string>('Chat 1');
  const [isRightPanelOpen, setIsRightPanelOpen] = useState(false);
  const [deleteConfirmationOpen, setDeleteConfirmationOpen] = useState(false);
  const [chatToDelete, setChatToDelete] = useState<string | null>(null);
  const [folderToDelete, setFolderToDelete] = useState<string | null>(null);

  const chatContainerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setFolders([{ name: 'Folder 1', chats: { 'Chat 1': [] } }]);
    setSelectedFolder('Folder 1');
    setSelectedChat('Chat 1');
  }, []);

  useEffect(() => {
    // Scroll to the bottom of the chat container when new messages are added
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  }, [folders, selectedFolder, selectedChat]);

  const sendMessage = async (text: string, file?: File) => {
    const newMessage: Message = {
      position: 'right',
      type: file ? getFileType(file) : 'text',
      content: file ? URL.createObjectURL(file) : text,
      text: text,
      fileName: file ? file.name : undefined
    };

    const newMessages = [...(folders.find(f => f.name === selectedFolder)?.chats[selectedChat] || []), newMessage];
    const updatedFolders = folders.map(f => f.name === selectedFolder ? { ...f, chats: { ...f.chats, [selectedChat]: newMessages } } : f);
    setFolders(updatedFolders);

    try {
      const formData = new FormData();
      formData.append('text', text);
      if (file) formData.append('file', file);

      const response = await axios.post('/api/chat', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      const aiResponse: Message = {
        position: 'left',
        type: 'text',
        content: response.data.text,
      };

      const updatedMessages = [...newMessages, aiResponse];
      const finalFolders = folders.map(f => f.name === selectedFolder ? { ...f, chats: { ...f.chats, [selectedChat]: updatedMessages } } : f);
      setFolders(finalFolders);
    } catch (error) {
      console.error('Error sending message:', error);
    }
  };

  const getFileType = (file: File): 'file' | 'image' | 'audio' | 'video' => {
    if (file.type.startsWith('image/')) return 'image';
    if (file.type.startsWith('audio/')) return 'audio';
    if (file.type.startsWith('video/')) return 'video';
    return 'file';
  };

  const handleChatSelect = (chatName: string) => {
    setSelectedChat(chatName);
  };

  const handleFolderSelect = (folderName: string) => {
    setSelectedFolder(folderName);
    setSelectedChat(Object.keys(folders.find(f => f.name === folderName)?.chats || {})[0]);
  };

  const handleCreateChat = (chatName: string) => {
    const updatedFolders = folders.map(f => f.name === selectedFolder ? { ...f, chats: { ...f.chats, [chatName]: [] } } : f);
    setFolders(updatedFolders);
  };

  const handleCreateFolder = (folderName: string) => {
    setFolders([...folders, { name: folderName, chats: {} }]);
  };

  const handleRenameChat = (newName: string) => {
    const updatedFolders = folders.map(f =>
      f.name === selectedFolder
        ? { ...f, chats: { ...f.chats, [newName]: f.chats[selectedChat] } }
        : f
    );
    setFolders(updatedFolders);
    setSelectedChat(newName);
  };

  const handleRenameFolder = (newName: string) => {
    const updatedFolders = folders.map(f =>
      f.name === selectedFolder ? { ...f, name: newName } : f
    );
    setFolders(updatedFolders);
    setSelectedFolder(newName);
  };

  const handleDeleteChat = (chatName: string) => {
    setChatToDelete(chatName);
    setDeleteConfirmationOpen(true);
  };

  const handleDeleteFolder = (folderName: string) => {
    setFolderToDelete(folderName);
    setDeleteConfirmationOpen(true);
  };

  const handleConfirmDelete = () => {
    if (chatToDelete) {
      const updatedFolders = folders.map(f => f.name === selectedFolder ? {
        ...f,
        chats: Object.fromEntries(Object.entries(f.chats).filter(([key]) => key !== chatToDelete))
      } : f);
      setFolders(updatedFolders);
      setSelectedChat(Object.keys(folders.find(f => f.name === selectedFolder)?.chats || {})[0]);
      setChatToDelete(null);
    } else if (folderToDelete) {
      const updatedFolders = folders.filter(f => f.name !== folderToDelete);
      setFolders(updatedFolders);
      setSelectedFolder(updatedFolders[0]?.name || '');
      setSelectedChat(Object.keys(updatedFolders[0]?.chats || {})[0]);
      setFolderToDelete(null);
    }
    setDeleteConfirmationOpen(false);
  };

  const handleCancelDelete = () => {
    setChatToDelete(null);
    setFolderToDelete(null);
    setDeleteConfirmationOpen(false);
  };

  return (
    <Box sx={{ width: '100%', height: '100vh', display: 'flex', flexDirection: 'row' }}>
      {/* Left Panel: Folder and Chat List */}
      <Paper elevation={3} sx={{ width: '20%', height: '100%', overflowY: 'auto', padding: '10px', borderRadius: '10px' }}>
        <NewFolderForm onCreateFolder={handleCreateFolder} />
        <FolderList
          folders={folders.map(f => f.name)}
          selectedFolder={selectedFolder}
          onFolderSelect={handleFolderSelect}
          onRenameFolder={handleRenameFolder}
          onDeleteFolder={handleDeleteFolder}
        />
        <NewChatForm onCreateChat={handleCreateChat} />
        <ChatList
          chats={Object.keys(folders.find(f => f.name === selectedFolder)?.chats || {})}
          selectedChat={selectedChat}
          onChatSelect={handleChatSelect}
          onRenameChat={handleRenameChat}
          onDeleteChat={handleDeleteChat}
        />
      </Paper>

      {/* Center Panel: Chat Interface */}
      <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', marginLeft: '10px', marginRight: '10px' }}>
        <Paper
          elevation={3}
          sx={{
            flex: 1,
            overflowY: 'auto',
            padding: '10px',
            borderRadius: '10px',
            maxHeight: 'calc(100vh - 200px)',
          }}
          ref={chatContainerRef}
        >
          <MessageList messages={folders.find(f => f.name === selectedFolder)?.chats[selectedChat] || []} />
        </Paper>
        <MessageInput onSendMessage={sendMessage} />
      </Box>

      {/* Right Panel: Sliding Column */}
      <RightPanel isOpen={isRightPanelOpen} onToggle={() => setIsRightPanelOpen(!isRightPanelOpen)} />

      {/* Delete Confirmation Dialog */}
      <Dialog
        open={deleteConfirmationOpen}
        onClose={handleCancelDelete}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogTitle id="alert-dialog-title">{"Confirm Delete"}</DialogTitle>
        <DialogContent>
          <DialogContentText id="alert-dialog-description">
            Are you sure you want to delete this {chatToDelete ? 'chat' : 'folder'}?
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCancelDelete} color="primary">
            No
          </Button>
          <Button onClick={handleConfirmDelete} color="primary" autoFocus>
            Yes
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default ChatComponent;
chatlist.tsx
import React, { useState } from 'react';
import { List, ListItem, ListItemText, IconButton, Input } from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';

interface ChatListProps {
  chats: string[];
  selectedChat: string;
  onChatSelect: (chatName: string) => void;
  onRenameChat: (chatName: string) => void;
  onDeleteChat: (chatName: string) => void;
}

const ChatList: React.FC<ChatListProps> = ({ chats, selectedChat, onChatSelect, onRenameChat, onDeleteChat }) => {
  const [editingChat, setEditingChat] = useState<string | null>(null);
  const [editedChatName, setEditedChatName] = useState<string>('');

  const handleRenameChat = (chatName: string) => {
    setEditingChat(chatName);
    setEditedChatName(chatName);
  };

  const handleSaveRenameChat = () => {
    if (editingChat && editedChatName) {
      onRenameChat(editedChatName);
      setEditingChat(null);
    }
  };

  return (
    <List>
      {chats.map((chatName, index) => (
        <ListItem
          key={index}
          button
          onClick={() => onChatSelect(chatName)}
          sx={{
            backgroundColor: selectedChat === chatName ? '#1976d2' : 'transparent',
            color: selectedChat === chatName ? 'white' : 'black',
            borderRadius: '10px',
            marginBottom: '5px',
            boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
            '&:hover': {
              boxShadow: 'inset 0 0 0 2px #1976d2',
            },
          }}
        >
          {editingChat === chatName ? (
            <Input
              value={editedChatName}
              onChange={(e) => setEditedChatName(e.target.value)}
              onBlur={handleSaveRenameChat}
              autoFocus
              fullWidth
            />
          ) : (
            <ListItemText primary={chatName} />
          )}
          <IconButton color="inherit" onClick={() => handleRenameChat(chatName)}>
            <EditIcon sx={{ color: selectedChat === chatName ? 'white' : 'black' }} />
          </IconButton>
          <IconButton color="inherit" onClick={() => onDeleteChat(chatName)}>
            <DeleteIcon sx={{ color: selectedChat === chatName ? 'white' : 'black' }} />
          </IconButton>
        </ListItem>
      ))}
    </List>
  );
};

export default ChatList;
folderlist.tsx
import React, { useState } from 'react';
import { List, ListItem, ListItemText, IconButton, Input } from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';

interface FolderListProps {
  folders: string[];
  selectedFolder: string;
  onFolderSelect: (folderName: string) => void;
  onRenameFolder: (folderName: string) => void;
  onDeleteFolder: (folderName: string) => void;
}

const FolderList: React.FC<FolderListProps> = ({ folders, selectedFolder, onFolderSelect, onRenameFolder, onDeleteFolder }) => {
  const [editingFolder, setEditingFolder] = useState<string | null>(null);
  const [editedFolderName, setEditedFolderName] = useState<string>('');

  const handleRenameFolder = (folderName: string) => {
    setEditingFolder(folderName);
    setEditedFolderName(folderName);
  };

  const handleSaveRenameFolder = () => {
    if (editingFolder && editedFolderName) {
      onRenameFolder(editedFolderName);
      setEditingFolder(null);
    }
  };

  return (
    <List>
      {folders.map((folderName, index) => (
        <ListItem
          key={index}
          button
          onClick={() => onFolderSelect(folderName)}
          sx={{
            backgroundColor: selectedFolder === folderName ? '#1976d2' : 'transparent',
            color: selectedFolder === folderName ? 'white' : 'black',
            borderRadius: '10px',
            marginBottom: '5px',
            boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
            '&:hover': {
              boxShadow: 'inset 0 0 0 2px #1976d2',
            },
          }}
        >
          {editingFolder === folderName ? (
            <Input
              value={editedFolderName}
              onChange={(e) => setEditedFolderName(e.target.value)}
              onBlur={handleSaveRenameFolder}
              autoFocus
              fullWidth
            />
          ) : (
            <ListItemText primary={folderName} />
          )}
          <IconButton color="inherit" onClick={() => handleRenameFolder(folderName)}>
            <EditIcon sx={{ color: selectedFolder === folderName ? 'white' : 'black' }} />
          </IconButton>
          <IconButton color="inherit" onClick={() => onDeleteFolder(folderName)}>
            <DeleteIcon sx={{ color: selectedFolder === folderName ? 'white' : 'black' }} />
          </IconButton>
        </ListItem>
      ))}
    </List>
  );
};

export default FolderList;
newchatform.tsx
import React, { useState } from 'react';
import { ListItem, TextField, IconButton } from '@mui/material';
import AddIcon from '@mui/icons-material/Add';

interface NewChatFormProps {
  onCreateChat: (chatName: string) => void;
}

const NewChatForm: React.FC<NewChatFormProps> = ({ onCreateChat }) => {
  const [newChatName, setNewChatName] = useState('');

  const handleCreateChat = () => {
    if (newChatName) {
      onCreateChat(newChatName);
      setNewChatName('');
    }
  };

  return (
    <ListItem sx={{ borderRadius: '10px' }}>
      <TextField
        placeholder="New chat name"
        value={newChatName}
        onChange={(e) => setNewChatName(e.target.value)}
        fullWidth
        sx={{ width: '100%' }}
      />
      <IconButton color="primary" onClick={handleCreateChat}>
        <AddIcon />
      </IconButton>
    </ListItem>
  );
};

export default NewChatForm;
newfolderform.tsx
import React, { useState } from 'react';
import { ListItem, TextField, IconButton } from '@mui/material';
import AddIcon from '@mui/icons-material/Add';

interface NewFolderFormProps {
  onCreateFolder: (folderName: string) => void;
}

const NewFolderForm: React.FC<NewFolderFormProps> = ({ onCreateFolder }) => {
  const [newFolderName, setNewFolderName] = useState('');

  const handleCreateFolder = () => {
    if (newFolderName) {
      onCreateFolder(newFolderName);
      setNewFolderName('');
    }
  };

  return (
    <ListItem sx={{ borderRadius: '10px' }}>
      <TextField
        placeholder="New folder name"
        value={newFolderName}
        onChange={(e) => setNewFolderName(e.target.value)}
        fullWidth
        sx={{ width: '100%' }}
      />
      <IconButton color="primary" onClick={handleCreateFolder}>
        <AddIcon />
      </IconButton>
    </ListItem>
  );
};

export default NewFolderForm;