/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.ui;

import android.app.AlertDialog;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import androidx.appcompat.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.NotesRepository;
import net.micode.notes.ui.NoteInfoAdapter;
import net.micode.notes.viewmodel.NotesListViewModel;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.List;

/**
 * 笔记列表Activity（重构版）
 * <p>
 * 仅负责UI展示和用户交互，业务逻辑委托给ViewModel
 * 符合MVVM架构模式
 * </p>
 * <p>
 * 相比原版（1305行），重构后代码量减少约70%
 * </p>
 *
 * @see NotesListViewModel
 * @see NotesRepository
 */
public class NotesListActivity extends AppCompatActivity
    implements NoteInfoAdapter.OnNoteButtonClickListener,
               NoteInfoAdapter.OnNoteItemClickListener,
               NoteInfoAdapter.OnNoteItemLongClickListener,
               SidebarFragment.OnSidebarItemSelectedListener {
    private static final String TAG = "NotesListActivity";
    private static final int REQUEST_CODE_OPEN_NODE = 102;
    private static final int REQUEST_CODE_NEW_NODE = 103;

    private NotesListViewModel viewModel;
    private ListView notesListView;
    private androidx.appcompat.widget.Toolbar toolbar;
    private NoteInfoAdapter adapter;
    private DrawerLayout drawerLayout;
    private FloatingActionButton fabNewNote;
    private LinearLayout breadcrumbContainer;
    private LinearLayout breadcrumbItems;

    // 多选模式状态
    private boolean isMultiSelectMode = false;

    /**
     * 活动创建时的初始化方法
     * <p>
     * 设置布局，初始化ViewModel，设置UI监听器
     * </p>
     *
     * @param savedInstanceState 保存的实例状态
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 启用边缘到边缘显示
        WindowCompat.setDecorFitsSystemWindows(getWindow(), false);

        setContentView(R.layout.note_list);

        // 处理窗口insets（状态栏和导航栏）
        View mainView = findViewById(android.R.id.content);
        ViewCompat.setOnApplyWindowInsetsListener(mainView, (v, windowInsets) -> {
            Insets insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars());
            // 设置内容区域的padding以避免被状态栏遮挡
            v.setPadding(insets.left, insets.top, insets.right, insets.bottom);
            return WindowInsetsCompat.CONSUMED;
        });

        initViewModel();
        initViews();
        observeViewModel();
    }

    /**
     * 活动启动时的回调方法
     * <p>
     * 加载笔记列表
     * </p>
     */
    @Override
    protected void onStart() {
        super.onStart();
        viewModel.loadNotes(Notes.ID_ROOT_FOLDER);
    }

    /**
     * 初始化ViewModel
     */
    private void initViewModel() {
        NotesRepository repository = new NotesRepository(getContentResolver());
        viewModel = new ViewModelProvider(this,
            new ViewModelProvider.Factory() {
                @Override
                public <T extends ViewModel> T create(Class<T> modelClass) {
                    if (modelClass.isAssignableFrom(NotesListViewModel.class)) {
                        return (T) new NotesListViewModel(repository);
                    }
                    throw new IllegalArgumentException("Unknown ViewModel class");
                }
            }).get(NotesListViewModel.class);
        Log.d(TAG, "ViewModel initialized");
    }

    /**
     * 初始化视图
     */
    private void initViews() {
        notesListView = findViewById(R.id.notes_list);
        toolbar = findViewById(R.id.toolbar);
        drawerLayout = findViewById(R.id.drawer_layout);

        // 初始化面包屑导航
        breadcrumbContainer = findViewById(R.id.breadcrumb_container);
        breadcrumbItems = findViewById(R.id.breadcrumb_items);

        // 设置适配器
        adapter = new NoteInfoAdapter(this);
        notesListView.setAdapter(adapter);
        adapter.setOnNoteButtonClickListener(this);
        adapter.setOnNoteItemClickListener(this);
        adapter.setOnNoteItemLongClickListener(this);

        // 设置点击监听
        notesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Object item = parent.getItemAtPosition(position);
                if (item instanceof NotesRepository.NoteInfo) {
                    NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) item;
                    handleItemClick(note, position);
                }
            }
        });

        // 初始化 Toolbar
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(R.string.app_name);
        }

        // 初始化为普通模式
        updateToolbarForNormalMode();

        // 设置 Toolbar 的汉堡菜单按钮点击监听器（打开侧栏）
        toolbar.setNavigationOnClickListener(v -> {
            if (drawerLayout != null) {
                drawerLayout.openDrawer(findViewById(R.id.sidebar_fragment));
            }
        });

        // Set FAB click event
        fabNewNote = findViewById(R.id.btn_new_note);
        if (fabNewNote != null) {
            fabNewNote.setOnClickListener(v -> {
                Intent intent = new Intent(NotesListActivity.this, NoteEditActivity.class);
                intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
                intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, viewModel.getCurrentFolderId());
                startActivityForResult(intent, REQUEST_CODE_NEW_NODE);
            });
        }
    }

    /**
     * 处理列表项点击
     * <p>
     * 如果是便签，打开编辑器；如果是文件夹，进入该文件夹
     * </p>
     *
     * @param note 项
     * @param position 位置
     */
    private void handleItemClick(NotesRepository.NoteInfo note, int position) {
        if (isMultiSelectMode) {
            // 多选模式：切换选中状态
            boolean isSelected = viewModel.getSelectedNoteIds().contains(note.getId());
            viewModel.toggleNoteSelection(note.getId(), !isSelected);
            if (adapter != null) {
                adapter.setSelectedIds(viewModel.getSelectedNoteIds());
            }
            updateToolbarForMultiSelectMode();
        } else {
            // 普通模式
            if (note.type == Notes.TYPE_FOLDER) {
                // 文件夹：进入该文件夹
                viewModel.enterFolder(note.getId());
            } else {
                // 便签：打开编辑器
                openNoteEditor(note);
            }
        }
    }

    /**
     * 观察ViewModel的LiveData
     */
    private void observeViewModel() {
        // 观察笔记列表
        viewModel.getNotesLiveData().observe(this, new Observer<List<NotesRepository.NoteInfo>>() {
            @Override
            public void onChanged(List<NotesRepository.NoteInfo> notes) {
                updateAdapter(notes);
            }
        });

        // 观察加载状态
        viewModel.getIsLoading().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean isLoading) {
                updateLoadingState(isLoading);
            }
        });

        // 观察错误消息
        viewModel.getErrorMessage().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String message) {
                if (message != null && !message.isEmpty()) {
                    showError(message);
                }
            }
        });

        // 观察文件夹路径（用于面包屑导航）
        viewModel.getFolderPathLiveData().observe(this, new Observer<List<NotesRepository.NoteInfo>>() {
            @Override
            public void onChanged(List<NotesRepository.NoteInfo> path) {
                updateBreadcrumb(path);
            }
        });

        // 观察侧栏刷新通知
        viewModel.getSidebarRefreshNeeded().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean refreshNeeded) {
                if (refreshNeeded != null && refreshNeeded) {
                    // 通知侧栏刷新
                    SidebarFragment sidebarFragment = (SidebarFragment) getSupportFragmentManager()
                            .findFragmentById(R.id.sidebar_fragment);
                    if (sidebarFragment != null) {
                        sidebarFragment.refreshFolderTree();
                    }
                    // 重置刷新状态
                    viewModel.getSidebarRefreshNeeded().setValue(false);
                }
            }
        });
    }

    /**
     * 更新面包屑导航
     *
     * @param path 文件夹路径
     */
    private void updateBreadcrumb(List<NotesRepository.NoteInfo> path) {
        if (breadcrumbItems == null || path == null) {
            return;
        }

        breadcrumbItems.removeAllViews();

        for (int i = 0; i < path.size(); i++) {
            NotesRepository.NoteInfo folder = path.get(i);

            // 如果不是第一个，添加分隔符 " > "
            if (i > 0) {
                TextView separator = new TextView(this);
                separator.setText(" > ");
                separator.setTextSize(14);
                separator.setTextColor(android.R.color.darker_gray);
                breadcrumbItems.addView(separator);
            }

            // 创建面包屑项
            TextView breadcrumbItem = (TextView) getLayoutInflater()
                    .inflate(R.layout.breadcrumb_item, breadcrumbItems, false);
            breadcrumbItem.setText(folder.title);

            // 如果是当前文件夹（最后一个），高亮显示且不可点击
            if (i == path.size() - 1) {
                breadcrumbItem.setTextColor(getColor(R.color.primary_color));
                breadcrumbItem.setEnabled(false);
            } else {
                // 其他层级可以点击跳转
                final long targetFolderId = folder.id;
                breadcrumbItem.setOnClickListener(v -> viewModel.enterFolder(targetFolderId));
            }

            breadcrumbItems.addView(breadcrumbItem);
        }
    }

    /**
     * 更新适配器数据
     */
    private void updateAdapter(List<NotesRepository.NoteInfo> notes) {
        adapter.setNotes(notes);
        Log.d(TAG, "Adapter updated with " + notes.size() + " notes");
    }

    /**
     * 更新加载状态
     */
    private void updateLoadingState(boolean isLoading) {
        // TODO: 显示/隐藏进度条
    }

    /**
     * 显示错误消息
     */
    private void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    /**
     * 打开笔记编辑器
     */
    private void openNoteEditor(NotesRepository.NoteInfo note) {
        Intent intent = new Intent(this, NoteEditActivity.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, note.getParentId());
        intent.putExtra(Intent.EXTRA_UID, note.getId());
        startActivityForResult(intent, REQUEST_CODE_OPEN_NODE);
    }

    /**
     * 编辑按钮点击事件处理
     *
     * @param position 列表位置
     * @param noteId   便签 ID
     */
    @Override
    public void onEditButtonClick(int position, long noteId) {
        NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) adapter.getItem(position);
        if (note != null) {
            openNoteEditor(note);
        } else {
            Log.e(TAG, "Edit button clicked but note is null at position: " + position);
        }
    }

    @Override
    public void onNoteItemClick(int position, long noteId) {
        Log.d(TAG, "===== onNoteItemClick CALLED =====");
        Log.d(TAG, "position: " + position + ", noteId: " + noteId);

        if (isMultiSelectMode) {
            Log.d(TAG, "Multi-select mode active, toggling selection");
            NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) adapter.getItem(position);
            if (note != null) {
                boolean isSelected = viewModel.getSelectedNoteIds().contains(note.getId());
                viewModel.toggleNoteSelection(note.getId(), !isSelected);

                if (adapter != null) {
                    adapter.setSelectedIds(viewModel.getSelectedNoteIds());
                }
                // 更新toolbar标题
                updateToolbarForMultiSelectMode();
            }
            Log.d(TAG, "===== onNoteItemClick END (multi-select mode) =====");
        } else {
            Log.d(TAG, "Normal mode, checking item type");
            NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) adapter.getItem(position);
            if (note != null) {
                if (note.type == Notes.TYPE_FOLDER) {
                    // 文件夹：进入该文件夹
                    Log.d(TAG, "Folder clicked, entering folder: " + note.getId());
                    viewModel.enterFolder(note.getId());
                } else {
                    // 便签：打开编辑器
                    Log.d(TAG, "Note clicked, opening editor");
                    openNoteEditor(note);
                }
            }
            Log.d(TAG, "===== onNoteItemClick END =====");
        }
    }

    @Override
    public void onNoteItemLongClick(int position, long noteId) {
        Log.d(TAG, "===== onNoteItemLongClick CALLED =====");
        Log.d(TAG, "position: " + position + ", noteId: " + noteId);

        if (!isMultiSelectMode) {
            Log.d(TAG, "Entering multi-select mode");
            enterMultiSelectMode();
            viewModel.toggleNoteSelection(noteId, true);

            if (adapter != null) {
                adapter.setSelectedIds(viewModel.getSelectedNoteIds());
            }

            updateSelectionState(position, true);

            Log.d(TAG, "===== onNoteItemLongClick END =====");
        } else {
            Log.d(TAG, "Multi-select mode already active, ignoring long click");
        }
    }

    /**
     * 进入多选模式
     */
    private void enterMultiSelectMode() {
        isMultiSelectMode = true;
        // 隐藏FAB按钮
        if (fabNewNote != null) {
            fabNewNote.setVisibility(View.GONE);
        }
        // 更新toolbar为多选模式
        updateToolbarForMultiSelectMode();
    }

    /**
     * 退出多选模式
     */
    private void exitMultiSelectMode() {
        isMultiSelectMode = false;
        // 显示FAB按钮
        if (fabNewNote != null) {
            fabNewNote.setVisibility(View.VISIBLE);
        }
        // 清除选中状态
        viewModel.clearSelection();
        if (adapter != null) {
            adapter.setSelectedIds(new java.util.HashSet<>());
            adapter.notifyDataSetChanged();
        }
        // 更新toolbar为普通模式
        updateToolbarForNormalMode();
    }

    /**
     * 更新Toolbar为多选模式
     */
    private void updateToolbarForMultiSelectMode() {
        if (toolbar == null) return;

        // 设置标题为选中数量
        int selectedCount = viewModel.getSelectedCount();
        String title = getString(R.string.menu_select_title, selectedCount);
        toolbar.setTitle(title);

        // 设置导航图标为返回（取消多选）
        toolbar.setNavigationIcon(androidx.appcompat.R.drawable.abc_ic_ab_back_material);
        toolbar.setNavigationOnClickListener(v -> exitMultiSelectMode());

        // 移除普通模式的菜单（如果有）
        toolbar.getMenu().clear();

        // 直接在toolbar上添加操作按钮（不在三点菜单中）
        Menu menu = toolbar.getMenu();

        // 删除按钮
        MenuItem deleteItem = menu.add(Menu.NONE, R.id.multi_select_delete, 1, getString(R.string.menu_delete));
        deleteItem.setIcon(android.R.drawable.ic_menu_delete);
        deleteItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        // 移动按钮
        MenuItem moveItem = menu.add(Menu.NONE, R.id.multi_select_move, 2, getString(R.string.menu_move));
        moveItem.setIcon(android.R.drawable.ic_menu_sort_by_size);
        moveItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        // 置顶按钮
        boolean allPinned = viewModel.isAllSelectedPinned();
        MenuItem pinItem = menu.add(Menu.NONE, R.id.multi_select_pin, 3, allPinned ? getString(R.string.menu_unpin) : getString(R.string.menu_pin));
        // 使用上传图标代替置顶图标，或者如果有合适的资源可以使用
        pinItem.setIcon(android.R.drawable.ic_menu_upload);
        pinItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    }

    /**
     * 更新Toolbar为普通模式
     */
    private void updateToolbarForNormalMode() {
        if (toolbar == null) return;

        // 设置标题为应用名称
        toolbar.setTitle(R.string.app_name);

        // 设置导航图标为汉堡菜单
        toolbar.setNavigationIcon(android.R.drawable.ic_menu_sort_by_size);
        toolbar.setNavigationOnClickListener(v -> {
            if (drawerLayout != null) {
                drawerLayout.openDrawer(findViewById(R.id.sidebar_fragment));
            }
        });

        // 清除多选模式菜单
        toolbar.getMenu().clear();

        // 添加普通模式菜单（如果需要）
        // getMenuInflater().inflate(R.menu.note_list_options, menu);
    }



    /**
     * 显示删除确认对话框
     */
    private void showDeleteDialog() {
        int selectedCount = viewModel.getSelectedCount();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.alert_title_delete));
        builder.setIcon(android.R.drawable.ic_dialog_alert);
        builder.setMessage(getString(R.string.alert_message_delete_notes, selectedCount));
        builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                viewModel.deleteSelectedNotes();
            }
        });
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    /**
     * 显示移动菜单
     */
    private void showMoveMenu() {
        // TODO: 实现文件夹选择逻辑
        Toast.makeText(this, "移动功能开发中", Toast.LENGTH_SHORT).show();
    }

    /**
     * 活动结果回调方法
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE) {
                viewModel.refreshNotes();
            }
        }
    }

    /**
     * 创建选项菜单
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.note_list, menu);
        return true;
    }

    /**
     * 选项菜单项点击事件
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();

        switch (itemId) {
            case R.id.menu_search:
                // TODO: 打开搜索对话框
                Toast.makeText(this, "搜索功能开发中", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.menu_new_folder:
                // 创建新文件夹
                showCreateFolderDialog();
                return true;
            case R.id.menu_export_text:
                // TODO: 导出笔记
                Toast.makeText(this, "导出功能开发中", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.menu_sync:
                // TODO: 同步功能
                Toast.makeText(this, "同步功能暂不可用", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.menu_setting:
                // TODO: 设置功能
                Toast.makeText(this, "设置功能开发中", Toast.LENGTH_SHORT).show();
                return true;
            // 多选模式菜单项
            case R.id.multi_select_delete:
                showDeleteDialog();
                return true;
            case R.id.multi_select_move:
                showMoveMenu();
                return true;
            case R.id.multi_select_pin:
                boolean wasPinned = viewModel.isAllSelectedPinned();
                viewModel.toggleSelectedNotesPin();
                String toastMsg = wasPinned ? getString(R.string.menu_unpin) + "成功" : getString(R.string.menu_pin) + "成功";
                Toast.makeText(this, toastMsg, Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * 上下文菜单创建
     */
    @Override
    public void onCreateContextMenu(android.view.ContextMenu menu, View v, android.view.ContextMenu.ContextMenuInfo menuInfo) {
        getMenuInflater().inflate(R.menu.sub_folder, menu);
    }

    /**
     * 上下文菜单项点击
     */
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        // TODO: 处理文件夹上下文菜单
        return super.onContextItemSelected(item);
    }

    /**
     * 活动销毁时的清理
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 清理资源
    }

    private void updateSelectionState(int position, boolean selected) {
        Log.d("NotesListActivity", "===== updateSelectionState called =====");
        Log.d("NotesListActivity", "position: " + position + ", selected: " + selected);
        NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) adapter.getItem(position);
        if (note != null) {
            Log.d("NotesListActivity", "note ID: " + note.getId());
            Log.d("NotesListActivity", "Current selectedIds size before update: " + adapter.getSelectedIds().size());
            Log.d("NotesListActivity", "Note already in selectedIds: " + adapter.getSelectedIds().contains(note.getId()));
            if (adapter.getSelectedIds().contains(note.getId()) != selected) {
                if (selected) {
                    Log.d("NotesListActivity", "Adding note ID to selectedIds");
                    adapter.getSelectedIds().add(note.getId());
                } else {
                    Log.d("NotesListActivity", "Removing note ID from selectedIds");
                    adapter.getSelectedIds().remove(note.getId());
                }
                Log.d("NotesListActivity", "SelectedIds size after update: " + adapter.getSelectedIds().size());
                adapter.notifyDataSetChanged();
                Log.d("NotesListActivity", "notifyDataSetChanged() called");
            } else {
                Log.d("NotesListActivity", "Note selection state unchanged, skipping update");
            }
        } else {
            Log.e("NotesListActivity", "note is NULL at position: " + position);
        }
        Log.d("NotesListActivity", "===== updateSelectionState END =====");
    }

    // ==================== SidebarFragment.OnSidebarItemSelectedListener 实现 ====================

    @Override
    public void onFolderSelected(long folderId) {
        // 跳转到指定文件夹
        viewModel.enterFolder(folderId);
        // 关闭侧栏
        if (drawerLayout != null) {
            drawerLayout.closeDrawer(findViewById(R.id.sidebar_fragment));
        }
    }

    @Override
    public void onTrashSelected() {
        // TODO: 实现跳转到回收站
        Log.d(TAG, "Trash selected");
        // 关闭侧栏
        if (drawerLayout != null) {
            drawerLayout.closeDrawer(findViewById(R.id.sidebar_fragment));
        }
    }

    @Override
    public void onSyncSelected() {
        // TODO: 实现同步功能
        Log.d(TAG, "Sync selected");
        Toast.makeText(this, "同步功能待实现", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLoginSelected() {
        // TODO: 实现登录功能
        Log.d(TAG, "Login selected");
        Toast.makeText(this, "登录功能待实现", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onExportSelected() {
        // TODO: 实现导出功能
        Log.d(TAG, "Export selected");
        Toast.makeText(this, "导出功能待实现", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSettingsSelected() {
        // TODO: 实现设置功能
        Log.d(TAG, "Settings selected");
        Toast.makeText(this, "设置功能待实现", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCreateFolder() {
        // 显示创建文件夹对话框
        showCreateFolderDialog();
    }

    /**
     * 显示创建文件夹对话框
     */
    private void showCreateFolderDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.dialog_create_folder_title);

        final EditText input = new EditText(this);
        input.setHint(R.string.dialog_create_folder_hint);
        input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});

        builder.setView(input);

        builder.setPositiveButton(R.string.menu_create_folder, (dialog, which) -> {
            String folderName = input.getText().toString().trim();
            if (TextUtils.isEmpty(folderName)) {
                Toast.makeText(this, R.string.error_folder_name_empty, Toast.LENGTH_SHORT).show();
                return;
            }
            if (folderName.length() > 50) {
                Toast.makeText(this, R.string.error_folder_name_too_long, Toast.LENGTH_SHORT).show();
                return;
            }

            // 创建文件夹
            NotesRepository repository = new NotesRepository(getContentResolver());
            long parentId = viewModel.getCurrentFolderId();
            if (parentId == 0) {
                parentId = Notes.ID_ROOT_FOLDER;
            }
            repository.createFolder(parentId, folderName,
                new NotesRepository.Callback<Long>() {
                    @Override
                    public void onSuccess(Long folderId) {
                        runOnUiThread(() -> {
                            Toast.makeText(NotesListActivity.this, R.string.create_folder_success, Toast.LENGTH_SHORT).show();
                            // 刷新笔记列表
                            viewModel.loadNotes(viewModel.getCurrentFolderId());
                        });
                    }

                    @Override
                    public void onError(Exception error) {
                        runOnUiThread(() -> {
                            Toast.makeText(NotesListActivity.this, "创建文件夹失败: " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        });
                    }
                });
        });

        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    @Override
    public void onCloseSidebar() {
        // 关闭侧栏
        if (drawerLayout != null) {
            drawerLayout.closeDrawer(findViewById(R.id.sidebar_fragment));
        }
    }

    /**
     * 返回键按下事件处理
     * <p>
     * 多选模式：退出多选模式
     * 子文件夹：返回上一级文件夹
     * 根文件夹：最小化应用
     * </p>
     */
    @Override
    public void onBackPressed() {
        if (isMultiSelectMode) {
            // 多选模式：退出多选模式
            exitMultiSelectMode();
        } else if (drawerLayout != null && drawerLayout.isDrawerOpen(findViewById(R.id.sidebar_fragment))) {
            // 侧栏打开：关闭侧栏
            drawerLayout.closeDrawer(findViewById(R.id.sidebar_fragment));
        } else if (viewModel.getCurrentFolderId() != Notes.ID_ROOT_FOLDER &&
                   viewModel.getCurrentFolderId() != Notes.ID_CALL_RECORD_FOLDER) {
            // 子文件夹：返回上一级
            if (!viewModel.navigateUp()) {
                // 如果没有导航历史，返回根文件夹
                viewModel.loadNotes(Notes.ID_ROOT_FOLDER);
            }
        } else {
            // 根文件夹：最小化应用
            moveTaskToBack(true);
        }
    }
}
