use eframe::egui;
use crate::ui::theme::Theme;

pub struct ChatMessage {
    pub author: String,
    pub body: String,
    pub timestamp: String,
}

pub struct ChatView {
    pub messages: Vec<ChatMessage>,
    pub input: String,
}

impl ChatView {
    pub fn new() -> Self {
        Self {
            messages: vec![
                ChatMessage {
                    author: "System".into(),
                    body: "Secure connection established.".into(),
                    timestamp: "12:00".into(),
                },
            ],
            input: String::new(),
        }
    }

    pub fn show(&mut self, ui: &mut egui::Ui, channel_name: &str) {
        ui.vertical(|ui| {
            // Header
            ui.add_space(8.0);
            ui.horizontal(|ui| {
                ui.label(egui::RichText::new("#").size(18.0).color(Theme::TEXT_DIM));
                ui.label(
                    egui::RichText::new(channel_name)
                        .size(16.0)
                        .strong()
                        .color(Theme::TEXT_PRIMARY),
                );
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    ui.label(egui::RichText::new("Online: 12").size(12.0).color(Theme::TEXT_DIM));
                });
            });
            ui.add_space(8.0);
            ui.separator();

            // Messages Area
            let available_height = ui.available_height() - 60.0;
            egui::ScrollArea::vertical()
                .auto_shrink([false, false])
                .max_height(available_height)
                .stick_to_bottom(true)
                .show(ui, |ui| {
                    ui.add_space(8.0);
                    for msg in &self.messages {
                        self.draw_message(ui, msg);
                    }
                });

            ui.add_space(ui.available_height() - 60.0); // Simple replacement for spacer

            // Input Area
            ui.horizontal(|ui| {
                let text_edit = egui::TextEdit::singleline(&mut self.input)
                    .hint_text("Message # ".to_owned() + channel_name)
                    .margin(egui::Margin::symmetric(12, 8))
                    .desired_width(f32::INFINITY);

                let response = ui.add(text_edit);

                if (response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) || ui.button("󰒍").clicked() {
                    let text = self.input.trim().to_string();
                    if !text.is_empty() {
                        self.messages.push(ChatMessage {
                            author: "You".into(),
                            body: text,
                            timestamp: "Now".into(),
                        });
                        self.input.clear();
                    }
                    response.request_focus();
                }
            });
            ui.add_space(8.0);
        });
    }

    fn draw_message(&self, ui: &mut egui::Ui, msg: &ChatMessage) {
        ui.horizontal_top(|ui| {
            let initial = msg.author.chars().next().unwrap_or('?');
            let avatar_color = if msg.author == "System" { Theme::TEXT_DIM } else { Theme::ACCENT_VIBRANT };
            
            // Avatar
            let (rect, _response) = ui.allocate_exact_size(egui::vec2(32.0, 32.0), egui::Sense::hover());
            ui.painter().circle_filled(rect.center(), 16.0, avatar_color.linear_multiply(0.2));
            ui.painter().text(
                rect.center(),
                egui::Align2::CENTER_CENTER,
                initial.to_string(),
                egui::FontId::proportional(14.0),
                avatar_color,
            );

            ui.add_space(8.0);

            ui.vertical(|ui| {
                ui.horizontal(|ui| {
                    ui.label(egui::RichText::new(&msg.author).strong().size(13.0).color(Theme::TEXT_PRIMARY));
                    ui.add_space(4.0);
                    ui.label(egui::RichText::new(&msg.timestamp).size(10.0).color(Theme::TEXT_DIM));
                });
                ui.label(egui::RichText::new(&msg.body).size(13.0).color(Theme::TEXT_PRIMARY));
            });
        });
        ui.add_space(12.0);
    }
}
