use std::io::Write as IoWrite;

use anyhow::Result;

use crate::api::{PlaneApiClient, WorkItemIdentifier};
use crate::config::resolve_plane_session;

/// Permanently deletes a work item from the project after confirming with the user.
/// Requires the work item identifier (e.g. "NRO-123") as a positional argument.
/// Pass --yes to skip the confirmation prompt for scripting use.
#[derive(clap::Args)]
pub struct DeleteWorkItemArgs {
    /// Work item identifier to delete (e.g. "NRO-123")
    identifier: String,
    /// Skip confirmation prompt and delete immediately
    #[arg(long)]
    yes: Option<String>,
}

/// Whether the user confirmed the destructive deletion operation
enum DeletionConfirmation {
    /// User typed "y" or passed --yes — proceed with deletion
    Confirmed,
    /// User declined or typed anything other than "y" — abort
    Declined,
}

/// Execution logic for the `plane delete` subcommand
impl DeleteWorkItemArgs {
    /// Resolves the work item, prompts for confirmation (unless --yes),
    /// then permanently deletes it via the Plane API
    pub async fn execute(self) -> Result<()> {
        let plane_session = resolve_plane_session()?;
        let api_client = PlaneApiClient::try_new(plane_session)?;

        let work_item_identifier: WorkItemIdentifier = self.identifier.parse()?;
        let fetched_work_item = api_client
            .find_work_item_by_identifier(&work_item_identifier)
            .await?;

        let confirmation = match self.yes {
            Option::Some(_) => DeletionConfirmation::Confirmed,
            Option::None => prompt_for_deletion_confirmation(&work_item_identifier)?,
        };

        match confirmation {
            DeletionConfirmation::Declined => {
                println!("Cancelled — {} was not deleted", work_item_identifier);
                return Ok(());
            }
            DeletionConfirmation::Confirmed => {}
        }

        let project_client = api_client.project_operations(fetched_work_item.project_id());
        let item_client = project_client.work_item_operations(fetched_work_item.id());
        item_client.delete_permanently().await?;

        println!(
            "Deleted {}: {}",
            work_item_identifier,
            fetched_work_item.title().as_str()
        );

        Ok(())
    }
}

fn prompt_for_deletion_confirmation(
    target_identifier: &WorkItemIdentifier,
) -> Result<DeletionConfirmation> {
    print!(
        "Permanently delete {}? This cannot be undone. (y/N): ",
        target_identifier
    );
    std::io::stdout().flush()?;

    let mut user_input = String::new();
    std::io::stdin().read_line(&mut user_input)?;

    if user_input.trim().eq_ignore_ascii_case("y") {
        Ok(DeletionConfirmation::Confirmed)
    } else {
        Ok(DeletionConfirmation::Declined)
    }
}
