use ratatui::{
    Frame,
    layout::{Alignment, Constraint, Direction, Layout},
    style::{Color, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph, Wrap},
};

use crate::core::Result;
use crate::core::store::Store;

/// The password authentication screen state.
pub struct AuthScreen {
    /// The password entered by the user.
    pub password: String,
    /// An optional error message to display.
    pub error: Option<String>,
}

impl AuthScreen {
    /// Creates a new AuthScreen with empty password and no error.
    pub fn new() -> Self {
        Self {
            password: String::new(),
            error: None,
        }
    }

    /// Handles a character input: appends to password on normal chars,
    /// attempts authentication on newline. Returns true on successful auth.
    pub fn handle_input(&mut self, c: char, store: &Store) -> Result<bool> {
        if c == '\n' {
            if !store.has_encrypted() {
                self.error = Some("vault 尚未初始化。请先运行 closure init。".to_string());
                self.password.clear();
                return Ok(false);
            }
            match store.authenticate(&self.password) {
                Ok(_) => return Ok(true),
                Err(e) => {
                    self.error = Some(e.to_string());
                    self.password.clear();
                }
            }
        } else {
            self.password.push(c);
        }
        Ok(false)
    }

    /// Removes the last character from the password buffer.
    pub fn handle_backspace(&mut self) {
        self.password.pop();
    }
}

/// Draws the authentication screen with a centered password input dialog.
pub fn draw(frame: &mut Frame, screen: &AuthScreen) {
    let area = frame.area();
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(0), Constraint::Length(1)])
        .split(area);

    let main = chunks[0];
    let footer = chunks[1];

    let popup_area = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage(40),
            Constraint::Length(7),
            Constraint::Percentage(40),
        ])
        .split(main)[1];

    let popup = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(30),
            Constraint::Percentage(40),
            Constraint::Percentage(30),
        ])
        .split(popup_area)[1];

    frame.render_widget(Clear, popup);

    let password_masked: String = screen.password.chars().map(|_| '*').collect();
    let mut text = format!("Password:\n{}", password_masked);
    if let Some(ref err) = screen.error {
        text.push_str(&format!("\n\n{}", err));
    }

    let paragraph = Paragraph::new(text)
        .block(
            Block::default()
                .title("可露希尔 · 接入管理终端")
                .borders(Borders::ALL),
        )
        .alignment(Alignment::Left)
        .wrap(Wrap { trim: true });

    frame.render_widget(paragraph, popup);

    let footer_text = Line::from(Span::styled(
        "罗德岛工程部 v0.1  |  Esc 退出",
        Style::default().fg(Color::DarkGray),
    ));
    frame.render_widget(footer_text, footer);
}
