use poise::{
    serenity_prelude as serenity,
    serenity_prelude::{CreateEmbed, CreateMessage, FullEvent},
};

use crate::{
    component_models::ComponentDataModel, metrics::COMMAND_COUNTER, Data, Error, THEME_COLOR,
};

pub async fn listener(
    ctx: &serenity::Context,
    event: &FullEvent,
    data: &Data,
) -> Result<(), Error> {
    match event {
        FullEvent::ChannelDelete { channel, .. } => {
            sqlx::query!("DELETE FROM channels WHERE channel = ?", channel.id.get())
                .execute(&data.database)
                .await
                .unwrap();
        }
        FullEvent::GuildCreate { guild, is_new } => {
            if is_new.unwrap_or(false) {
                let guild_id = guild.id.get().to_owned();

                sqlx::query!("INSERT IGNORE INTO guilds (guild) VALUES (?)", guild_id)
                    .execute(&data.database)
                    .await?;

                let default_channel = guild.default_channel_guaranteed();

                if let Some(default_channel) = default_channel {
                    default_channel.send_message(
                        &ctx,
                        CreateMessage::new()
                            .embed(
                                CreateEmbed::new()
                                    .title("Thank you for adding Reminder Bot!")
                                    .description("To get started:
• Set your timezone with `/timezone`
• Set up permissions in Server Settings 🠚 Integrations 🠚 Reminder Bot (desktop only)
• Create your first reminder with `/remind`

__Support__
If you need any support, please come and ask us! Join our [Discord](https://discord.jellywx.com).

__Updates__
To stay up to date on the latest features and fixes, join our [Discord](https://discord.jellywx.com).
")
                                    .color(*THEME_COLOR)
                            )
                        )
                        .await?;
                }
            }
        }
        FullEvent::GuildDelete { incomplete, .. } => {
            if !incomplete.unavailable {
                let _ = sqlx::query!("DELETE FROM guilds WHERE guild = ?", incomplete.id.get())
                    .execute(&data.database)
                    .await;
            }
        }
        FullEvent::InteractionCreate { interaction } => {
            if let Some(component) = interaction.clone().message_component() {
                let component_model = ComponentDataModel::from_custom_id(&component.data.custom_id);

                component_model.act(ctx, data, &component).await;
            }

            if let Some(command) = interaction.clone().command() {
                COMMAND_COUNTER.with_label_values(&[command.data.name.as_str()]).inc();
            }
        }
        _ => {}
    }

    Ok(())
}
