// src/pages/register/ui.rs

use crate::{
    config::colors::themes::Theme,
    state::app::state::AppState,
};
use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Rect, Margin},
    style::{Style, Modifier, Color},
    widgets::{Block, BorderType, Borders, Paragraph},
    Frame,
};
use crate::dialog;
use crate::pages::register::RegisterFormState;
use crate::pages::register::suggestions::RoleSuggestionsProvider;
use tokio::runtime::Handle;
use canvas::{render_canvas, render_suggestions_dropdown, DefaultCanvasTheme};
use canvas::SuggestionsProvider;

pub fn render_register(
    f: &mut Frame,
    area: Rect,
    theme: &Theme,
    register_page: &RegisterFormState,
    app_state: &AppState,
) {
    let state = &register_page.state;
    let editor = &register_page.editor;

    // Outer block
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Plain)
        .border_style(Style::default().fg(theme.border))
        .title(" Register ")
        .style(Style::default().bg(theme.bg));

    f.render_widget(block, area);

    let inner_area = area.inner(Margin {
        horizontal: 1,
        vertical: 1,
    });

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(7), // Form (5 fields + padding)
            Constraint::Length(1), // Help text line
            Constraint::Length(1), // Error message
            Constraint::Length(3), // Buttons
        ])
        .split(inner_area);

    // Render the form canvas
    let input_rect = render_canvas(f, chunks[0], editor, theme);


    // --- HELP TEXT ---
    let help_text = Paragraph::new("* are optional fields")
        .style(Style::default().fg(theme.fg))
        .alignment(Alignment::Center);
    f.render_widget(help_text, chunks[1]);

    // --- ERROR MESSAGE ---
    if let Some(err) = &state.error_message {
        f.render_widget(
            Paragraph::new(err.as_str())
                .style(Style::default().fg(Color::Red))
                .alignment(Alignment::Center),
            chunks[2],
        );
    }

    // --- BUTTONS ---
    let button_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
        .split(chunks[3]);

    // Register Button
    let register_button_index = 0;
    let register_active = app_state.ui.focus_outside_canvas
        && app_state.focused_button_index == register_button_index;
    let mut register_style = Style::default().fg(theme.fg);
    let mut register_border = Style::default().fg(theme.border);
    if register_active {
        register_style = register_style.fg(theme.highlight).add_modifier(Modifier::BOLD);
        register_border = register_border.fg(theme.accent);
    }

    f.render_widget(
        Paragraph::new("Register")
            .style(register_style)
            .alignment(Alignment::Center)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(BorderType::Plain)
                    .border_style(register_border),
            ),
        button_chunks[0],
    );

    // Return Button
    let return_button_index = 1;
    let return_active = app_state.ui.focus_outside_canvas
        && app_state.focused_button_index == return_button_index;
    let mut return_style = Style::default().fg(theme.fg);
    let mut return_border = Style::default().fg(theme.border);
    if return_active {
        return_style = return_style.fg(theme.highlight).add_modifier(Modifier::BOLD);
        return_border = return_border.fg(theme.accent);
    }

    f.render_widget(
        Paragraph::new("Return")
            .style(return_style)
            .alignment(Alignment::Center)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(BorderType::Plain)
                    .border_style(return_border),
            ),
        button_chunks[1],
    );

    // --- DIALOG ---
    if app_state.ui.dialog.dialog_show {
        dialog::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 suggestions dropdown if active (library GUI)
    if editor.mode() == canvas::AppMode::Edit {
        if let Some(input_rect) = input_rect {
            render_suggestions_dropdown(
                f,
                f.area(),
                input_rect,
                &DefaultCanvasTheme,
                editor,
            );
        }
    }
}
