use std::{sync::Arc, pin::Pin};

use actix_web::{get, post, web, HttpResponse, ResponseError};
use log::warn;
use serde::{Serialize, Deserialize};
use serenity::model::prelude::{GuildChannel, ChannelType};
use siren::{ServiceError, Response};

use crate::{AppState, bot::commands::audio::{play::play_track, join}, storage::guilds::QueryGuild, auth::{JwtAuth, verify_role}};

#[get("/guilds")]
async fn get_guilds(data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
  let _ = match verify_role(&auth, "admin") {
    Ok(_) => {},
    Err(err) => return ResponseError::error_response(&err)
  };
  let guild_results = &data.http.get_guilds(None, None).await;
  let guilds = match guild_results {
    Ok(guilds) => guilds,
    Err(err) => return ResponseError::error_response(&ServiceError {
      status: 422,
      message: err.to_string()
    })
  };
  HttpResponse::Ok().json(Response {
    data: guilds,
    metadata: None
  })
}

#[get("/{id}/text")]
async fn get_text_channels(id: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
  let _ = match verify_role(&auth, "admin") {
    Ok(_) => {},
    Err(err) => return ResponseError::error_response(&err)
  };
  let channel_results = &data.http.get_channels(id.parse::<u64>().unwrap()).await;
  let channels = match channel_results {
    Ok(channels) => channels.iter().filter(|c| c.kind == ChannelType::Text).collect::<Vec<&GuildChannel>>(),
    Err(err) => return ResponseError::error_response(&ServiceError {
      status: 422,
      message: err.to_string()
    })
  };
  HttpResponse::Ok().json(Response {
    data: channels,
    metadata: None
  })
}

#[get("/{id}/voice")]
async fn get_voice_channels(id: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
  let _ = match verify_role(&auth, "admin") {
    Ok(_) => {},
    Err(err) => return ResponseError::error_response(&err)
  };
  let channel_results = &data.http.get_channels(id.parse::<u64>().unwrap()).await;
  let channels = match channel_results {
    Ok(channels) => channels.iter().filter(|c| c.kind == ChannelType::Voice).collect::<Vec<&GuildChannel>>(),
    Err(err) => return ResponseError::error_response(&ServiceError {
      status: 422,
      message: err.to_string()
    })
  };
  HttpResponse::Ok().json(Response {
    data: channels,
    metadata: None
  })
}

#[derive(Serialize, Deserialize)]
struct ChannelMessage {
  message: String
}

#[post("/{guild_id}/text/{channel_id}/message")]
async fn send_message(path: web::Path<(String, String)>, text: web::Json<ChannelMessage>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
  let _ = match verify_role(&auth, "admin") {
    Ok(_) => {},
    Err(err) => return ResponseError::error_response(&err)
  };
  let (guild_id, channel_id) = path.into_inner();
  let guild_id = match guild_id.parse::<u64>() {
    Ok(id) => id,
    Err(err) => {
      return ResponseError::error_response(&ServiceError {
        status: 422,
        message: err.to_string()
      })
    }
  };
  let channel_id = match channel_id.parse::<u64>() {
    Ok(id) => id,
    Err(err) => {
      return ResponseError::error_response(&ServiceError {
        status: 422,
        message: err.to_string()
      })
    }
  };
  let channel_results = &data.http.get_channels(guild_id).await;
  let channels = match channel_results {
    Ok(channels) => channels,
    Err(err) => {
      return ResponseError::error_response(&ServiceError {
        status: 422,
        message: err.to_string()
      })
    }
  };
  
  let channel = match channels.iter().find(|c| c.id.0 == channel_id) {
    Some(channel) => channel,
    None => {
      return ResponseError::error_response(&ServiceError {
        status: 422,
        message: format!("Could not find channel with id {}", channel_id)
      })
    }
  };

  if let Err(err) = channel.say(&Pin::new(&data.http).get_ref(), &text.message).await {
    return ResponseError::error_response(&ServiceError {
      status: 422,
      message: err.to_string()
    })
  };

  HttpResponse::Ok().finish()
}

#[derive(Serialize, Deserialize)]
struct PlayRequest {
  track_url: String
}

#[post("/{guild_id}/voice/{channel_id}/play")]
async fn play(path: web::Path<(String, String)>, play_request: web::Json<PlayRequest>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
  let _ = match verify_role(&auth, "admin") {
    Ok(_) => {},
    Err(err) => return ResponseError::error_response(&err)
  };
  let (guild_id, channel_id) = path.into_inner();
  let guild_id = match guild_id.parse::<u64>() {
    Ok(id) => id,
    Err(err) => {
      return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() })
    }
  };
  let channel_id = match channel_id.parse::<u64>() {
    Ok(id) => id,
    Err(err) => {
      return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() })
    }
  };
  let http = Pin::new(&data.http).get_ref();
  let guild = match http.get_guild(guild_id).await {
    Ok(guild) => guild,
    Err(err) => {
      return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() })
    }
  };
  let channel = match http.get_channel(channel_id).await {
    Ok(channel) => channel,
    Err(err) => {
      return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() })
    }
  };

  let manager = Arc::clone(&data.songbird);

  match join(Arc::clone(&manager), &guild.id, &channel.id()).await {
    Ok(_) => {
      match play_track(Arc::clone(&data.songbird), guild.id, play_request.track_url.to_string()).await {
        Ok(_) => HttpResponse::Ok().finish(),
        Err(err) => {
          return ResponseError::error_response(&err)
        }
      }
    },
    Err(err) => {
      return ResponseError::error_response(&ServiceError { status: 500, message: err.to_string() })
    }
  }
}

