use chrono_tz::Tz;
use serde::{Deserialize, Serialize};

use crate::{
    commands::autocomplete::{time_hint_autocomplete, timezone_autocomplete},
    models::reminder::create_reminder,
    utils::{Extract, Recordable},
    Context, Error,
};

#[derive(Serialize, Deserialize, Extract)]
pub struct Options {
    time: String,
    content: String,
    channels: Option<String>,
    interval: Option<String>,
    expires: Option<String>,
    tts: Option<bool>,
    timezone: Option<String>,
}

impl Recordable for Options {
    async fn run(self, ctx: Context<'_>) -> Result<(), Error> {
        let tz = self.timezone.map(|t| t.parse::<Tz>().ok()).flatten();

        create_reminder(
            ctx,
            self.time,
            self.content,
            self.channels,
            self.interval,
            self.expires,
            self.tts,
            tz,
        )
        .await
    }
}

/// Create a reminder. Press "+4 more" for other options. Use "/multiline" for multiline content.
#[poise::command(
    slash_command,
    rename = "remind",
    default_member_permissions = "MANAGE_GUILD",
    identifying_name = "remind"
)]
pub async fn command(
    ctx: Context<'_>,
    #[description = "The time (and optionally date) to set the reminder for"]
    #[autocomplete = "time_hint_autocomplete"]
    time: String,
    #[description = "The message content to send"] content: String,
    #[description = "Channel or user mentions to set the reminder for"] channels: Option<String>,
    #[description = "(Patreon only) Time to wait before repeating the reminder. Leave blank for one-shot reminder"]
    interval: Option<String>,
    #[description = "(Patreon only) For repeating reminders, the time at which the reminder will stop repeating"]
    expires: Option<String>,
    #[description = "Set the TTS flag on the reminder message, similar to the /tts command"]
    tts: Option<bool>,
    #[description = "Set a timezone override for this reminder only"]
    #[autocomplete = "timezone_autocomplete"]
    timezone: Option<String>,
) -> Result<(), Error> {
    (Options { time, content, channels, interval, expires, tts, timezone }).run(ctx).await
}
