package level

import (
	"context"
	"bytes"
	"strconv"
	"fmt"

	"velox-bot/internal/db/services"
	"velox-bot/internal/rankcard"

	"github.com/bwmarrin/discordgo"
)

var RankCommand = &discordgo.ApplicationCommand{
	Name:        "rank",
	Description: "Get your level card",
	Options: []*discordgo.ApplicationCommandOption{
		{
			Type:        discordgo.ApplicationCommandOptionUser,
			Name:        "user",
			Description: "The user to get the rank card of",
			Required:    false,
		},
	},
}

var LeaderboardCommand = &discordgo.ApplicationCommand{
	Name:        "leaderboard",
	Description: "Top 10 levels in this server",
}

func HandleRank(s *discordgo.Session, i *discordgo.InteractionCreate) {
	if services.Global == nil || services.Global.Level == nil {
		s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
			Type: discordgo.InteractionResponseChannelMessageWithSource,
			Data: &discordgo.InteractionResponseData{
				Content: "Leveling service is not available.",
				Flags:   discordgo.MessageFlagsEphemeral,
			},
		})
		return
	}

	// Determine target user: option or caller.
	target := i.User
	if i.Member != nil && i.Member.User != nil {
		target = i.Member.User
	}

	if len(i.ApplicationCommandData().Options) > 0 {
		if u := i.ApplicationCommandData().Options[0].UserValue(s); u != nil {
			target = u
		}
	}

	if target == nil {
		return
	}

	guildID, err := strconv.ParseInt(i.GuildID, 10, 64)
	if err != nil {
		return
	}
	userID, err := strconv.ParseInt(target.ID, 10, 64)
	if err != nil {
		return
	}

	ctx := context.Background()
	lvl, err := services.Global.Level.GetLevel(ctx, guildID, userID)
	if err != nil {
		return
	}

	percent := float64(lvl.XP) / 100.0
	avatarURL := target.AvatarURL("256")

	pngBytes, err := rankcard.RenderPNG(ctx, rankcard.Data{
		Name:    target.Username,
		Level:   lvl.Level,
		XP:      lvl.XP,
		Percent: percent,
		Avatar:  avatarURL,
	})
	if err != nil {
		s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
			Type: discordgo.InteractionResponseChannelMessageWithSource,
			Data: &discordgo.InteractionResponseData{
				Content: "Failed to render rank card.",
				Flags:   discordgo.MessageFlagsEphemeral,
			},
		})
		return
	}

	s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
		Type: discordgo.InteractionResponseChannelMessageWithSource,
		Data: &discordgo.InteractionResponseData{
			Files: []*discordgo.File{
				{
					Name:   "levelcard.png",
					Reader: bytes.NewReader(pngBytes),
				},
			},
		},
	})
}

func HandleLeaderboard(s *discordgo.Session, i *discordgo.InteractionCreate) {
	if i.GuildID == "" {
		s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
			Type: discordgo.InteractionResponseChannelMessageWithSource,
			Data: &discordgo.InteractionResponseData{
				Content: "This command can only be used in a server.",
				Flags:   discordgo.MessageFlagsEphemeral,
			},
		})
		return
	}

	if services.Global == nil || services.Global.Level == nil {
		s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
			Type: discordgo.InteractionResponseChannelMessageWithSource,
			Data: &discordgo.InteractionResponseData{
				Content: "Leveling service is not available.",
				Flags:   discordgo.MessageFlagsEphemeral,
			},
		})
		return
	}

	guildID, err := strconv.ParseInt(i.GuildID, 10, 64)
	if err != nil {
		s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
			Type: discordgo.InteractionResponseChannelMessageWithSource,
			Data: &discordgo.InteractionResponseData{
				Content: "Invalid guild ID.",
				Flags:   discordgo.MessageFlagsEphemeral,
			},
		})
		return
	}

	ctx := context.Background()
	top, err := services.Global.Level.TopLevels(ctx, guildID, 10)
	if err != nil {
		s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
			Type: discordgo.InteractionResponseChannelMessageWithSource,
			Data: &discordgo.InteractionResponseData{
				Content: "Failed to load leaderboard.",
				Flags:   discordgo.MessageFlagsEphemeral,
			},
		})
		return
	}

	if len(top) == 0 {
		s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
			Type: discordgo.InteractionResponseChannelMessageWithSource,
			Data: &discordgo.InteractionResponseData{
				Content: "No leaderboard data yet.",
				Flags:   discordgo.MessageFlagsEphemeral,
			},
		})
		return
	}

	fields := make([]*discordgo.MessageEmbedField, 0, len(top))
	for idx, entry := range top {
		display := fmt.Sprintf("<@%d>", entry.UserID)
		if u, err := s.User(strconv.FormatInt(entry.UserID, 10)); err == nil && u != nil && u.Username != "" {
			display = u.Username
		}

		fields = append(fields, &discordgo.MessageEmbedField{
			Name:   fmt.Sprintf("%d. %s", idx+1, display),
			Value:  fmt.Sprintf("Level: **%d** | XP: **%d**", entry.Level, entry.XP),
			Inline: false,
		})
	}

	embed := &discordgo.MessageEmbed{
		Title:       "Leaderboard",
		Description: fmt.Sprintf("These are the top %d users in the server", len(top)),
		Fields:      fields,
		Color:       0xF59E0B,
	}

	s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
		Type: discordgo.InteractionResponseChannelMessageWithSource,
		Data: &discordgo.InteractionResponseData{
			Embeds: []*discordgo.MessageEmbed{embed},
		},
	})
}
