//! Kurtarma modu adımı.
//!
//! Özellikler:
//! - Mevcut Linux kurulumlarını tarar (lsblk)
//! - Seçilen bölümü /mnt'a bağlar
//! - chroot kabuğu başlatır
//! - GRUB'u yeniden yükler
//! - **Pisi paket geçmişini listeler ve `pisi takeback <N>` ile geri alır**

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

/// Pisi geçmişindeki tek bir işlem kaydı.
#[derive(Clone, Debug)]
struct PisiHistoryEntry {
    /// İşlem numarası (takeback argümanı)
    pub op: u32,
    /// Tarih/saat dizisi
    pub date: String,
    /// İşlem türü (install, remove, upgrade, …)
    pub op_type: String,
    /// Etkilenen paket sayısı veya açıklaması
    pub summary: String,
}

/// Pisi geçmiş geri alma modunun durumu.
#[derive(Default)]
struct PisiHistoryState {
    entries: Vec<PisiHistoryEntry>,
    selected: Option<usize>,
    scanned: bool,
    running: bool,
    result_msg: Option<String>,
    result_ok: Option<bool>,
}

#[derive(Default)]
pub struct RescueStep {
    detected: Vec<String>,
    selected: Option<usize>,
    log: Vec<String>,
    mount_done: bool,
    pisi: PisiHistoryState,
    /// Aktif sekme: 0=Chroot/GRUB, 1=Pisi Geçmiş
    tab: usize,
}

impl RescueStep {
    fn detect_installations(&mut self) {
        self.detected.clear();
        self.mount_done = false;
        if let Ok(out) = std::process::Command::new("lsblk")
            .args(["-o", "NAME,FSTYPE,MOUNTPOINT", "-l", "-n"])
            .output()
        {
            let text = String::from_utf8_lossy(&out.stdout);
            for line in text.lines() {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 2 {
                    let fstype = parts[1];
                    if fstype == "ext4" || fstype == "btrfs" || fstype == "xfs" {
                        let dev = format!("/dev/{}", parts[0]);
                        let mp  = parts.get(2).unwrap_or(&"-").to_string();
                        self.detected.push(format!("{}  ({})  [{}]", dev, fstype, mp));
                    }
                }
            }
        }
    }

    /// Seçili bölümü /mnt'a bağlar. Başarılıysa `true` döner.
    fn mount_selected(&mut self) -> bool {
        if let Some(idx) = self.selected {
            if let Some(entry) = self.detected.get(idx) {
                // Entry: "/dev/sda1  (ext4)  [-]" — sadece ilk token aygıt yolu
                let dev = entry.split_whitespace().next().unwrap_or("");
                if dev.is_empty() { return false; }
                // /mnt boşsa bağla
                let r = std::process::Command::new("mount")
                    .args([dev, "/mnt"])
                    .status();
                if let Ok(s) = r {
                    if s.success() {
                        self.mount_done = true;
                        self.log.push(format!("\u{EB7B} {} → /mnt bağlandı.", dev));
                        return true;
                    } else {
                        self.log.push(format!("\u{EA6B} {} bağlanamadı (zaten bağlı veya hata).", dev));
                        self.mount_done = true; // Belki zaten bağlı
                        return true;
                    }
                }
            }
        }
        false
    }

    fn run_rescue_cmd(cmd: &str, args: &[&str]) -> Result<String, String> {
        let out = std::process::Command::new(cmd)
            .args(args)
            .output()
            .map_err(|e| format!("{} hatası: {}", cmd, e))?;
        if out.status.success() {
            Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
        } else {
            Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
        }
    }

