// src/components/admin/admin_panel_admin.rs

use crate::config::colors::themes::Theme;
use crate::state::pages::admin::{AdminFocus, AdminState};
use crate::state::app::state::AppState;
use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::Style,
    text::{Line, Span, Text},
    widgets::{Block, BorderType, Borders, List, ListItem, Paragraph},
    Frame,
};

pub fn render_admin_panel_admin(
    f: &mut Frame,
    area: Rect,
    app_state: &AppState,
    admin_state: &mut AdminState,
    theme: &Theme,
) {
    let main_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(0), Constraint::Length(1)].as_ref())
        .split(area);
    let panes_area = main_chunks[0];
    let buttons_area = main_chunks[1];

    let pane_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(25), // Profiles
            Constraint::Percentage(40), // Tables
            Constraint::Percentage(35), // Dependencies
        ].as_ref())
        .split(panes_area);

    let profiles_pane = pane_chunks[0];
    let tables_pane = pane_chunks[1];
    let deps_pane = pane_chunks[2];

    // --- Profiles Pane (Left) ---
    let profile_pane_has_focus = matches!(admin_state.current_focus, AdminFocus::ProfilesPane | AdminFocus::InsideProfilesList);
    let profile_border_style = if profile_pane_has_focus {
        Style::default().fg(theme.highlight)
    } else {
        Style::default().fg(theme.border)
    };
    let profiles_block = Block::default().title(" Profiles ").borders(Borders::ALL).border_type(BorderType::Rounded).border_style(profile_border_style);
    let profiles_inner_area = profiles_block.inner(profiles_pane);
    f.render_widget(profiles_block, profiles_pane);
    let profile_list_items: Vec<ListItem> = app_state.profile_tree.profiles.iter().enumerate().map(|(idx, profile)| {
        let is_persistently_selected = admin_state.selected_profile_index == Some(idx);
        let is_nav_highlighted = admin_state.profile_list_state.selected() == Some(idx) && admin_state.current_focus == AdminFocus::InsideProfilesList;
        let prefix = if is_persistently_selected { "[*] " } else { "[ ] " };
        let item_style = if is_nav_highlighted { Style::default().fg(theme.highlight).add_modifier(ratatui::style::Modifier::BOLD) }
                         else if is_persistently_selected { Style::default().fg(theme.accent) }
                         else { Style::default().fg(theme.fg) };
        ListItem::new(Line::from(vec![Span::styled(prefix, item_style), Span::styled(&profile.name, item_style)]))
    }).collect();
    let profile_list = List::new(profile_list_items)
        .highlight_style(if admin_state.current_focus == AdminFocus::InsideProfilesList { Style::default().add_modifier(ratatui::style::Modifier::REVERSED) } else { Style::default() })
        .highlight_symbol(if admin_state.current_focus == AdminFocus::InsideProfilesList { "> " } else { "  " });
    f.render_stateful_widget(profile_list, profiles_inner_area, &mut admin_state.profile_list_state);


    // --- Tables Pane (Middle) ---
    let table_pane_has_focus = matches!(admin_state.current_focus, AdminFocus::Tables | AdminFocus::InsideTablesList);
    let table_border_style = if table_pane_has_focus { Style::default().fg(theme.highlight) } else { Style::default().fg(theme.border) };
    
    let profile_to_display_tables_for_idx: Option<usize>;
    if admin_state.current_focus == AdminFocus::InsideProfilesList {
        profile_to_display_tables_for_idx = admin_state.profile_list_state.selected();
    } else {
        profile_to_display_tables_for_idx = admin_state.selected_profile_index
            .or_else(|| admin_state.profile_list_state.selected());
    }
    let tables_pane_title_profile_name = profile_to_display_tables_for_idx
        .and_then(|idx| app_state.profile_tree.profiles.get(idx))
        .map_or("None Selected", |p| p.name.as_str());
    let tables_block = Block::default().title(format!(" Tables (Profile: {}) ", tables_pane_title_profile_name)).borders(Borders::ALL).border_type(BorderType::Rounded).border_style(table_border_style);
    let tables_inner_area = tables_block.inner(tables_pane);
    f.render_widget(tables_block, tables_pane);

    let table_list_items_for_display: Vec<ListItem> =
        if let Some(profile_data_for_tables) = profile_to_display_tables_for_idx
            .and_then(|idx| app_state.profile_tree.profiles.get(idx)) {
            profile_data_for_tables.tables.iter().enumerate().map(|(idx, table)| {
                let is_table_persistently_selected = admin_state.selected_table_index == Some(idx) &&
                                                     profile_to_display_tables_for_idx == admin_state.selected_profile_index;
                let is_table_nav_highlighted = admin_state.table_list_state.selected() == Some(idx) &&
                                               admin_state.current_focus == AdminFocus::InsideTablesList;
                let prefix = if is_table_persistently_selected { "[*] " } else { "[ ] " };
                let style = if is_table_nav_highlighted { Style::default().fg(theme.highlight).add_modifier(ratatui::style::Modifier::BOLD) }
                            else if is_table_persistently_selected { Style::default().fg(theme.accent) }
                            else { Style::default().fg(theme.fg) };
                ListItem::new(Line::from(vec![Span::styled(prefix, style), Span::styled(&table.name, style)]))
            }).collect()
        } else {
            vec![ListItem::new("Select a profile to see tables")]
        };
    let table_list = List::new(table_list_items_for_display)
        .highlight_style(if admin_state.current_focus == AdminFocus::InsideTablesList { Style::default().add_modifier(ratatui::style::Modifier::REVERSED) } else { Style::default() })
        .highlight_symbol(if admin_state.current_focus == AdminFocus::InsideTablesList { "> " } else { "  " });
    f.render_stateful_widget(table_list, tables_inner_area, &mut admin_state.table_list_state);


    // --- Dependencies Pane (Right) ---
    let mut deps_pane_title_table_name = "N/A".to_string();
    let dependencies_to_display: Vec<String>;

    if admin_state.current_focus == AdminFocus::InsideTablesList {
        // If navigating tables, show dependencies for the '>' highlighted table.
        // The profile context is `profile_to_display_tables_for_idx` (from Tables pane logic).
        if let Some(p_idx_for_current_tables) = profile_to_display_tables_for_idx {
            if let Some(current_profile_showing_tables) = app_state.profile_tree.profiles.get(p_idx_for_current_tables) {
                if let Some(table_nav_idx) = admin_state.table_list_state.selected() { // The '>' highlighted table
                    if let Some(navigated_table) = current_profile_showing_tables.tables.get(table_nav_idx) {
                        deps_pane_title_table_name = navigated_table.name.clone();
                        dependencies_to_display = navigated_table.depends_on.clone();
                    } else {
                        dependencies_to_display = Vec::new(); // Navigated table index out of bounds
                    }
                } else {
                    dependencies_to_display = Vec::new(); // No table navigated with '>'
                }
            } else {
                dependencies_to_display = Vec::new(); // Profile for tables out of bounds
            }
        } else {
            dependencies_to_display = Vec::new(); // No profile active for table display
        }
    } else {
        // Otherwise, show dependencies for the '[*]' persistently selected table & profile.
        if let Some(p_idx) = admin_state.selected_profile_index { // Must be a persistently selected profile
            if let Some(selected_profile) = app_state.profile_tree.profiles.get(p_idx) {
                if let Some(t_idx) = admin_state.selected_table_index { // Must be a persistently selected table
                    if let Some(selected_table) = selected_profile.tables.get(t_idx) {
                        deps_pane_title_table_name = selected_table.name.clone();
                        dependencies_to_display = selected_table.depends_on.clone();
                    } else { dependencies_to_display = Vec::new(); }
                } else { dependencies_to_display = Vec::new(); }
            } else { dependencies_to_display = Vec::new(); }
        } else { dependencies_to_display = Vec::new(); }
    }

    let deps_block = Block::default()
        .title(format!(" Dependencies (Table: {}) ", deps_pane_title_table_name))
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(Style::default().fg(theme.border));
    let deps_inner_area = deps_block.inner(deps_pane);
    f.render_widget(deps_block, deps_pane);

    let mut deps_content = Text::default();
    deps_content.lines.push(Line::from(Span::styled(
                "Depends On:",
                Style::default().fg(theme.accent),
    )));

    if !dependencies_to_display.is_empty() {
        for dep in dependencies_to_display {
            deps_content.lines.push(Line::from(Span::styled(format!("- {}", dep), theme.fg)));
        }
    } else {
        deps_content.lines.push(Line::from(Span::styled("  None", theme.secondary)));
    }
    let deps_paragraph = Paragraph::new(deps_content);
    f.render_widget(deps_paragraph, deps_inner_area);

    // --- Buttons Row ---
    let button_chunks = Layout::default().direction(Direction::Horizontal).constraints([Constraint::Percentage(33), Constraint::Percentage(34), Constraint::Percentage(33)].as_ref()).split(buttons_area);
    let btn_base_style = Style::default().fg(theme.secondary);
    let get_btn_style = |button_focus: AdminFocus| { if admin_state.current_focus == button_focus { btn_base_style.add_modifier(ratatui::style::Modifier::REVERSED) } else { btn_base_style } };
    let btn1 = Paragraph::new("Add Logic").style(get_btn_style(AdminFocus::Button1)).alignment(Alignment::Center);
    let btn2 = Paragraph::new("Add Table").style(get_btn_style(AdminFocus::Button2)).alignment(Alignment::Center);
    let btn3 = Paragraph::new("Change Table").style(get_btn_style(AdminFocus::Button3)).alignment(Alignment::Center);
    f.render_widget(btn1, button_chunks[0]);
    f.render_widget(btn2, button_chunks[1]);
    f.render_widget(btn3, button_chunks[2]);
}
