// src/ui/handlers/render.rs

use crate::components::{
    admin::add_logic::render_add_logic,
    admin::render_add_table,
    render_background,
};
use crate::pages::login::render_login;
use crate::pages::register::render_register;
use crate::pages::intro::render_intro;
use crate::bottom_panel::{
    command_line::render_command_line,
    status_line::render_status_line,
    find_file_palette,
};
use crate::sidebar::{calculate_sidebar_layout, render_sidebar};
use crate::buffer::render_buffer_list;
use crate::search::render_search_palette;
use crate::config::colors::themes::Theme;
use crate::modes::general::command_navigation::NavigationState;
use crate::buffer::state::BufferState;
use crate::state::app::state::AppState;
use crate::state::pages::auth::AuthState;
use crate::bottom_panel::layout::{bottom_panel_constraints, render_bottom_panel};
use canvas::FormEditor;
use ratatui::{
    layout::{Constraint, Direction, Layout},
    Frame,
};
use crate::pages::routing::{Router, Page};
use crate::dialog::render_dialog;
use crate::pages::forms::render_form_page;

pub fn render_ui(
    f: &mut Frame,
    router: &mut Router,
    buffer_state: &BufferState,
    theme: &Theme,
    event_handler_command_input: &str,
    event_handler_command_mode_active: bool,
    event_handler_command_message: &str,
    navigation_state: &NavigationState,
    current_dir: &str,
    current_fps: f64,
    app_state: &AppState,
    auth_state: &AuthState,
) {
    render_background(f, f.area(), theme);

    // Layout: optional buffer list + main content + bottom panel
    let mut main_layout_constraints = vec![Constraint::Min(1)];
    if app_state.ui.show_buffer_list {
        main_layout_constraints.insert(0, Constraint::Length(1));
    }
    main_layout_constraints.extend(bottom_panel_constraints(
        app_state,
        navigation_state,
        event_handler_command_mode_active,
    ));

    let root_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints(main_layout_constraints)
        .split(f.area());

    let mut chunk_idx = 0;
    let buffer_list_area = if app_state.ui.show_buffer_list {
        let area = Some(root_chunks[chunk_idx]);
        chunk_idx += 1;
        area
    } else {
        None
    };

    let main_content_area = root_chunks[chunk_idx];
    chunk_idx += 1;

    // Page rendering is now fully router-driven
    match &mut router.current {
        Page::Intro(state) => render_intro(f, state, main_content_area, theme),
        Page::Login(page) => render_login(
            f,
            main_content_area,
            theme,
            page,
            app_state,
        ),
        Page::Register(state) => render_register(
            f,
            main_content_area,
            theme,
            state,
            app_state,
        ),
        Page::Admin(state) => crate::pages::admin::main::ui::render_admin_panel(
            f,
            app_state,
            auth_state,
            state,
            main_content_area,
            theme,
            &app_state.profile_tree,
            &app_state.selected_profile,
        ),
        Page::AddLogic(state) => render_add_logic(
            f,
            main_content_area,
            theme,
            app_state,
            state,
        ),
        Page::AddTable(state) => render_add_table(
            f,
            main_content_area,
            theme,
            app_state,
            state,
        ),
        Page::Form(path) => {
            let (sidebar_area, form_actual_area) =
                calculate_sidebar_layout(app_state.ui.show_sidebar, main_content_area);
            if let Some(sidebar_rect) = sidebar_area {
                render_sidebar(
                    f,
                    sidebar_rect,
                    theme,
                    &app_state.profile_tree,
                    &app_state.selected_profile,
                );
            }
            let available_width = form_actual_area.width;
            let form_render_area = if available_width >= 80 {
                Layout::default()
                    .direction(Direction::Horizontal)
                    .constraints([Constraint::Min(0), Constraint::Length(80), Constraint::Min(0)])
                    .split(form_actual_area)[1]
            } else {
                Layout::default()
                    .direction(Direction::Horizontal)
                    .constraints([
                        Constraint::Min(0),
                        Constraint::Length(available_width),
                        Constraint::Min(0),
                    ])
                    .split(form_actual_area)[1]
            };

            if let Some(editor) = app_state.editor_for_path_ref(path) {
                let (total_count, current_position) =
                    if let Some(fs) = app_state.form_state_for_path_ref(path) {
                        (fs.total_count, fs.current_position)
                    } else {
                        (0, 1)
                    };
                let table_name = path.split('/').nth(1).unwrap_or("");

                render_form_page(
                    f,
                    form_render_area,
                    editor,
                    table_name,
                    theme,
                    total_count,
                    current_position,
                );
            }
        }
    }

    // Global overlays (not tied to a page)
    if let Some(area) = buffer_list_area {
        render_buffer_list(f, area, theme, buffer_state, app_state);
    }

    if app_state.ui.show_search_palette {
        if let Some(search_state) = &app_state.search_state {
            render_search_palette(f, f.area(), theme, search_state);
        }
    } else if app_state.ui.dialog.dialog_show {
        render_dialog(
            f,
            f.area(),
            theme,
            &app_state.ui.dialog.dialog_title,
            &app_state.ui.dialog.dialog_message,
            &app_state.ui.dialog.dialog_buttons,
            app_state.ui.dialog.dialog_active_button_index,
            app_state.ui.dialog.is_loading,
        );
    }

    render_bottom_panel(
        f,
        &root_chunks,
        &mut chunk_idx,
        current_dir,
        theme,
        current_fps,
        app_state,
        router,
        navigation_state,
        event_handler_command_input,
        event_handler_command_mode_active,
        event_handler_command_message,
    );
}
