use crate::screenshot::take_area_screenshot;
use crate::state::SharedWatcherState;
use crate::utils::process_png_file;
use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher};
use std::path::PathBuf;
use std::sync::mpsc::channel;
use tauri::AppHandle;

// TODO: we might be able to delete this soon.

#[tauri::command]
pub async fn handle_selected_folder(
    path: String,
    state: tauri::State<'_, SharedWatcherState>,
    app: AppHandle,
) -> Result<String, String> {
    let path_buf = PathBuf::from(&path);

    if !path_buf.exists() || !path_buf.is_dir() {
        return Err("Invalid directory path".to_string());
    }

    // Stop existing watcher if any
    let mut state = state
        .lock()
        .map_err(|_| "Failed to lock state".to_string())?;
    state.clear_watcher();

    // Create a channel to receive file system events
    let (tx, rx) = channel();

    // Create a new watcher
    let mut watcher = RecommendedWatcher::new(tx, Config::default())
        .map_err(|e| format!("Failed to create watcher: {}", e))?;

    // Start watching the directory
    watcher
        .watch(path_buf.as_ref(), RecursiveMode::Recursive)
        .map_err(|e| format!("Failed to watch directory: {}", e))?;

    // Store the watcher in state
    state.set_watcher(watcher);

    let path_clone = path.clone();
    let app_clone = app.clone();
    tokio::spawn(async move {
        println!("Starting to watch directory: {}", path_clone);
        for res in rx {
            match res {
                Ok(event) => {
                    println!("Received event: {:?}", event);
                    match event.kind {
                        notify::EventKind::Create(_) | notify::EventKind::Modify(_) => {
                            for path in event.paths {
                                println!("Processing path: {}", path.display());
                                if let Some(extension) = path.extension() {
                                    if extension.to_string_lossy().to_lowercase() == "png" {
                                        if let Err(e) = process_png_file(&path, app_clone.clone()) {
                                            eprintln!("Error processing PNG file: {}", e);
                                        }
                                    }
                                }
                            }
                        }
                        _ => {}
                    }
                }
                Err(e) => eprintln!("Watch error: {:?}", e),
            }
        }
    });

    Ok(format!("Now watching directory: {}", path))
}

#[tauri::command]
pub fn take_screenshot(app: AppHandle) -> Result<String, String> {
    take_area_screenshot(&app)
}
