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",
}

var RewardsCommand = &discordgo.ApplicationCommand{
	Name:        "rewards",
	Description: "View level rewards in this server",
}

func HandleRank(s *discordgo.Session, i *discordgo.InteractionCreate) {
	if !requireLevelServices(s, i) {
		return
	}

	if i.GuildID != "" && !requireLevelSystemEnabled(s, i) {
		respondEphemeral(s, i, "Leveling system is disabled on this server.")
		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, ok := parseGuildID(s, i)
	if !ok {
		return
	}
	userID, err := strconv.ParseInt(target.ID, 10, 64)
	if err != nil {
		respondEphemeral(s, i, "Invalid user ID.")
		return
	}

	ctx := context.Background()
	lvl, err := services.Global.Level.GetLevel(ctx, guildID, userID)
	if err != nil {
		respondEphemeral(s, i, "Failed to load level.")
		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 {
		respondEphemeral(s, i, "Failed to render rank card.")
		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 !requireGuild(s, i) {
		return
	}

	if !requireLevelServices(s, i) {
		return
	}

	guildID, ok := parseGuildID(s, i)
	if !ok {
		return
	}

	ctx := context.Background()
	if !requireLevelSystemEnabled(s, i) {
		return
	}
	top, err := services.Global.Level.TopLevels(ctx, guildID, 10)
	if err != nil {
		respondEphemeral(s, i, "Failed to load leaderboard.")
		return
	}

	if len(top) == 0 {
		respondEphemeral(s, i, "No leaderboard data yet.")
		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},
		},
	})
}

func HandleRewards(s *discordgo.Session, i *discordgo.InteractionCreate) {
	if !requireGuild(s, i) {
		return
	}

	if !requireLevelSettingsService(s, i) {
		return
	}

	guildID, ok := parseGuildID(s, i)
	if !ok {
		return
	}

	ctx := context.Background()
	if !requireLevelSystemEnabled(s, i) {
		return
	}
	rewards, err := services.Global.LevelSettings.ListRoleRewards(ctx, guildID, 25)
	if err != nil {
		respondEphemeral(s, i, "Failed to load rewards.")
		return
	}

	if len(rewards) == 0 {
		respondEphemeral(s, i, "No rewards configured yet.")
		return
	}

	fields := make([]*discordgo.MessageEmbedField, 0, len(rewards))
	for _, r := range rewards {
		fields = append(fields, &discordgo.MessageEmbedField{
			Name:   fmt.Sprintf("Level %d", r.Level),
			Value:  fmt.Sprintf("<@&%d>", r.RoleID),
			Inline: true,
		})
	}

	embed := &discordgo.MessageEmbed{
		Title:       "Level Rewards",
		Description: "Roles granted when you reach a level.",
		Fields:      fields,
		Color:       0xF59E0B,
	}

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