use std::{cmp::Reverse, time::Duration};

use nmrs::{
    AirplaneModeState, ConnectionError, Network, NetworkInfo, RadioState, SavedConnection,
    SettingsPatch, WifiDevice, WifiSecurity,
};
use tokio::{
    sync::mpsc::UnboundedSender,
    time::{self, timeout},
};

use crate::action::Action;

#[derive(Clone)]
pub struct NetworkManager {
    pub nmrs: nmrs::NetworkManager,
    pub current_network: Option<Network>,
    pub current_network_info: Option<NetworkInfo>,
}

impl NetworkManager {
    pub async fn new() -> anyhow::Result<Self> {
        let nmrs = nmrs::NetworkManager::new().await?;
        let current_network = nmrs.current_network().await?;
        let current_network_info = if let Some(network) = &current_network {
            Some(nmrs.show_details(network).await?)
        } else {
            None
        };

        Ok(Self {
            nmrs,
            current_network,
            current_network_info,
        })
    }

    // Scanning & Discovery

    pub async fn scan_networks(&self) {
        if let Err(e) = self.nmrs.scan_networks(None).await {
            debug!("Failed to trigger WiFi scan via NetworkManager: {e}");
        }
    }

    pub async fn update_network_on_changes(
        &self,
        tx: UnboundedSender<Action>,
    ) -> Result<nmrs::MonitorHandle, ConnectionError> {
        self.nmrs
            .monitor_network_changes(move || _ = tx.send(Action::Reload))
            .await
    }

    pub async fn networks_list(&self) -> Result<(Vec<Network>, Vec<Network>), ConnectionError> {
        let mut networks = self.nmrs.list_networks(None).await?;
        networks.sort_by_key(|b| Reverse(b.strength));
        Ok(networks.into_iter().partition(|net| net.known))
    }

    pub async fn get_devices(&self) -> Result<Vec<WifiDevice>, ConnectionError> {
        self.nmrs.list_wifi_devices().await
    }

    // Active Connection

    pub async fn current_network(&self) -> Option<Network> {
        self.nmrs.current_network().await.ok()?
    }

    pub async fn show_details(&self, network: &Network) -> Result<NetworkInfo, ConnectionError> {
        self.nmrs.show_details(network).await
    }

    pub async fn connect(
        &self,
        ssid: &str,
        interface: Option<String>,
        credentials: WifiSecurity,
    ) -> Result<Result<(), ConnectionError>, time::error::Elapsed> {
        timeout(
            Duration::from_secs(30),
            self.nmrs.connect(ssid, interface.as_deref(), credentials),
        )
        .await
    }

    pub async fn disconnect(&self) -> Result<(), ConnectionError> {
        self.nmrs.disconnect(None).await
    }

    pub async fn forget(&self, ssid: &str) -> Result<(), ConnectionError> {
        self.nmrs.forget(ssid).await
    }

    // Saved Connections

    pub async fn get_saved_connection_uuid(
        &self,
        ssid: &str,
    ) -> Result<Option<String>, ConnectionError> {
        self.nmrs.get_saved_connection_uuid(ssid).await
    }

    pub async fn get_saved_connection(
        &self,
        uuid: &str,
    ) -> Result<SavedConnection, ConnectionError> {
        self.nmrs.get_saved_connection(uuid).await
    }

    pub async fn update_saved_connection(
        &self,
        uuid: &str,
        patch: SettingsPatch,
    ) -> Result<(), ConnectionError> {
        self.nmrs.update_saved_connection(uuid, patch).await
    }

    // Radio & Hardware State

    pub async fn wifi_state(&self) -> Result<RadioState, ConnectionError> {
        self.nmrs.wifi_state().await
    }

    pub async fn set_wireless_enabled(&self, enabled: bool) -> Result<(), ConnectionError> {
        self.nmrs.set_wireless_enabled(enabled).await
    }

    pub async fn airplane_mode_state(&self) -> Result<AirplaneModeState, ConnectionError> {
        self.nmrs.airplane_mode_state().await
    }

    pub async fn set_airplane_mode(&self, enabled: bool) -> Result<(), ConnectionError> {
        self.nmrs.set_airplane_mode(enabled).await
    }
}
