const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js');

class EmbedBuilders {
    static createUserEmbed(playerData, gameFilter, playerService) {
        const profile = playerData.profile || {};
        const embed = new EmbedBuilder()
            .setTitle(`User: ${playerData.username || 'Unknown'}`)
            .setDescription(profile.bio || 'No bio available')
            .setColor('#0099ff')
            .setImage('https://www.vrbattles.gg/assets/images/Qubi/vrwearcubesatad.png');

        // Add thumbnail (avatar)
        if (profile.avatar) {
            embed.setThumbnail(
                `https://www.vrbattles.gg/assets/uploads/profile/${profile.avatar}`
            );
        }

        // Add profile fields
        const profileFields = [];
        if (profile.country) profileFields.push({ name: 'Country', value: profile.country, inline: true });
        if (profile.level) profileFields.push({ name: 'Level', value: profile.level.toString(), inline: true });
        if (profile.xp) profileFields.push({ name: 'Total XP', value: profile.xp.toString(), inline: true });
        if (profile.prestige) profileFields.push({ name: 'Prestige', value: profile.prestige.toString(), inline: true });

        if (profileFields.length > 0) {
            embed.addFields(profileFields);
        }

        // Add game stats if available
        const games = playerData.stats?.games;
        if (games) {
            Object.entries(games).forEach(([gameName, gameData]) => {
                if (gameFilter && gameName.toLowerCase() !== gameFilter.toLowerCase()) return;

                embed.addFields({ name: gameName, value: '\u200B' });
                Object.entries(gameData).forEach(([mode, stats]) => {
                    if (mode === 'Overall') return;

                    const statFields = [];
                    if (stats.matches) statFields.push(`Matches: ${stats.matches}`);
                    if (stats.wins) statFields.push(`Wins: ${stats.wins}`);
                    if (stats.losses) statFields.push(`Losses: ${stats.losses}`);
                    if (stats.win_rate) statFields.push(`Win Rate: ${stats.win_rate}`);

                    if (statFields.length > 0) {
                        embed.addFields({
                            name: mode,
                            value: statFields.join(' | '),
                            inline: true
                        });
                    }
                });
            });
        }

        // Add teams if available
        const teams = playerData.teams;
        if (teams && Object.keys(teams).length > 0) {
            const teamList = Object.values(teams)
                .map(team => `- **${team.team_name}** (${team.game_name} - ${team.game_mode})`)
                .join('\n');

            embed.addFields(
                { name: '\u200B', value: '**Teams**' },
                { name: 'Team List', value: teamList || 'No teams available' }
            );
        }

        // Add recent matches if available
        const matches = playerData.matches;
        if (matches && Object.keys(matches).length > 0) {
            const matchList = Object.values(matches)
                .sort((a, b) => new Date(b.start_time) - new Date(a.start_time))
                .slice(0, 3)
                .map(match => {
                    const date = new Date(match.start_time).toLocaleDateString();
                    const team1 = match.team1_name || 'Team 1';
                    const team2 = match.team2_name || 'Team 2';
                    const score = match.score || 'N/A';
                    return `- **${team1}** vs **${team2}** on ${date} - Result: ${score}`;
                })
                .join('\n');

            embed.addFields(
                { name: '\u200B', value: '**Recent Matches**' },
                { name: 'Match History', value: matchList || 'No recent matches' }
            );
        }

        return embed;
    }

    static createMatchHistoryEmbed(playerData, matches) {
        const embed = new EmbedBuilder()
            .setTitle(`Match History for ${playerData.username}`)
            .setColor('#0099ff')
            .setDescription(`Last ${matches.length} matches`);

        if (playerData.profile?.avatar) {
            embed.setThumbnail(
                `https://www.vrbattles.gg/assets/uploads/profile/${playerData.profile.avatar}`
            );
        }

        // Add match stats
        const wins = matches.filter(m => {
            const isTeam1 = m.team1_name === playerData.username;
            return m.winner_id === (isTeam1 ? "1" : "2");
        }).length;

        const winRate = ((wins / matches.length) * 100).toFixed(1);

        embed.addFields(
            { name: 'Recent Win Rate', value: `${winRate}%`, inline: true },
            { name: 'Matches Analyzed', value: matches.length.toString(), inline: true },
            { name: 'Recent Wins', value: wins.toString(), inline: true }
        );

        // Add individual matches
        matches.forEach((match, index) => {
            const date = new Date(match.start_time).toLocaleDateString();
            const isTeam1 = match.team1_name === playerData.username;
            const opponent = isTeam1 ? match.team2_name : match.team1_name;
            const won = match.winner_id === (isTeam1 ? "1" : "2");
            const score = match.score || '0 - 0';
            const gameMode = match.game_mode ? ` (${match.game_mode})` : '';
            
            const matchResult = won ? '✅ Victory' : '❌ Defeat';
            
            embed.addFields({
                name: `Match ${index + 1} - ${matchResult}`,
                value: `🎮 **${match.game_name}${gameMode}**\n` +
                    `🆚 vs ${opponent}\n` +
                    `📊 Score: ${score}\n` +
                    `📅 ${date}`,
                inline: false
            });
        });

        return embed;
    }

