// src/components/auth/register.rs

use crate::{
    config::colors::themes::Theme,
    state::pages::auth::RegisterState,
    components::common::dialog,
    state::app::state::AppState,
    modes::handlers::mode_manager::AppMode,
};
use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Rect, Margin},
    style::{Style, Modifier, Color},
    widgets::{Block, BorderType, Borders, Paragraph},
    Frame,
};
use crate::state::app::highlight::HighlightState;
use canvas::canvas::{render_canvas, HighlightState as CanvasHighlightState}; // Use canvas library's render function
use canvas::autocomplete::gui::render_autocomplete_dropdown;
use canvas::autocomplete::AutocompleteCanvasState;

// Helper function to convert between HighlightState types
fn convert_highlight_state(local: &HighlightState) -> CanvasHighlightState {
    match local {
        HighlightState::Off => CanvasHighlightState::Off,
        HighlightState::Characterwise { anchor } => CanvasHighlightState::Characterwise { anchor: *anchor },
        HighlightState::Linewise { anchor_line } => CanvasHighlightState::Linewise { anchor_line: *anchor_line },
    }
}

pub fn render_register(
    f: &mut Frame,
    area: Rect,
    theme: &Theme,
    state: &RegisterState,
    app_state: &AppState,
    is_edit_mode: bool,
    highlight_state: &HighlightState,
) {
    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);

    // --- FORM RENDERING (Using canvas library directly) ---
    let canvas_highlight_state = convert_highlight_state(highlight_state);
    let input_rect = render_canvas(
        f,
        chunks[0],
        state,              // RegisterState implements CanvasState
        theme,              // Theme implements CanvasTheme
        is_edit_mode,
        &canvas_highlight_state,
    );

    // --- 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 = if app_state.ui.focus_outside_canvas {
        app_state.focused_button_index== register_button_index
    } else {
        false
    };
    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 = if app_state.ui.focus_outside_canvas {
        app_state.focused_button_index== return_button_index
    } else {
        false
    };
    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],
    );

    // --- AUTOCOMPLETE DROPDOWN (Using canvas library directly) ---
    if app_state.current_mode == AppMode::Edit {
        if let Some(autocomplete_state) = state.autocomplete_state() {
            if let Some(input_rect) = input_rect {
                render_autocomplete_dropdown(
                    f,
                    f.area(),        // Frame area
                    input_rect,      // Current input field rect
                    theme,           // Theme implements CanvasTheme
                    autocomplete_state,
                );
            }
        }
    }

    // --- 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,
        );
    }
}
