use eframe::egui;
use rust_i18n::t;
use crate::installer::{GlobalState, InstallerStep};

/// Kurulumdan önce kullanıcının tüm seçimlerini gösteren özet ekranı.
/// Calamares'in Summary modülüne karşılık gelir.
pub struct SummaryStep;

impl InstallerStep for SummaryStep {
    fn name(&self) -> String {
        t!("summary").to_string()
    }

    fn show(&mut self, ui: &mut egui::Ui, state: &mut GlobalState) {
        ui.heading(t!("summary_title"));
        ui.label(t!("summary_description"));

        ui.add_space(12.0);

        egui::Frame::group(ui.style()).show(ui, |ui| {
            ui.set_width(ui.available_width());

            egui::Grid::new("summary_grid")
                .num_columns(2)
                .spacing([20.0, 8.0])
                .striped(true)
                .show(ui, |ui| {
                    summary_row(ui, t!("summary_language"), &state.language);
                    summary_row(ui, t!("summary_timezone"), &state.timezone);

                    let kb = if state.keyboard_variant.is_empty() {
                        state.keyboard_layout.clone()
                    } else {
                        format!("{} ({})", state.keyboard_layout, state.keyboard_variant)
                    };
                    summary_row(ui, t!("summary_keyboard"), &kb);

                    let disk_str = match &state.selected_disk {
                        Some(d) => {
                            if state.erase_disk {
                                format!("{} — {}", d, t!("summary_erase_mode"))
                            } else {
                                format!("{} — {}", d, t!("summary_manual_mode"))
                            }
                        }
                        None => t!("summary_not_selected").to_string(),
                    };
                    summary_row(ui, t!("summary_disk"), &disk_str);

                    // Bölüm planı detayları
                    if state.erase_disk {
                        if let Some(ref plan) = state.partition_plan {
                            let plan_str = if plan.efi_mb > 0 {
                                format!("EFI {}MB  |  swap {}MB  |  / {:.1}GB  ({})",
                                    plan.efi_mb, plan.swap_mb,
                                    plan.root_mb as f64 / 1024.0,
                                    plan.table_type)
                            } else {
                                format!("swap {}MB  |  / {:.1}GB  ({})",
                                    plan.swap_mb,
                                    plan.root_mb as f64 / 1024.0,
                                    plan.table_type)
                            };
                            summary_row(ui, t!("summary_partition_plan"), &plan_str);
                        }
                    } else if !state.custom_partitions.is_empty() {
                        let mut plan_lines = Vec::new();
                        for part in &state.custom_partitions {
                            let size_str = if part.size_mb == 0 {
                                t!("mp_size_remaining").to_string()
                            } else if part.size_mb >= 1024 {
                                format!("{:.1} GB", part.size_mb as f64 / 1024.0)
                            } else {
                                format!("{} MB", part.size_mb)
                            };
                            plan_lines.push(format!("{}  ➔  {}  ({}, {})", part.device, part.mountpoint, part.fstype, size_str));
                        }
                        summary_row(ui, t!("summary_custom_partitions"), &plan_lines.join("\n"));
                    }

                    // Tarih/Saat
                    let dt_str = if state.use_ntp {
                        t!("summary_ntp_enabled").to_string()
                    } else {
                        format!("{:04}-{:02}-{:02} {:02}:{:02} (NTP off)",
                            state.manual_year, state.manual_month, state.manual_day,
                            state.manual_hour, state.manual_minute)
                    };
                    summary_row(ui, t!("summary_datetime"), &dt_str);

                    // Bootloader
                    let bl_str = format!("{} ({}s timeout{})",
                        state.bootloader_device,
                        state.bootloader_timeout,
                        if state.bootloader_password.is_empty() { "" } else { ", password protected" }
                    );
                    summary_row(ui, t!("summary_bootloader"), &bl_str);

                    // Display Manager
                    let dm_str = format!("{} / {} ({})",
                        state.display_manager,
                        state.desktop_environment,
                        if state.autologin { t!("summary_autologin") } else { std::borrow::Cow::Borrowed("manual login") }
                    );
                    summary_row(ui, t!("summary_display_manager"), &dm_str);

                    let root_str = if state.root_password.is_empty() {
                        t!("summary_root_disabled").to_string()
                    } else {
                        t!("summary_root_enabled").to_string()
                    };
                    summary_row(ui, t!("summary_root"), &root_str);

                    summary_row(ui, t!("summary_username"), &state.username);
                    summary_row(ui, t!("summary_hostname"), &state.hostname);
                });
        });

        ui.add_space(16.0);

        // Uyarı kutusu
        egui::Frame::none()
            .fill(egui::Color32::from_rgba_unmultiplied(200, 60, 40, 30))
            .rounding(6.0)
            .inner_margin(egui::Margin::same(10.0))
            .show(ui, |ui| {
                ui.colored_label(
                    egui::Color32::from_rgb(180, 60, 40),
                    t!("summary_warning"),
                );
            });
    }

    fn is_complete(&self, _state: &GlobalState) -> bool {
        // Özet her zaman geçerlidir; önceki adımlar bunu garantiler.
        true
    }
}

fn summary_row(ui: &mut egui::Ui, label: impl Into<String>, value: &str) {
    ui.label(egui::RichText::new(label.into()).strong().color(crate::ui::theme::c_text()));
    ui.label(egui::RichText::new(value).color(crate::ui::theme::c_text()));
    ui.end_row();
}
