Recommedn ways to split this class into several classes to increase readebility: class TableManager:
    """Deals with table operations like creation, deletion, loading, and saving."""

    def __init__(self, app: TableApp):
        self.app = app

    def create_new_table(self):
        """Create a new table."""
        existing_numbers = [
            int(name.split(" ")[1])
            for name in self.app.data_manager.tables_data
            if name.startswith("Table ") and name.split(" ")[1].isdigit()
        ]
        next_number = max(existing_numbers, default=0) + 1
        table_name = f"Table {next_number}"
        self.add_table(table_name)
        self.load_selected_table(table_name)

    def add_table(
        self,
        table_name: str,
        data: list[list[str]] | None = None,
        headers: Optional[list[str]] = None,
    ):
        """Add a new table."""
        if headers:
            self.app.data_manager.headers[table_name] = headers
        else:
            default_headers = [
                "Column 1",
                "Column 2",
                "Column 3",
                "Column 4",
                "Column 5",
            ]
            self.app.data_manager.headers[table_name] = default_headers
        self.app.data_manager.tables_data[table_name] = {
            "headers": self.app.data_manager.headers[table_name],
            "data": data
            or [
                ["" for _ in range(len(self.app.data_manager.headers[table_name]))]
                for _ in range(10)
            ],
        }
        self.app.sidebar.create_table_label(table_name)
        self.app.data_manager.save_data()

    def load_selected_table(self, table_name: str):
        """Display selected table."""
        if self.app.current_sheet:
            self.app.current_sheet.pack_forget()
            self.app.current_sheet.destroy()
            self.app.current_sheet = None
        if self.app.sidebar.selected_table_label:
            try:
                self.app.sidebar.selected_table_label.config(
                    bg=self.app.colors["button"]
                )
            except tk.TclError:
                self.app.sidebar.selected_table_label = None

        if table_name not in self.app.data_manager.tables_data:
            messagebox.showerror("Error", f"Table '{table_name}' does not exist.")
            self.app.current_table_name = None
            self.app.sidebar.selected_table_label = None
            return

        table_info = self.app.data_manager.tables_data[table_name]
        headers = table_info["headers"]
        data = table_info["data"]
        try:
            sheet = Sheet(
                self.app.table_frame,
                data=data,
                show_table=True,
                headers=headers,
                font=self.app.fonts["tksheet"],
                header_font=self.app.fonts["tksheet"],
                auto_resize_columns=True,
            )
            sheet.set_options(
                table_fg=self.app.colors["text"], header_fg=self.app.colors["text"]
            )
            sheet.enable_bindings()
            sheet.extra_bindings(
                [
                    ("end_edit_cell", self.on_cell_edit),
                    ("end_delete_columns", self.on_columns_deleted),
                ]
            )
            sheet.pack(expand=True, fill="both")
            self.app.current_sheet = sheet
            self.app.current_table_name = table_name

            if self.app.header.table_name_label:
                self.app.header.table_name_label.config(text=self.app.current_table_name)
            else:
                self.app.header.table_name_label = tk.Label(
                    self.app.root,
                    text=self.app.current_table_name,
                    bg=self.app.colors["background"],
                    fg=self.app.colors["text"],
                    font=self.app.fonts["header_info"],
                )
                self.app.header.table_name_label.grid(
                    row=0, column=0, padx=(60, 10), pady=(5, 0), sticky="nw"
                )

            label = self.app.sidebar.table_labels.get(table_name)
            if label:
                self.app.sidebar.selected_table_label = label
                try:
                    self.app.sidebar.selected_table_label.config(
                        bg=self.app.colors["button_selected"]
                    )
                except tk.TclError:
                    self.app.sidebar.selected_table_label = None
                    messagebox.showerror(
                        "Error", f"Failed to update the label for '{table_name}'."
                    )
            else:
                self.app.sidebar.selected_table_label = None
                messagebox.showerror("Error", f"Label for '{table_name}' not found.")

            self.app.filter_controls.filter_header_var.set("All")
            self.app.filter_controls.filter_header_dropdown["values"] = ["All"] + headers

            self.app.filter_controls.filter_option_var.set("contains")
            self.app.filter_controls.update_filter_text_state()

            self.app.apply_filter()
        except Exception as e:
            messagebox.showerror(
                "Sheet Error", f"Failed to load table '{table_name}': {e}"
            )
            self.app.current_table_name = None
            self.app.sidebar.selected_table_label = None

    def on_cell_edit(self, event=None):
        """Handle cell edits."""
        if self.app.current_table_name and self.app.current_sheet:
            sheet_data = self.app.current_sheet.get_sheet_data()
            for idx, row in enumerate(sheet_data):
                if idx < len(self.app.displayed_row_indices):
                    data_idx = self.app.displayed_row_indices[idx]
                    self.app.data_manager.tables_data[self.app.current_table_name][
                        "data"
                    ][data_idx] = row
                else:
                    # Handle new rows by appending to the underlying data
                    self.app.data_manager.tables_data[self.app.current_table_name][
                        "data"
                    ].append(row)
            self.app.data_manager.save_data()

    def on_columns_deleted(self, event):
        """Handle column deletion and update filter headers."""
        if not self.app.current_table_name or not self.app.current_sheet:
            return
        new_headers = self.app.current_sheet.headers()
        self.app.data_manager.headers[self.app.current_table_name] = new_headers
        self.app.filter_controls.filter_header_dropdown["values"] = ["All"] + new_headers
        self.app.filter_controls.filter_header_var.set("All")
        self.app.filter_controls.filter_option_var.set("contains")
        self.app.filter_controls.filter_text_var.set("")
        self.app.filter_controls.filter_text_entry.config(state="normal")
        self.app.apply_filter()

    def import_file(self):
        """Import table from file."""
        file_path = filedialog.askopenfilename(
            title="Import File",
            filetypes=[
                ("All Supported Files", "*.json *.csv"),
                ("JSON files", "*.json"),
                ("CSV files", "*.csv"),
            ],
        )
        if not file_path:
            return
        try:
            if file_path.endswith(".csv"):
                with open(file_path, newline="", encoding="utf-8") as csvfile:
                    data = list(csv.reader(csvfile))
            elif file_path.endswith(".json"):
                with open(file_path, "r", encoding="utf-8") as jsonfile:
                    data = json.load(jsonfile)
            else:
                raise ValueError("Unsupported file format.")
            if (
                not data
                or not isinstance(data, list)
                or not all(isinstance(row, list) for row in data)
            ):
                raise ValueError("Invalid data format in the file.")
            headers, table_data = data[0], data[1:]
            self.add_table_from_data(file_path, headers, table_data)
        except Exception as e:
            messagebox.showerror("File Import Error", str(e))

    def add_table_from_data(
        self, file_path: str, headers: list[str], table_data: list[list[str]]
    ):
        """Add a table from file data."""
        table_name = Path(file_path).stem
        table_name = self.ensure_unique_table_name(table_name)
        self.add_table(table_name, data=table_data, headers=headers)
        self.load_selected_table(table_name)
        self.app.data_manager.save_data()

    def ensure_unique_table_name(self, table_name: str) -> str:
        """Ensure table name is unique."""
        original_name = table_name
        counter = 1
        while table_name in self.app.data_manager.tables_data:
            table_name = f"{original_name} (New {counter})"
            counter += 1
        return table_name

    def export_table(self):
        """Export current table to file."""
        if (
            not self.app.current_table_name
            or self.app.current_table_name not in self.app.data_manager.tables_data
        ):
            messagebox.showwarning(
                "No Table Selected", "Please select a table to export."
            )
            return
        file_path = filedialog.asksaveasfilename(
            title="Export File",
            defaultextension=".json",
            filetypes=[("JSON files", "*.json"), ("CSV files", "*.csv")],
            initialfile=self.app.current_table_name,
        )
        if not file_path:
            return
        try:
            data = [
                self.app.data_manager.headers[self.app.current_table_name]
            ] + self.app.data_manager.tables_data[self.app.current_table_name]["data"]
            if file_path.endswith(".csv"):
                self.save_table_data(file_path, data, "csv")
            elif file_path.endswith(".json"):
                with open(file_path, "w", encoding="utf-8") as file:
                    json.dump(data, file, indent=4)
            else:
                raise ValueError("Unsupported file format.")
            self.app.data_manager.save_data()
            messagebox.showinfo(
                "Export Successful",
                f"Table '{self.app.current_table_name}' has been exported successfully.",
            )
        except Exception as e:
            messagebox.showerror(
                "Export Failed", f"An error occurred during export: {e}"
            )

    def save_table_data(self, file_path: str, data: list[list[str]], format: str):
        """Save table data in specified format."""
        match format:
            case "csv":
                with open(file_path, "w", newline="", encoding="utf-8") as file:
                    csv.writer(file).writerows(data)
            case "json":
                with open(file_path, "w", encoding="utf-8") as file:
                    json.dump(data, file, indent=4)
            case _:
                raise ValueError("Unsupported file format.")

    def delete_table(self):
        """Delete selected table."""
        if (
            not self.app.current_table_name
            or self.app.current_table_name not in self.app.data_manager.tables_data
        ):
            messagebox.showwarning(
                "No Table Selected", "Please select a valid table to delete."
            )
            return
        if messagebox.askyesno(
            "Delete Table",
            f"Are you sure you want to delete the table '{self.app.current_table_name}'?",
        ):
            self.remove_table(self.app.current_table_name)

    def remove_table(self, table_name: str):
        """Remove a table."""
        if self.app.current_table_name == table_name and self.app.current_sheet:
            self.app.current_sheet.destroy()
            self.app.current_sheet = None
        label = self.app.sidebar.table_labels.get(table_name)
        if label:
            label.destroy()
        if table_name in self.app.data_manager.tables_data:
            del self.app.data_manager.tables_data[table_name]
        if table_name in self.app.data_manager.headers:
            del self.app.data_manager.headers[table_name]
        if table_name in self.app.sidebar.table_labels:
            del self.app.sidebar.table_labels[table_name]
        self.app.current_table_name = None
        self.app.sidebar.selected_table_label = None
        self.app.data_manager.save_data()
        self.app.sidebar.sort_table_labels()

    def rename_headers(self):
        """Rename table headers."""
        if not self.app.current_table_name:
            messagebox.showwarning(
                "No Table Selected", "Please select a table to rename headers."
            )
            return
        current_headers = self.app.data_manager.headers[self.app.current_table_name]
        new_headers = simpledialog.askstring(
            "Rename Headers",
            "Enter new headers (comma-separated):",
            initialvalue=", ".join(current_headers),
        )
        if new_headers:
            header_list = [header.strip() for header in new_headers.split(",")]
            if not header_list:
                messagebox.showerror("Invalid Headers", "Header list cannot be empty.")
                return
            self.app.data_manager.headers[self.app.current_table_name] = header_list
            self.app.data_manager.tables_data[self.app.current_table_name][
                "headers"
            ] = header_list
            if self.app.current_sheet:
                try:
                    self.app.current_sheet.headers(header_list)
                except tk.TclError as e:
                    messagebox.showerror("Error", f"Failed to rename headers: {e}")

            self.app.filter_controls.filter_header_var.set("All")
            self.app.filter_controls.filter_header_dropdown["values"] = [
                "All"
            ] + header_list
            self.app.apply_filter()

            self.app.data_manager.save_data()

    def begin_rename(self, table_name: str):
        """Start renaming a table."""
        if table_name not in self.app.sidebar.table_labels:
            messagebox.showerror("Error", f"Table '{table_name}' not found.")
            return
        label = self.app.sidebar.table_labels[table_name]
        self.cancel_rename()
        self.app.sidebar.rename_entry = tk.Entry(
            self.app.sidebar.table_labels_frame,
            bg=label.cget("bg"),
            fg=self.app.colors["text"],
            relief="flat",
        )
        self.app.sidebar.rename_entry.insert(0, table_name)
        self.app.sidebar.rename_entry.place(
            x=label.winfo_x(),
            y=label.winfo_y(),
            width=label.winfo_width(),
            height=label.winfo_height(),
        )
        self.app.sidebar.rename_entry.focus()
        self.app.sidebar.rename_entry.select_range(0, tk.END)
        self.app.sidebar.rename_entry.bind(
            "<Return>", lambda event: self.end_rename(table_name)
        )
        self.app.sidebar.rename_entry.bind("<FocusOut>", lambda event: self.cancel_rename())

    def end_rename(self, old_name: str):
        """Finalize table renaming."""
        new_name = self.app.sidebar.rename_entry.get().strip()
        if not new_name:
            messagebox.showerror("Invalid Name", "Table name cannot be empty.")
            self.app.sidebar.rename_entry.focus_set()
            return
        if new_name in self.app.data_manager.tables_data and new_name != old_name:
            messagebox.showerror(
                "Duplicate Name", f"A table named '{new_name}' already exists."
            )
            self.app.sidebar.rename_entry.focus_set()
            return
        if new_name != old_name:
            self.update_table_name(old_name, new_name)
            self.load_selected_table(new_name)
        self.cancel_rename()

    def update_table_name(self, old_name: str, new_name: str):
        """Update table name and resources."""
        self.app.data_manager.tables_data[new_name] = self.app.data_manager.tables_data.pop(
            old_name
        )
        self.app.data_manager.headers[new_name] = self.app.data_manager.headers.pop(
            old_name
        )
        label = self.app.sidebar.table_labels.pop(old_name)
        label.config(text=new_name)
        label.bind(
            "<Button-1>", lambda event: self.load_selected_table(new_name)
        )
        label.bind(
            "<Double-1>", lambda event: self.begin_rename(new_name)
        )
        self.app.sidebar.table_labels[new_name] = label
        if self.app.sidebar.selected_table_label == label:
            try:
                label.config(bg=self.app.colors["button_selected"])
            except tk.TclError:
                pass
        self.app.data_manager.save_data()
        self.app.sidebar.sort_table_labels()

    def cancel_rename(self):
        """Cancel rename operation."""
        if self.app.sidebar.rename_entry:
            self.app.sidebar.rename_entry.destroy()
            self.app.sidebar.rename_entry = None