use crate::services::{common, workspaces_service};
use anyhow::Result;
use clap::Subcommand;

#[derive(Subcommand)]
pub enum WorkspaceCommands {
    /// List all workspaces
    #[clap(visible_alias("ls"))]
    List,
    /// Create a new workspace
    Create {
        /// Workspace name
        #[arg(value_name = "NAME")]
        name: String,
    },
    /// Rename a workspace
    Rename {
        /// Workspace slug or ID
        #[arg(value_name = "SELECTOR")]
        selector: String,
        /// New workspace name
        #[arg(value_name = "NEW_NAME")]
        new_name: String,
    },
    /// Delete a workspace
    Delete {
        /// Workspace slug or ID
        #[arg(value_name = "SELECTOR")]
        selector: String,
    },
}

pub async fn handle_list(token: &str) -> Result<()> {
    let workspaces = workspaces_service::list_workspaces(token).await?;

    if workspaces.is_empty() {
        println!("No workspaces found.");
    } else {
        println!("Workspaces:");
        println!("{:<38} {:<20} {}", "ID", "Slug", "Name");
        println!("{}", "-".repeat(80));
        for workspace in workspaces {
            println!(
                "{:<38} {:<20} {}",
                workspace.id, workspace.slug, workspace.name
            );
        }
    }

    Ok(())
}

pub async fn handle_create(token: &str, name: &str) -> Result<()> {
    let workspace_id = workspaces_service::create_workspace(token, name).await?;
    println!("✓ Workspace created successfully");
    println!("  ID: {}", workspace_id);
    println!("  Name: {}", name);

    Ok(())
}

pub async fn handle_rename(token: &str, selector: &str, new_name: &str) -> Result<()> {
    let workspace_id = workspaces_service::resolve_workspace_id(token, selector).await?;
    workspaces_service::update_workspace(token, &workspace_id, new_name).await?;
    println!("✓ Workspace renamed successfully to '{}'", new_name);

    Ok(())
}

pub async fn handle_delete(token: &str, selector: &str) -> Result<()> {
    let workspace_id = workspaces_service::resolve_workspace_id(token, selector).await?;
    let workspace = workspaces_service::get_workspace(token, &workspace_id).await?;

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

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

    workspaces_service::delete_workspace(token, &workspace_id).await?;
    println!("✓ Workspace deleted permanently");

    Ok(())
}
