// src/components/auth/login.rs

use crate::{
    config::colors::themes::Theme,
    state::pages::auth::LoginState,
    components::common::dialog,
    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::state::app::highlight::HighlightState;
use canvas::canvas::{render_canvas, HighlightState as CanvasHighlightState}; // Use canvas library's render function

// 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_login(
    f: &mut Frame,
    area: Rect,
    theme: &Theme,
    login_state: &LoginState,
    app_state: &AppState,
    is_edit_mode: bool,
    highlight_state: &HighlightState,
) {
    // Main container
    let block = Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Plain)
        .border_style(Style::default().fg(theme.border))
        .title(" Login ")
        .style(Style::default().bg(theme.bg));

    f.render_widget(block, area);

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

    // Layout chunks
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(4),  // Form (2 fields + padding)
            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);
    render_canvas(
        f,
        chunks[0],
        login_state,        // LoginState implements CanvasState
        theme,              // Theme implements CanvasTheme
        is_edit_mode,
        &canvas_highlight_state,
    );

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

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

    // Login Button
    let login_button_index = 0;
    let login_active = if app_state.ui.focus_outside_canvas {
        app_state.focused_button_index== login_button_index
    } else {
        false
    };
    let mut login_style = Style::default().fg(theme.fg);
    let mut login_border = Style::default().fg(theme.border);
    if login_active {
        login_style = login_style.fg(theme.highlight).add_modifier(Modifier::BOLD);
        login_border = login_border.fg(theme.accent);
    }

    f.render_widget(
        Paragraph::new("Login")
            .style(login_style)
            .alignment(Alignment::Center)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_type(BorderType::Plain)
                    .border_style(login_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],
    );

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