    static createMatchRequestEmbed(matchData) {
        // Parse the match date from the provided format
        const matchDateTime = new Date(matchData.match_date);
        const now = new Date();
        
        // Calculate time difference in minutes
        const timeDiffMinutes = Math.floor((matchDateTime - now) / (1000 * 60));
        
        // Format the time until match
        let timeUntilMatch;
        if (timeDiffMinutes < 0) {
            timeUntilMatch = 'Match has already started';
        } else if (timeDiffMinutes < 60) {
            timeUntilMatch = `${timeDiffMinutes} minutes`;
        } else {
            const hours = Math.floor(timeDiffMinutes / 60);
            const minutes = timeDiffMinutes % 60;
            timeUntilMatch = `${hours} hour${hours !== 1 ? 's' : ''} ${minutes} minute${minutes !== 1 ? 's' : ''}`;
        }

        return new EmbedBuilder()
            .setColor('#00ff00')
            .setTitle(`🎮 New ${matchData.game_name} Match`)
            .setDescription(`${matchData.team_size} Match in ${matchData.region} Region`)
            .addFields(
                {
                    name: '⏰ Match Time (UTC)',
                    value: matchDateTime.toUTCString(),
                    inline: true
                },
                {
                    name: '⏳ Time Until Match',
                    value: timeUntilMatch,
                    inline: true
                },
                {
                    name: '📊 Status',
                    value: matchData.status,
                    inline: true
                },
                {
                    name: '🎲 Match Type',
                    value: matchData.match_type,
                    inline: true
                }
            )
            .setTimestamp()
            .setFooter({ text: 'VRBattles Match System' });
    }

    static createActionRow(username, playerService) {
        return new ActionRowBuilder().addComponents(
            new ButtonBuilder()
                .setLabel('🔵 View Profile')
                .setStyle(ButtonStyle.Link)
                .setURL(playerService.getProfileUrl(username)),
            new ButtonBuilder()
                .setLabel('🟡 Join Main Discord')
                .setStyle(ButtonStyle.Link)
                .setURL('https://discord.gg/j3DKVATPGQ')
        );
    }

    static createTeamEmbed(teams) {
        const embeds = [];
        const infoEmbed = new EmbedBuilder()
            .setTitle(`Teams Found`)
            .setColor('#0099ff')
            .setImage('https://www.vrbattles.gg/assets/images/Qubi/vrwearcubesatad.png');

        if (!teams || teams.length === 0) {
            infoEmbed.setDescription('No teams found');
            return [infoEmbed];
        }

        // Sort teams by game mode priority and date
        const gameModeOrder = {
            'Squads': 1,
            'Duo': 2,
            'Solo': 3
        };

        teams.sort((a, b) => {
            const modeA = gameModeOrder[a.game_mode] || 999;
            const modeB = gameModeOrder[b.game_mode] || 999;
            if (modeA !== modeB) return modeA - modeB;
            return new Date(b.date_created) - new Date(a.date_created);
        });

        teams.forEach((team, index) => {
            const modeIcon = team.game_mode === 'Squads' ? '🎮' : 
                           team.game_mode === 'Duo' ? '🎯' : '⚔️';
            
            // Combine stats into a single line
            const stats = [];
            if (team.matches) stats.push(`M:${team.matches}`);
            if (team.wins) stats.push(`W:${team.wins}`);
            if (team.losses) stats.push(`L:${team.losses}`);
            const winRate = team.matches > 0 ? 
                ((parseInt(team.wins) / parseInt(team.matches)) * 100).toFixed(1) : 0;
            stats.push(`WR:${winRate}%`);

            // Create team header with stats
            let teamInfo = `${modeIcon} **${team.name}** (${team.game_name} ${team.game_mode})\n`;
            teamInfo += `📊 ${stats.join(' | ')}`;
            
            // Add players if available
            if (team.players?.length > 0) {
                teamInfo += `\n👥 ${team.players.map(p => p.username).join(', ')}`;
            }
            
            // Add logo link if available
            if (team.logo) {
                teamInfo += `\n🎨 [View Logo](${team.logo})`;
            }

            infoEmbed.addFields({
                name: `Team ${index + 1}`,
                value: teamInfo
            });

            // Add small separator if not the last team
            if (index < teams.length - 1) {
                infoEmbed.addFields({ name: '\u200B', value: '▬▬▬▬▬▬▬▬▬▬', inline: false });
            }
        });

        embeds.push(infoEmbed);
        return embeds;
    }
}

module.exports = EmbedBuilders;