use anyhow::Result;
use clap::Subcommand;

#[derive(Subcommand)]
pub enum NotebookCommands {
    /// List all notebooks (optionally filtered by workspace)
    #[clap(visible_alias("ls"))]
    List {
        /// Workspace selector (slug or ID) to filter notebooks
        #[arg(value_name = "WORKSPACE")]
        workspace: Option<String>,
    },
    /// Create a new notebook
    Create {
        /// Notebook name
        #[arg(value_name = "NAME")]
        name: String,
        /// Workspace selector (slug or ID)
        #[arg(long = "workspace", short = 'w')]
        workspace: String,
    },
    /// Rename a notebook
    Rename {
        /// Notebook selector (@notebook[workspace/notebook]) or notebook ID
        #[arg(value_name = "SELECTOR")]
        selector: String,
        /// New notebook name
        #[arg(value_name = "NEW_NAME")]
        new_name: String,
    },
    /// Delete a notebook
    Delete {
        /// Notebook selector (@notebook[workspace/notebook]) or notebook ID
        #[arg(value_name = "SELECTOR")]
        selector: String,
    },
}

pub async fn handle_list(token: &str, workspace_selector: &Option<String>) -> Result<()> {
    use crate::services::{notebooks_service, workspaces_service};

    let enriched_notebooks = notebooks_service::list_enriched_notebooks(token).await?;

    let filtered_notebooks: Vec<_> = if let Some(ws_selector) = workspace_selector {
        let workspace_id = workspaces_service::resolve_workspace_id(token, ws_selector).await?;
        enriched_notebooks
            .into_iter()
            .filter(|item| item.notebook.workspace_id == workspace_id)
            .collect()
    } else {
        enriched_notebooks
    };

    if filtered_notebooks.is_empty() {
        if workspace_selector.is_some() {
            println!("No notebooks found in the specified workspace.");
        } else {
            println!("No notebooks found.");
        }
    } else {
        println!("Notebooks:");
        println!(
            "{:<50} {:<20} {:<20} {:<25} {}",
            "Selector", "Workspace", "Slug", "Name", "ID"
        );
        println!("{}", "-".repeat(150));
        for item in filtered_notebooks {
            let selector = format!("@notebook[{}/{}]", item.workspace_slug, item.notebook.slug);
            println!(
                "{:<50} {:<20} {:<20} {:<25} {}",
                selector,
                item.workspace_name,
                item.notebook.slug,
                item.notebook.name,
                item.notebook.id
            );
        }
    }

    Ok(())
}

pub async fn handle_create(token: &str, name: &str, workspace_selector: &str) -> Result<()> {
    use crate::services::{notebooks_service, workspaces_service};

    let workspace_id = workspaces_service::resolve_workspace_id(token, workspace_selector).await?;
    let notebook_id = notebooks_service::create_notebook(token, &workspace_id, name).await?;
    println!("✓ Notebook created successfully");
    println!("  ID: {}", notebook_id);
    println!("  Name: {}", name);

    Ok(())
}

pub async fn handle_rename(token: &str, selector: &str, new_name: &str) -> Result<()> {
    use crate::services::notebooks_service;

    let notebook_id = notebooks_service::resolve_notebook_id(token, selector).await?;
    notebooks_service::update_notebook(token, &notebook_id, new_name).await?;
    println!("✓ Notebook renamed successfully to '{}'", new_name);

    Ok(())
}

pub async fn handle_delete(token: &str, selector: &str) -> Result<()> {
    use crate::services::{common, notebooks_service};

    let notebook_id = notebooks_service::resolve_notebook_id(token, selector).await?;
    let notebook = notebooks_service::get_notebook(token, &notebook_id).await?;

    println!("\nWarning: You are about to permanently delete this notebook:");
    println!("  Name: {}", notebook.name);
    println!("  ID: {}", notebook.id);
    println!("  Slug: {}", notebook.slug);
    println!("\nThis will also delete all notes within this notebook!");
    println!("This action cannot be undone!");

    if !common::confirm_action("Are you sure you want to delete this notebook?")? {
        println!("Deletion cancelled.");
        return Ok(());
    }

    notebooks_service::delete_notebook(token, &notebook_id).await?;
    println!("✓ Notebook deleted permanently");

    Ok(())
}