#[post("/{guild_id}/voice/stop")]
async fn stop(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
  let _ = match verify_role(&auth, "admin") {
    Ok(_) => {},
    Err(err) => return ResponseError::error_response(&err)
  };
  let guild_id = path.into_inner();
  let guild_id = match guild_id.parse::<u64>() {
    Ok(id) => id,
    Err(err) => {
      return ResponseError::error_response(&ServiceError {
        status: 422,
        message: err.to_string()
      })
    }
  };

  if let Some(handler_lock) = data.songbird.get(guild_id) {
    let handler = handler_lock.lock().await;
    handler.queue().stop();
  }

  HttpResponse::Ok().finish()
}

#[post("/{guild_id}/voice/resume")]
async fn resume(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
  let _ = match verify_role(&auth, "admin") {
    Ok(_) => {},
    Err(err) => return ResponseError::error_response(&err)
  };
  let guild_id = path.into_inner();
  let guild_id = match guild_id.parse::<u64>() {
    Ok(id) => id,
    Err(err) => {
      return ResponseError::error_response(&ServiceError {
        status: 422,
        message: err.to_string()
      })
    }
  };

  if let Some(handler_lock) = data.songbird.get(guild_id) {
    let handler = handler_lock.lock().await;
    if let Err(err) = handler.queue().resume() {
      return ResponseError::error_response(&ServiceError {
        status: 422,
        message: err.to_string()
      })
    }
  }

  HttpResponse::Ok().finish()
}

#[post("/{guild_id}/voice/pause")]
async fn pause(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
  let _ = match verify_role(&auth, "admin") {
    Ok(_) => {},
    Err(err) => return ResponseError::error_response(&err)
  };
  let guild_id = path.into_inner();
  let guild_id = match guild_id.parse::<u64>() {
    Ok(id) => id,
    Err(err) => {
      return ResponseError::error_response(&ServiceError {
        status: 422,
        message: err.to_string()
      })
    }
  };

  if let Some(handler_lock) = data.songbird.get(guild_id) {
    let handler = handler_lock.lock().await;
    if let Err(err) = handler.queue().pause() {
      return ResponseError::error_response(&ServiceError {
        status: 422,
        message: err.to_string()
      })
    }
  }

  HttpResponse::Ok().finish()
}

#[derive(Serialize, Deserialize)]
struct SetVolume {
  volume: String
}

#[get("/{guild_id}/voice/volume")]
async fn get_volume(path: web::Path<String>, auth: JwtAuth) -> HttpResponse {
  let _ = match verify_role(&auth, "admin") {
    Ok(_) => {},
    Err(err) => return ResponseError::error_response(&err)
  };
  let guild_id = path.into_inner();
  let guild_id = match guild_id.parse::<u64>() {
    Ok(id) => id,
    Err(err) => {
      return ResponseError::error_response(&ServiceError {
        status: 422,
        message: err.to_string()
      })
    }
  };

  let volume = match QueryGuild::get(guild_id as i64) {
    Ok(guild) => guild.volume,
    Err(err) => {
      return ResponseError::error_response(&ServiceError {
        status: 422,
        message: err.to_string()
      })
    }
  };

  HttpResponse::Ok().json(volume)
}

#[post("/{guild_id}/voice/volume")]
async fn set_volume(path: web::Path<String>, volume: web::Json::<SetVolume>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
  let _ = match verify_role(&auth, "admin") {
    Ok(_) => {},
    Err(err) => return ResponseError::error_response(&err)
  };
  let guild_id = path.into_inner();
  let guild_id = match guild_id.parse::<u64>() {
    Ok(id) => id,
    Err(err) => {
      return ResponseError::error_response(&ServiceError {
        status: 422,
        message: err.to_string()
      })
    }
  };

  let volume = volume.volume.parse::<i32>().unwrap_or(0);
  let manager = Arc::clone(&data.songbird);
  let http = Arc::clone(&data.http);
  let guild = match http.get_guild(guild_id).await {
    Ok(guild) => guild,
    Err(err) => {
      return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() })
    }
  };
  crate::bot::commands::audio::volume::set_volume(manager, guild.id, volume).await;

  HttpResponse::Ok().finish()
}

#[post("/{guild_id}/voice/skip")]
async fn skip(path: web::Path<String>, data: web::Data<Arc<AppState>>, auth: JwtAuth) -> HttpResponse {
  let _ = match verify_role(&auth, "admin") {
    Ok(_) => {},
    Err(err) => return ResponseError::error_response(&err)
  };
  let guild_id = path.into_inner();
  let guild_id = match guild_id.parse::<u64>() {
    Ok(id) => id,
    Err(err) => {
      return ResponseError::error_response(&ServiceError {
        status: 422,
        message: err.to_string()
      })
    }
  };

  if let Some(handler_lock) = data.songbird.get(guild_id) {
    let handler = handler_lock.lock().await;
    if let Err(err) = handler.queue().skip() {
      return ResponseError::error_response(&ServiceError {
        status: 422,
        message: err.to_string()
      })
    }
  }

  HttpResponse::Ok().finish()
}

pub fn init_routes(config: &mut web::ServiceConfig) {
  config
    .service(get_guilds)
    .service(web::scope("guilds")
      .service(get_text_channels)
      .service(get_voice_channels)
      .service(send_message)
      .service(play)
      .service(stop)
      .service(resume)
      .service(pause)
      .service(set_volume)
      .service(get_volume)
      .service(skip)
  );
}