// src/functions/modes/navigation/admin_nav.rs
use crate::state::pages::admin::{AdminFocus, AdminState};
use crate::state::app::state::AppState;
use crate::config::binds::config::Config;
use crate::state::app::buffer::{BufferState, AppView};
use crate::state::pages::add_table::{AddTableState, LinkDefinition};
use ratatui::widgets::ListState;
use crate::state::pages::add_logic::{AddLogicState, AddLogicFocus}; // Added AddLogicFocus import

// Helper functions list_select_next and list_select_previous remain the same
fn list_select_next(list_state: &mut ListState, item_count: usize) {
    if item_count == 0 {
        list_state.select(None);
        return;
    }
    let i = match list_state.selected() {
        Some(i) => if i >= item_count - 1 { 0 } else { i + 1 },
        None => 0,
    };
    list_state.select(Some(i));
}

fn list_select_previous(list_state: &mut ListState, item_count: usize) {
    if item_count == 0 {
        list_state.select(None);
        return;
    }
    let i = match list_state.selected() {
        Some(i) => if i == 0 { item_count - 1 } else { i - 1 },
        None => if item_count > 0 { item_count - 1 } else { 0 },
    };
    list_state.select(Some(i));
}

pub fn handle_admin_navigation(
    key: crossterm::event::KeyEvent,
    config: &Config,
    app_state: &mut AppState,
    admin_state: &mut AdminState,
    buffer_state: &mut BufferState,
    command_message: &mut String,
) -> bool {
    let action = config.get_general_action(key.code, key.modifiers).map(String::from);
    let current_focus = admin_state.current_focus;
    let profile_count = app_state.profile_tree.profiles.len();
    let mut handled = false;

    match current_focus {
        AdminFocus::ProfilesPane => {
            match action.as_deref() {
                Some("select") => {
                    admin_state.current_focus = AdminFocus::InsideProfilesList;
                    if !app_state.profile_tree.profiles.is_empty() {
                        if admin_state.profile_list_state.selected().is_none() {
                            admin_state.profile_list_state.select(Some(0));
                        }
                    }
                    *command_message = "Navigating profiles. Use Up/Down. Esc to exit.".to_string();
                    handled = true;
                }
                Some("next_option") | Some("move_down") => {
                    admin_state.current_focus = AdminFocus::Tables;
                    *command_message = "Focus: Tables Pane".to_string();
                    handled = true;
                }
                Some("previous_option") | Some("move_up") => {
                    // No wrap-around: Stay on ProfilesPane if trying to go "before" it
                    *command_message = "At first focusable pane.".to_string();
                    handled = true;
                }
                _ => handled = false,
            }
        }

        AdminFocus::InsideProfilesList => {
            match action.as_deref() {
                Some("move_up") => {
                    if profile_count > 0 {
                        list_select_previous(&mut admin_state.profile_list_state, profile_count);
                        *command_message = "".to_string();
                        handled = true;
                    }
                }
                Some("move_down") => {
                    if profile_count > 0 {
                        list_select_next(&mut admin_state.profile_list_state, profile_count);
                        *command_message = "".to_string();
                        handled = true;
                    }
                }
                Some("select") => {
                    admin_state.selected_profile_index = admin_state.profile_list_state.selected();
                    admin_state.selected_table_index = None; // Deselect table when profile changes
                    if let Some(profile_idx) = admin_state.selected_profile_index {
                        if let Some(profile) = app_state.profile_tree.profiles.get(profile_idx) {
                            if !profile.tables.is_empty() {
                                admin_state.table_list_state.select(Some(0)); // Auto-select first table for nav
                            } else {
                                admin_state.table_list_state.select(None);
                            }
                        }
                    } else {
                        admin_state.table_list_state.select(None);
                    }
                    *command_message = format!(
                        "Profile '{}' set as active.",
                        admin_state.get_selected_profile_name().unwrap_or(&"N/A".to_string())
                    );
                    handled = true;
                }
                Some("exit_table_scroll") => {
                    admin_state.current_focus = AdminFocus::ProfilesPane;
                    *command_message = "Focus: Profiles Pane".to_string();
                    handled = true;
                }
                _ => handled = false,
            }
        }

        AdminFocus::Tables => {
            match action.as_deref() {
                Some("select") => {
                    admin_state.current_focus = AdminFocus::InsideTablesList;
                    let current_profile_idx = admin_state.selected_profile_index
                        .or_else(|| admin_state.profile_list_state.selected());
                    if let Some(profile_idx) = current_profile_idx {
                        if let Some(profile) = app_state.profile_tree.profiles.get(profile_idx) {
                             if !profile.tables.is_empty() {
                                if admin_state.table_list_state.selected().is_none() {
                                    admin_state.table_list_state.select(Some(0));
                                }
                             } else {
                                admin_state.table_list_state.select(None);
                             }
                        } else {
                            admin_state.table_list_state.select(None);
                        }
                    } else {
                        admin_state.table_list_state.select(None);
                         *command_message = "Select a profile first to view its tables.".to_string();
                    }
                    if admin_state.current_focus == AdminFocus::InsideTablesList && !admin_state.table_list_state.selected().is_none() {
                        *command_message = "Navigating tables. Use Up/Down. Esc to exit.".to_string();
                    } else if admin_state.table_list_state.selected().is_none() {
                         if current_profile_idx.is_none() {
                            *command_message = "No profile selected to view tables.".to_string();
                         } else {
                            *command_message = "No tables in selected profile.".to_string();
                         }
                         admin_state.current_focus = AdminFocus::Tables; // Stay in Tables pane if no tables to enter
                    }
                    handled = true;
                }
                Some("previous_option") | Some("move_up") => {
                    admin_state.current_focus = AdminFocus::ProfilesPane;
                    *command_message = "Focus: Profiles Pane".to_string();
                    handled = true;
                }
                Some("next_option") | Some("move_down") => {
                    admin_state.current_focus = AdminFocus::Button1;
                    *command_message = "Focus: Add Logic Button".to_string();
                    handled = true;
                }
                _ => handled = false,
            }
        }

        AdminFocus::InsideTablesList => {
            match action.as_deref() {
                Some("move_up") => {
                    let current_profile_idx = admin_state.selected_profile_index
                        .or_else(|| admin_state.profile_list_state.selected());
                    if let Some(p_idx) = current_profile_idx {
                        if let Some(profile) = app_state.profile_tree.profiles.get(p_idx) {
                            if !profile.tables.is_empty() {
                                list_select_previous(&mut admin_state.table_list_state, profile.tables.len());
                                *command_message = "".to_string();
                                handled = true;
                            } else {
                                *command_message = "No tables to navigate.".to_string();
                                handled = true;
                            }
                        }
                    } else {
                        *command_message = "No active profile for tables.".to_string();
                        handled = true;
                    }
                }
                Some("move_down") => {
                    let current_profile_idx = admin_state.selected_profile_index
                        .or_else(|| admin_state.profile_list_state.selected());
                    if let Some(p_idx) = current_profile_idx {
                        if let Some(profile) = app_state.profile_tree.profiles.get(p_idx) {
                             if !profile.tables.is_empty() {
                                list_select_next(&mut admin_state.table_list_state, profile.tables.len());
                                *command_message = "".to_string();
                                handled = true;
                            } else {
                                *command_message = "No tables to navigate.".to_string();
                                handled = true;
                            }
                        }
                    } else {
                        *command_message = "No active profile for tables.".to_string();
                        handled = true;
                    }
                }
                Some("select") => { // This is for persistently selecting a table with [*]
                    admin_state.selected_table_index = admin_state.table_list_state.selected();
                    let table_name = admin_state.selected_profile_index
                         .and_then(|p_idx| app_state.profile_tree.profiles.get(p_idx))
                         .and_then(|p| admin_state.selected_table_index.and_then(|t_idx| p.tables.get(t_idx)))
                         .map_or("N/A", |t| t.name.as_str());
                    *command_message = format!("Table '{}' set as active.", table_name);
                    handled = true;
                }
                Some("exit_table_scroll") => {
                    admin_state.current_focus = AdminFocus::Tables;
                    *command_message = "Focus: Tables Pane".to_string();
                    handled = true;
                }
                _ => handled = false,
            }
        }

        AdminFocus::Button1 => { // Add Logic Button
            match action.as_deref() {
                Some("select") => { // Typically "Enter" key
                    if let Some(p_idx) = admin_state.selected_profile_index {
                        if let Some(profile) = app_state.profile_tree.profiles.get(p_idx) {
                            if let Some(t_idx) = admin_state.selected_table_index {
                                if let Some(table) = profile.tables.get(t_idx) {
                                    // Both profile and table are selected, proceed
                                    admin_state.add_logic_state = AddLogicState {
                                        profile_name: profile.name.clone(),
                                        selected_table_name: Some(table.name.clone()),
                                        selected_table_id: Some(table.id), // If you have table IDs
                                        editor_keybinding_mode: config.editor.keybinding_mode.clone(),
                                        current_focus: AddLogicFocus::default(),
                                        ..AddLogicState::default()
                                    };
                                    
                                    // Store table info for later fetching
                                    app_state.pending_table_structure_fetch = Some((
                                        profile.name.clone(),
                                        table.name.clone()
                                    ));
                                    
                                    buffer_state.update_history(AppView::AddLogic);
                                    app_state.ui.focus_outside_canvas = false;
                                    *command_message = format!(
                                        "Opening Add Logic for table '{}' in profile '{}'...",
                                        table.name, profile.name
                                    );
                                } else {
                                    *command_message = "Error: Selected table data not found.".to_string();
                                }
                            } else {
                                *command_message = "Select a table first!".to_string();
                            }
                        } else {
                            *command_message = "Error: Selected profile data not found.".to_string();
                        }
                    } else {
                        *command_message = "Select a profile first!".to_string();
                    }
                    handled = true;
                }
                Some("previous_option") | Some("move_up") => {
                    admin_state.current_focus = AdminFocus::Tables;
                    *command_message = "Focus: Tables Pane".to_string();
                    handled = true;
                }
                Some("next_option") | Some("move_down") => {
                    admin_state.current_focus = AdminFocus::Button2;
                    *command_message = "Focus: Add Table Button".to_string();
                    handled = true;
                }
                _ => handled = false,
            }
        }

        AdminFocus::Button2 => { // Add Table Button
            match action.as_deref() {
                Some("select") => {
                     if let Some(p_idx) = admin_state.selected_profile_index {
                        if let Some(profile) = app_state.profile_tree.profiles.get(p_idx) {
                            let selected_profile_name = profile.name.clone();
                            // Prepare links from the selected profile's existing tables
                            let available_links: Vec<LinkDefinition> = profile.tables.iter()
                                .map(|table| LinkDefinition {
                                    linked_table_name: table.name.clone(),
                                    is_required: false, // Default, can be changed in AddTable screen
                                    selected: false,
                                }).collect();

                            admin_state.add_table_state = AddTableState {
                                profile_name: selected_profile_name,
                                links: available_links,
                                ..AddTableState::default() // Reset other fields
                            };
                            buffer_state.update_history(AppView::AddTable);
                            app_state.ui.focus_outside_canvas = false;
                            *command_message = format!("Opening Add Table for profile '{}'...", admin_state.add_table_state.profile_name);
                            handled = true;
                        } else {
                             *command_message = "Error: Selected profile index out of bounds.".to_string();
                             handled = true;
                        }
                    } else {
                        *command_message = "Please select a profile ([*]) first to add a table.".to_string();
                        handled = true;
                    }
                }
                Some("previous_option") | Some("move_up") => {
                    admin_state.current_focus = AdminFocus::Button1;
                    *command_message = "Focus: Add Logic Button".to_string();
                    handled = true;
                }
                Some("next_option") | Some("move_down") => {
                    admin_state.current_focus = AdminFocus::Button3;
                    *command_message = "Focus: Change Table Button".to_string();
                    handled = true;
                }
                _ => handled = false,
            }
        }

        AdminFocus::Button3 => { // Change Table Button
            match action.as_deref() {
                Some("select") => {
                    // Future: Logic to load selected table into AddTableState for editing
                    *command_message = "Action: Change Table (Not Implemented)".to_string();
                    handled = true;
                }
                Some("previous_option") | Some("move_up") => {
                    admin_state.current_focus = AdminFocus::Button2;
                    *command_message = "Focus: Add Table Button".to_string();
                    handled = true;
                }
                Some("next_option") | Some("move_down") => {
                    // No wrap-around: Stay on Button3 if trying to go "after" it
                    *command_message = "At last focusable button.".to_string();
                    handled = true;
                }
                _ => handled = false,
            }
        }
    }
    handled
}
