use crate::app::App;
use crate::workspace::MOUNT;
use rune::{ClipboardContent, FileDialogOptions, Tx};
use std::path::Path;
use std::process::Command;

const IMAGES: [&str; 6] = ["png", "jpg", "jpeg", "gif", "webp", "svg"];
const VIDEOS: [&str; 4] = ["mp4", "webm", "mov", "mkv"];
const GRAPH: &str = "\n```mermaid\ngraph LR\n  idea --> plan --> build\n```\n";

impl App {
    pub fn insert(&mut self, stem: &str, text: &str) {
        if let Some(e) = self.editor_mut(stem) {
            e.edit.insert(text);
            e.edit.focused = true;
        }
    }

    pub fn wrap(&mut self, stem: &str, mark: &str) {
        let Some(e) = self.editor_mut(stem) else {
            return;
        };
        let inner = e.edit.selected().to_string();
        e.edit.insert(&format!("{mark}{inner}{mark}"));
        e.edit.focused = true;
    }

    pub fn heading(&mut self, stem: &str) {
        let Some(e) = self.editor_mut(stem) else {
            return;
        };
        let (a, _) = e.edit.range();
        let start = e.edit.text[..a].rfind('\n').map_or(0, |i| i + 1);
        e.edit.set_caret(start);
        e.edit.insert("## ");
        e.edit.focused = true;
    }

    pub fn graph(&mut self, stem: &str) {
        self.insert(stem, GRAPH);
    }

    pub fn paste(&mut self, stem: &str, content: &ClipboardContent) -> bool {
        if let Some(img) = content.image() {
            return match self.save_asset("pasted.png", img.png()) {
                Some(rel) => {
                    self.insert(stem, &format!("![pasted image]({rel})"));
                    true
                }
                None => false,
            };
        }
        let Some(md) = content.html().and_then(|h| htmd::convert(h).ok()) else {
            return false;
        };
        let md = md.trim();
        if md.is_empty() || md == content.text().trim() {
            return false;
        }
        self.insert(stem, md);
        true
    }

    pub fn pick_media(&mut self, stem: &str, video: bool, tx: &mut Tx) {
        let (name, exts): (&str, &[&str]) = if video {
            ("Videos", &VIDEOS)
        } else {
            ("Images", &IMAGES)
        };
        let opts = FileDialogOptions {
            title: format!("Embed {}", name.to_lowercase()),
            ..Default::default()
        }
        .filter(name, exts);
        let stem = stem.to_string();
        tx.open_file(opts, move |s: &mut App, r, _| match r {
            Ok(Some(path)) => s.embed(&stem, &path, video),
            Ok(None) => {}
            Err(e) => s.fail(e.to_string()),
        });
    }

    fn embed(&mut self, stem: &str, path: &Path, video: bool) {
        let name = path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        let Some(rel) = std::fs::read(path)
            .ok()
            .and_then(|b| self.save_asset(&name, &b))
        else {
            return self.fail(format!("could not copy {name} into the assets folder"));
        };
        let md = match (video, self.poster(&rel)) {
            (false, _) => format!("![{name}]({rel})"),
            (true, Some(poster)) => format!("[![▶ {name}]({poster})]({rel})"),
            (true, None) => format!("[▶ {name}]({rel})"),
        };
        self.insert(stem, &md);
    }

    fn poster(&self, rel: &str) -> Option<String> {
        let ws = self.ws.as_ref()?;
        let out = format!("{rel}.poster.png");
        let ok = Command::new("ffmpeg")
            .args(["-y", "-loglevel", "error", "-i"])
            .arg(ws.resolve(rel))
            .args(["-frames:v", "1", "-vf", "scale=640:-2"])
            .arg(ws.resolve(&out))
            .status()
            .is_ok_and(|s| s.success());
        ok.then_some(out)
    }

    fn save_asset(&self, name: &str, bytes: &[u8]) -> Option<String> {
        let ws = self.ws.as_ref()?;
        let stamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_millis());
        let rel = format!("{MOUNT}/assets/{stamp}-{}", name.replace(' ', "-"));
        let path = ws.resolve(&rel);
        std::fs::create_dir_all(path.parent()?).ok()?;
        std::fs::write(&path, bytes).ok()?;
        Some(rel)
    }

    pub fn open_link(&mut self, url: &str) {
        let target = match (&self.ws, url.contains("://")) {
            (Some(ws), false) => ws.resolve(url).display().to_string(),
            _ => url.to_string(),
        };
        if Command::new("xdg-open").arg(target).spawn().is_err() {
            self.fail("xdg-open is not available");
        }
    }
}
