// src/pages/admin/admin/state.rs
use ratatui::widgets::ListState;
use crate::state::pages::add_table::AddTableState;
use crate::state::pages::add_logic::AddLogicState;
use crate::movement::{move_focus, MovementAction};
use crate::state::app::state::AppState;

/// Focus states for the admin panel
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AdminFocus {
    #[default]
    ProfilesPane,
    InsideProfilesList,
    Tables,
    InsideTablesList,
    Button1,
    Button2,
    Button3,
}

/// Full admin panel state (for logged-in admins)
#[derive(Default, Clone, Debug)]
pub struct AdminState {
    pub profiles: Vec<String>,
    pub profile_list_state: ListState,
    pub table_list_state: ListState,
    pub selected_profile_index: Option<usize>,
    pub selected_table_index: Option<usize>,
    pub current_focus: AdminFocus,
    pub add_table_state: AddTableState,
    pub add_logic_state: AddLogicState,
}

impl AdminState {
    pub fn get_selected_index(&self) -> Option<usize> {
        self.profile_list_state.selected()
    }

    pub fn get_selected_profile_name(&self) -> Option<&String> {
        self.profile_list_state.selected().and_then(|i| self.profiles.get(i))
    }

    pub fn set_profiles(&mut self, new_profiles: Vec<String>) {
        let current_selection_index = self.profile_list_state.selected();
        self.profiles = new_profiles;

        if self.profiles.is_empty() {
            self.profile_list_state.select(None);
        } else {
            let new_selection = match current_selection_index {
                Some(index) => Some(index.min(self.profiles.len() - 1)),
                None => Some(0),
            };
            self.profile_list_state.select(new_selection);
        }
    }

    pub fn next(&mut self) {
        if self.profiles.is_empty() {
            self.profile_list_state.select(None);
            return;
        }
        let i = match self.profile_list_state.selected() {
            Some(i) => if i >= self.profiles.len() - 1 { 0 } else { i + 1 },
            None => 0,
        };
        self.profile_list_state.select(Some(i));
    }

    pub fn previous(&mut self) {
        if self.profiles.is_empty() {
            self.profile_list_state.select(None);
            return;
        }
        let i = match self.profile_list_state.selected() {
            Some(i) => if i == 0 { self.profiles.len() - 1 } else { i - 1 },
            None => self.profiles.len() - 1,
        };
        self.profile_list_state.select(Some(i));
    }

    pub fn handle_movement(
        &mut self,
        app: &AppState,
        action: MovementAction,
    ) -> bool {
        use AdminFocus::*;

        const ORDER: [AdminFocus; 5] = [
            ProfilesPane,
            Tables,
            Button1,
            Button2,
            Button3,
        ];

        match (self.current_focus, action) {
            (ProfilesPane, MovementAction::Select) => {
                if !app.profile_tree.profiles.is_empty()
                    && self.profile_list_state.selected().is_none()
                {
                    self.profile_list_state.select(Some(0));
                }
                self.current_focus = InsideProfilesList;
                return true;
            }
            (Tables, MovementAction::Select) => {
                let p_idx = self
                    .selected_profile_index
                    .or_else(|| self.profile_list_state.selected());
                if let Some(pi) = p_idx {
                    let len = app
                        .profile_tree
                        .profiles
                        .get(pi)
                        .map(|p| p.tables.len())
                        .unwrap_or(0);
                    if len > 0 && self.table_list_state.selected().is_none() {
                        self.table_list_state.select(Some(0));
                    }
                }
                self.current_focus = InsideTablesList;
                return true;
            }
            _ => {}
        }

        match self.current_focus {
            InsideProfilesList => match action {
                MovementAction::Up => {
                    if !app.profile_tree.profiles.is_empty() {
                        let curr = self.profile_list_state.selected().unwrap_or(0);
                        let next = curr.saturating_sub(1);
                        self.profile_list_state.select(Some(next));
                    }
                    true
                }
                MovementAction::Down => {
                    let len = app.profile_tree.profiles.len();
                    if len > 0 {
                        let curr = self.profile_list_state.selected().unwrap_or(0);
                        let next = if curr + 1 < len { curr + 1 } else { curr };
                        self.profile_list_state.select(Some(next));
                    }
                    true
                }
                MovementAction::Esc => {
                    self.current_focus = ProfilesPane;
                    true
                }
                MovementAction::Next | MovementAction::Previous => true,
                MovementAction::Select => false,
                _ => false,
            },
            InsideTablesList => {
                let tables_len = {
                    let p_idx = self
                        .selected_profile_index
                        .or_else(|| self.profile_list_state.selected());
                    p_idx.and_then(|pi| app.profile_tree.profiles.get(pi))
                        .map(|p| p.tables.len())
                        .unwrap_or(0)
                };
                match action {
                    MovementAction::Up => {
                        if tables_len > 0 {
                            let curr = self.table_list_state.selected().unwrap_or(0);
                            let next = curr.saturating_sub(1);
                            self.table_list_state.select(Some(next));
                        }
                        true
                    }
                    MovementAction::Down => {
                        if tables_len > 0 {
                            let curr = self.table_list_state.selected().unwrap_or(0);
                            let next = if curr + 1 < tables_len { curr + 1 } else { curr };
                            self.table_list_state.select(Some(next));
                        }
                        true
                    }
                    MovementAction::Esc => {
                        self.current_focus = Tables;
                        true
                    }
                    MovementAction::Next | MovementAction::Previous => true,
                    MovementAction::Select => false,
                    _ => false,
                }
            }
            _ => {
                move_focus(&ORDER, &mut self.current_focus, action)
            }
        }
    }
}