    /// `pisi history` çıktısını ayrıştırır.
    /// Örnek satır: "Operation 42 [2024-03-15 12:00:01]: install [vim]"
    fn parse_pisi_history(raw: &str) -> Vec<PisiHistoryEntry> {
        let mut entries = Vec::new();
        for line in raw.lines() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') { continue; }

            // "Operation 42 [2024-03-15 12:00:01]: install [vim, curl]"
            if let Some(rest) = line.strip_prefix("Operation ") {
                let mut parts = rest.splitn(2, ' ');
                let op_str = parts.next().unwrap_or("0");
                let remainder = parts.next().unwrap_or("");

                let op: u32 = op_str.parse().unwrap_or(0);

                // Tarih: "[2024-03-15 12:00:01]"
                let date = if let Some(start) = remainder.find('[') {
                    if let Some(end) = remainder.find(']') {
                        remainder[start+1..end].to_string()
                    } else { String::new() }
                } else { String::new() };

                // Tür + özet: ": install [vim, curl]"
                let (op_type, summary) = if let Some(colon) = remainder.rfind("]: ") {
                    let after = &remainder[colon+3..];
                    if let Some(sp) = after.find(' ') {
                        (after[..sp].to_string(), after[sp+1..].to_string())
                    } else {
                        (after.to_string(), String::new())
                    }
                } else { ("unknown".to_string(), remainder.to_string()) };

                entries.push(PisiHistoryEntry { op, date, op_type, summary });
            }
        }
        // En yeni önce
        entries.sort_by(|a, b| b.op.cmp(&a.op));
        entries
    }

    /// /mnt chroot içinde `pisi history` çalıştırır ve ayrıştırır.
    fn scan_pisi_history(&mut self) {
        self.pisi.entries.clear();
        self.pisi.result_msg = None;
        self.pisi.selected   = None;

        let out = std::process::Command::new("chroot")
            .args(["/mnt", "pisi", "history"])
            .output();

        match out {
            Ok(o) => {
                let text = String::from_utf8_lossy(&o.stdout).to_string();
                let entries = Self::parse_pisi_history(&text);
                if entries.is_empty() {
                    self.pisi.result_msg = Some(t!("rescue_pisi_history_empty").to_string());
                    self.pisi.result_ok  = Some(false);
                }
                self.pisi.entries = entries;
            }
            Err(e) => {
                self.pisi.result_msg = Some(format!("{}", e));
                self.pisi.result_ok  = Some(false);
            }
        }
        self.pisi.scanned = true;
    }

    /// `pisi takeback <op>` çalıştırır.
    fn run_takeback(&mut self, op: u32) {
        self.pisi.running    = true;
        self.pisi.result_msg = Some(t!("rescue_pisi_takeback_start").to_string());
        self.pisi.result_ok  = None;

        let op_str = op.to_string();
        let out = std::process::Command::new("chroot")
            .args(["/mnt", "pisi", "takeback", &op_str])
            .output();

        self.pisi.running = false;
        match out {
            Ok(o) if o.status.success() => {
                self.pisi.result_ok  = Some(true);
                self.pisi.result_msg = Some(t!("rescue_pisi_history_ok").to_string());
                self.log.push(format!("\u{EB7B} pisi takeback {} başarılı.", op));
            }
            Ok(o) => {
                let err = String::from_utf8_lossy(&o.stderr).trim().to_string();
                self.pisi.result_ok  = Some(false);
                self.pisi.result_msg = Some(t!("rescue_pisi_history_err", err = err).to_string());
                self.log.push(format!("\u{EA21} pisi takeback {}: {}", op, err));
            }
            Err(e) => {
                self.pisi.result_ok  = Some(false);
                self.pisi.result_msg = Some(t!("rescue_pisi_history_err", err = e.to_string()).to_string());
            }
        }
    }

    // ─── UI Panelleri ────────────────────────────────────────────────

    fn show_chroot_panel(&mut self, ui: &mut egui::Ui, state: &mut GlobalState) {
        ui.add_space(6.0);

        // Bölüm listesi
        ui.label(egui::RichText::new(t!("rescue_detected")).strong().color(theme::c_text()));
        ui.add_space(4.0);
        egui::ScrollArea::vertical()
            .id_source("rescue_partition_list")
            .max_height(130.0)
            .show(ui, |ui| {
                for (i, entry) in self.detected.iter().enumerate() {
                    let is_selected = self.selected == Some(i);
                    let label = egui::RichText::new(entry)
                        .family(egui::FontFamily::Monospace)
                        .color(if is_selected { theme::c_accent() } else { theme::c_text() });
                    if ui.selectable_label(is_selected, label).clicked() {
                        self.selected = Some(i);
                        self.mount_done = false;
                    }
                }
            });

        ui.add_space(10.0);

        // İşlem butonları
        ui.horizontal(|ui| {
            // 1. Bağla
            let cond = self.selected.is_some() && !self.mount_done;
            let resp = theme::secondary_button(ui, "📂  /mnt'a Bağla");
            if cond && resp.clicked() {
                self.mount_selected();
            }

            // 2. Chroot
            let resp = theme::secondary_button(ui, &t!("rescue_chroot"));
            if self.mount_done && resp.clicked() {
                self.log.push(t!("rescue_chroot_start").to_string());
                match Self::run_rescue_cmd("chroot", &["/mnt", "/bin/bash", "-c", "echo 'chroot OK'"]) {
                    Ok(msg) => self.log.push(format!("\u{EB7B} {}", msg)),
                    Err(e)  => self.log.push(format!("\u{EA21} {}", e)),
                }
            }

            // 3. GRUB yeniden yükle
            let resp = theme::secondary_button(ui, &t!("rescue_grub"));
            if self.mount_done && resp.clicked() {
                self.log.push(t!("rescue_grub_start").to_string());
                let boot_dev = state.bootloader_device.clone();
                let steps: &[(&str, &[&str])] = &[
                    ("mount", &["--bind", "/proc", "/mnt/proc"]),
                    ("mount", &["--bind", "/sys",  "/mnt/sys"]),
                    ("mount", &["--bind", "/dev",  "/mnt/dev"]),
                ];
                for (cmd, args) in steps {
                    match Self::run_rescue_cmd(cmd, args) {
                        Ok(m) if !m.is_empty() => self.log.push(m),
                        Ok(_)  => {},
                        Err(e) => self.log.push(format!("\u{EA6B} {}", e)),
                    }
                }
                // grub2-install
                let grub_args: Vec<&str> = vec!["grub2-install", &boot_dev];
                match Self::run_rescue_cmd("chroot", &{
                    let mut a: Vec<&str> = vec!["/mnt"];
                    a.extend_from_slice(&grub_args);
                    a
                }) {
                    Ok(m)  => self.log.push(format!("\u{EB7B} grub2-install: {}", m)),
                    Err(e) => self.log.push(format!("\u{EA21} grub2-install: {}", e)),
                }
                // grub2-mkconfig
                match Self::run_rescue_cmd("chroot", &["/mnt", "grub2-mkconfig", "-o", "/boot/grub2/grub.cfg"]) {
                    Ok(m)  => self.log.push(format!("\u{EB7B} grub2-mkconfig: {}", m)),
                    Err(e) => self.log.push(format!("\u{EA21} grub2-mkconfig: {}", e)),
                }
            }
        });
    }

    fn show_pisi_panel(&mut self, ui: &mut egui::Ui) {
        ui.add_space(6.0);
        ui.label(
            egui::RichText::new(t!("rescue_pisi_history_desc"))
                .size(12.0)
                .color(theme::c_text_dim()),
        );
        ui.add_space(8.0);

        if !self.mount_done {
            theme::warning_box(ui, "Önce 'Chroot & GRUB' sekmesinden bölümü /mnt'a bağlayın.");
            return;
        }

        // Tara butonu
        ui.horizontal(|ui| {
            if theme::secondary_button(ui, &t!("rescue_pisi_history_scan")).clicked() {
                self.scan_pisi_history();
            }
            if self.pisi.scanned {
                ui.label(
                    egui::RichText::new(format!("{} işlem listelendi", self.pisi.entries.len()))
                        .size(12.0)
                        .color(theme::c_text_dim()),
                );
            }
        });

        if self.pisi.entries.is_empty() {
            if let Some(ref msg) = self.pisi.result_msg.clone() {
                ui.add_space(6.0);
                theme::warning_box(ui, msg);
            }
            return;
        }

        ui.add_space(8.0);

        // Geçmiş tablosu
        egui::ScrollArea::vertical()
            .id_source("pisi_history_scroll")
            .max_height(200.0)
            .show(ui, |ui| {
                egui::Grid::new("pisi_history_grid")
                    .num_columns(4)
                    .spacing([12.0, 4.0])
                    .striped(true)
                    .show(ui, |ui| {
                        // Başlık satırı
                        ui.label(egui::RichText::new("#").strong().color(theme::c_text_dim()));
                        ui.label(egui::RichText::new("Tarih").strong().color(theme::c_text_dim()));
                        ui.label(egui::RichText::new("İşlem").strong().color(theme::c_text_dim()));
                        ui.label(egui::RichText::new("Paketler").strong().color(theme::c_text_dim()));
                        ui.end_row();

                        for (i, entry) in self.pisi.entries.iter().enumerate() {
                            let is_selected = self.pisi.selected == Some(i);
                            let row_color = if is_selected {
                                theme::c_accent()
                            } else {
                                theme::c_text()
                            };

                            let op_label = egui::RichText::new(entry.op.to_string())
                                .family(egui::FontFamily::Monospace)
                                .color(row_color);
                            if ui.selectable_label(is_selected, op_label).clicked() {
                                self.pisi.selected = Some(i);
                            }

                            ui.label(egui::RichText::new(&entry.date).size(11.0).color(row_color));

                            // İşlem türüne renkli badge
                            let type_color = match entry.op_type.as_str() {
                                "install" => egui::Color32::from_rgb(80, 180, 80),
                                "remove"  => egui::Color32::from_rgb(200, 70, 70),
                                "upgrade" => egui::Color32::from_rgb(70, 140, 220),
                                _         => theme::c_text_dim(),
                            };
                            ui.colored_label(type_color, &entry.op_type);

                            // Özet — truncate
                            let summary = if entry.summary.len() > 50 {
                                format!("{}…", &entry.summary[..50])
                            } else {
                                entry.summary.clone()
                            };
                            ui.label(egui::RichText::new(summary).size(11.0).color(theme::c_text_dim()));
                            ui.end_row();
                        }
                    });
            });

        ui.add_space(10.0);

        // Geri al butonu
        let can_takeback = self.pisi.selected.is_some() && !self.pisi.running;
        let resp = theme::primary_button(ui, &t!("rescue_pisi_takeback"));
        if can_takeback && resp.clicked() {
            if let Some(idx) = self.pisi.selected {
                let op = self.pisi.entries[idx].op;
                self.run_takeback(op);
            }
        }

        // Sonuç mesajı
        if let Some(ref msg) = self.pisi.result_msg.clone() {
            ui.add_space(6.0);
            match self.pisi.result_ok {
                Some(true)  => theme::success_box(ui, msg),
                Some(false) => theme::error_box(ui, msg),
                None        => { ui.label(msg); }
            }
        }
    }
}

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

    fn on_enter(&mut self, _state: &mut GlobalState) {
        self.detect_installations();
    }

    fn show(&mut self, ui: &mut egui::Ui, state: &mut GlobalState) {
        theme::section_heading(ui, &t!("rescue_title"));
        ui.label(
            egui::RichText::new(t!("rescue_description"))
                .color(theme::c_text_dim())
                .size(13.0),
        );
        ui.add_space(10.0);

        if self.detected.is_empty() {
            theme::warning_box(ui, &t!("rescue_no_installations"));
            ui.add_space(6.0);
            if theme::secondary_button(ui, &t!("rescue_scan")).clicked() {
                self.detect_installations();
            }
            return;
        }

        // ─── Sekmeler ───────────────────────────────────────────────
        ui.horizontal(|ui| {
            let tab_labels = [
                ("💻  Chroot & GRUB", 0usize),
                ("📜  Pisi Geçmiş", 1usize),
            ];
            for (label, idx) in &tab_labels {
                let active = self.tab == *idx;
                let rt = egui::RichText::new(*label)
                    .strong()
                    .color(if active { theme::c_accent() } else { theme::c_text_dim() });
                if ui.selectable_label(active, rt).clicked() {
                    self.tab = *idx;
                }
                ui.separator();
            }
        });

        ui.separator();
        ui.add_space(4.0);

        match self.tab {
            0 => self.show_chroot_panel(ui, state),
            1 => self.show_pisi_panel(ui),
            _ => {}
        }

        ui.add_space(12.0);

        // Log alanı — her iki sekmede de görünür
        if !self.log.is_empty() {
            ui.separator();
            ui.add_space(4.0);
            ui.label(
                egui::RichText::new("Log")
                    .size(11.0)
                    .color(theme::c_text_dim()),
            );
            egui::ScrollArea::vertical()
                .id_source("rescue_log")
                .max_height(160.0)
                .stick_to_bottom(true)
                .show(ui, |ui| {
                    egui::Frame::group(ui.style())
                        .inner_margin(egui::Margin::same(8.0))
                        .show(ui, |ui| {
                            for line in &self.log {
                                let color = if line.starts_with("\u{EB7B}") {
                                    theme::c_success()
                                } else if line.starts_with("\u{EA21}") {
                                    theme::c_error()
                                } else if line.starts_with("\u{EA6B}") {
                                    theme::c_warning()
                                } else {
                                    theme::c_text_dim()
                                };
                                ui.colored_label(
                                    color,
                                    egui::RichText::new(line)
                                        .size(11.0)
                                        .family(egui::FontFamily::Monospace),
                                );
                            }
                        });
                });
        }

        // Geri dön butonu
        ui.add_space(8.0);
        if theme::secondary_button(ui, &format!("\u{EB7C} {}", t!("rescue_return"))).clicked() {
            state.rescue_mode = false;
        }
    }

    fn is_complete(&self, _state: &GlobalState) -> bool {
        false // Rescue modu her zaman "tamamlanmamış" — normal kuruluma dönmek için rescue_mode=false
    }
}
