import {
    GameState,
    Player,
    GamePhase,
    Role,
    Faction,
    GAME_CONFIG
} from '../../../shared/types';

export class Game {
    public state: GameState;

    public roomName: string;
    public hostId: string;
    public maxPlayers: number;
    public password?: string;

    constructor(
        roomId: string,
        roomName: string,
        hostId: string,
        maxPlayers: number,
        password?: string
    ) {
        this.roomName = roomName;
        this.hostId = hostId;
        this.maxPlayers = maxPlayers;
        this.password = password;

        this.state = {
            roomId,
            phase: GamePhase.LOBBY,
            players: [],
            currentRound: 1,
            failedVotesCount: 0,
            questResults: [null, null, null, null, null],
            currentLeaderId: '',
            leaderVotes: {},
            proposedTeam: [],
            teamVotes: {},
            missionVotes: [],
            missionHistory: [],
            revealedVotes: [],
            history: [],
            hostId: hostId
        };
    }

    addPlayer(id: string, name: string): Player {
        // Asignar avatar aleatorio persistente (rebel001.jpg - rebel010.jpg)
        const avatarIdx = Math.floor(Math.random() * 10) + 1;
        const avatarStr = `rebel${avatarIdx.toString().padStart(3, '0')}.jpg`;

        const player: Player = {
            id,
            name,
            avatar: avatarStr,
            isLeader: false
        };
        this.state.players.push(player);
        this.log(`${name} se ha unido a la partida.`);
        return player;
    }

    removePlayer(id: string) {
        this.state.players = this.state.players.filter(p => p.id !== id);
    }

    startGame(): boolean {
        const count = this.state.players.length;
        if (count < 5 || count > 10) return false;

        const config = GAME_CONFIG[count as keyof typeof GAME_CONFIG];

        // 1. Asignar Roles
        this.assignRoles(config.good, config.evil);

        // 2. Asignar Líder inicial aleatorio
        const leaderIndex = Math.floor(Math.random() * count);
        this.state.players[leaderIndex].isLeader = true;
        this.state.currentLeaderId = this.state.players[leaderIndex].id;

        // 3. Iniciar juego - Fase Votación de Líder
        this.state.phase = GamePhase.VOTE_LEADER;
        this.state.leaderVotes = {}; // Reset votes
        this.state.currentRound = 1;
        this.log('¡La partida ha comenzado! Ahora deben votar para confirmar al Líder.');

        return true;
    }

    // ... assignRoles se mantiene igual ...
    private assignRoles(goodCount: number, evilCount: number) {
        // Roles obligatorios
        const roles: Role[] = [Role.MERLIN, Role.ASSASSIN];

        // Rellenar resto de malos
        for (let i = 0; i < evilCount - 1; i++) roles.push(Role.MINION);

        // Rellenar resto de buenos
        for (let i = 0; i < goodCount - 1; i++) roles.push(Role.LOYAL_SERVANT);

        // Barajar roles
        const shuffledRoles = roles.sort(() => Math.random() - 0.5);

        // Asignar a jugadores
        this.state.players.forEach((player, index) => {
            player.role = shuffledRoles[index];
            // Asignar facción basada en el rol
            if ([Role.MERLIN, Role.PERCIVAL, Role.LOYAL_SERVANT].includes(player.role)) {
                player.faction = Faction.RESISTANCE;
            } else {
                player.faction = Faction.SPIES;
            }
        });
    }

    // --- LOGICA DE VOTACIÓN DE LÍDER ---
    voteLeader(playerId: string, approve: boolean | null) {
        this.state.leaderVotes[playerId] = approve;

        // Comprobar si todos han votado
        if (Object.keys(this.state.leaderVotes).length === this.state.players.length) {
            this.resolveLeaderVote();
        }
    }

    private resolveLeaderVote() {
        const votes = Object.values(this.state.leaderVotes);
        const approves = votes.filter(v => v === true).length;
        const rejects = votes.filter(v => v === false).length;
        // Los nulos (timeout) no suman a ninguno, o cuentan como reject implícito?
        // "Si llega a 0... su voto no cuenta". Simplemente no suma.

        this.log(`Votación de Líder: ${approves} A favor - ${rejects} En contra.`);

        if (approves > rejects) {
            // Líder Aprobado -> Fase de Construcción de Equipo
            this.state.phase = GamePhase.TEAM_BUILDING;
            this.state.proposedTeam = []; // Reset team selection
            this.log('Líder confirmado. Ahora debe proponer un equipo.');
        } else {
            // Líder Rechazado -> Siguiente líder
            this.log('Líder rechazado. Pasando turno al siguiente jugador.');
            this.nextLeader(); // Esto pondrá phase en VOTE_LEADER de nuevo
        }
    }

    proposeTeam(playerIds: string[]): boolean {
        // Validar tamaño del equipo según la ronda
        const config = GAME_CONFIG[this.state.players.length as keyof typeof GAME_CONFIG];
        const requiredSize = config.quests[this.state.currentRound - 1];

        if (playerIds.length !== requiredSize) return false;

        this.state.proposedTeam = playerIds;
        this.state.phase = GamePhase.MISSION; // Ir directamente a la misión
        this.state.missionVotes = []; // Resetear votos de misión
        this.state.failedVotesCount = 0; // Reset contador de rechazos
        this.log(`El líder ha seleccionado un equipo de ${playerIds.length} personas. ¡Comienza la misión!`);
        return true;
    }

    voteForTeam(playerId: string, approve: boolean) {
        this.state.teamVotes[playerId] = approve;

        // Comprobar si todos han votado
        if (Object.keys(this.state.teamVotes).length === this.state.players.length) {
            this.resolveTeamVote();
        }
    }

    private resolveTeamVote() {
        const votes = Object.values(this.state.teamVotes);
        const approves = votes.filter(v => v).length;
        const rejects = votes.length - approves;

        this.log(`Votación completada: ${approves} A favor - ${rejects} En contra.`);

        if (approves > rejects) {
            // Equipo Aprobado
            this.state.phase = GamePhase.MISSION;
            this.state.missionVotes = [];
            this.state.failedVotesCount = 0;
            this.log('El equipo ha sido aprobado. ¡Comienza la misión!');
        } else {
            // Equipo Rechazado
            this.state.failedVotesCount++;
            this.state.proposedTeam = [];

            if (this.state.failedVotesCount >= 5) {
                this.endGame(Faction.SPIES, 'Se han rechazado 5 equipos consecutivos.');
            } else {
                this.nextLeader(); // Pasa a VOTE_LEADER
                this.log('El equipo fue rechazado. El liderazgo pasa al siguiente jugador.');
            }
        }
    }

    voteMission(success: boolean) {
        this.state.missionVotes.push(success);

        // Comprobar si todos los miembros del equipo han votado
        if (this.state.missionVotes.length === this.state.proposedTeam.length) {
            this.resolveMission();
        }
    }

    private resolveMission() {
        const fails = this.state.missionVotes.filter(v => !v).length;
        const successes = this.state.missionVotes.filter(v => v).length;
        const playerCount = this.state.players.length;
        const round = this.state.currentRound;

        // Regla especial: 4ta misión con 7+ jugadores necesita 2 fallos
        let failsRequired = 1;
        if (playerCount >= 7 && round === 4) {
            failsRequired = 2;
        }

        const isSuccess = fails < failsRequired;

        // 1. BARAJAR los votos para que no se sepa quién votó qué
        const shuffledVotes = [...this.state.missionVotes].sort(() => Math.random() - 0.5);

        // 2. Guardar en el histórico
        const missionRecord = {
            round,
            team: [...this.state.proposedTeam],
            votes: shuffledVotes,
            successes,
            fails,
            isSuccess,
            leaderId: this.state.currentLeaderId
        };
        this.state.missionHistory.push(missionRecord);

        // 3. Actualizar resultado de la quest
        this.state.questResults[round - 1] = isSuccess;

        // 4. Pasar a fase MISSION_REVEAL (mostrar cartas una a una)
        this.state.phase = GamePhase.MISSION_REVEAL;
        this.state.revealedVotes = shuffledVotes; // Las cartas a revelar

        this.log(`Misión ${round} completada. Revelando votos...`);
    }

    // Método para avanzar desde MISSION_REVEAL a MISSION_RESULT
    finishReveal() {
        this.state.phase = GamePhase.MISSION_RESULT;
    }

    // Método para avanzar desde MISSION_RESULT y continuar el juego
    finishMissionResult() {
        const round = this.state.currentRound;
        const isSuccess = this.state.questResults[round - 1];

        this.log(`Misión ${round}: ${isSuccess ? 'ÉXITO' : 'FRACASO'}`);

        // Comprobar condiciones de victoria
        const successes = this.state.questResults.filter(r => r === true).length;
        const failures = this.state.questResults.filter(r => r === false).length;

        if (failures >= 3) {
            this.endGame(Faction.SPIES, 'Tres misiones han fracasado.');
        } else if (successes >= 3) {
            this.state.phase = GamePhase.ASSASSIN_PHASE;
            this.log('¡La Resistencia ha triunfado! Pero el Asesino tiene una última oportunidad...');
        } else {
            // Siguiente ronda
            this.state.currentRound++;
            this.nextLeader(); // Esto pone phase = VOTE_LEADER
            this.state.proposedTeam = [];
            this.state.missionVotes = [];
            this.state.revealedVotes = [];
        }
    }

    assassinKill(targetId: string) {
        const target = this.state.players.find(p => p.id === targetId);
        if (target && target.role === Role.MERLIN) {
            this.endGame(Faction.SPIES, '¡El Asesino ha eliminado a Marlenne (Merlín)!');
        } else {
            this.endGame(Faction.RESISTANCE, 'El Asesino ha fallado. ¡La Resistencia gana!');
        }
    }

    private nextLeader() {
        const currentIdx = this.state.players.findIndex(p => p.id === this.state.currentLeaderId);
        const nextIdx = (currentIdx + 1) % this.state.players.length;

        this.state.players[currentIdx].isLeader = false;
        this.state.players[nextIdx].isLeader = true;
        this.state.currentLeaderId = this.state.players[nextIdx].id;

        // Fase de confirmar al nuevo líder
        this.state.phase = GamePhase.VOTE_LEADER;
        this.state.leaderVotes = {};
    }

    private endGame(winner: Faction, reason: string) {
        this.state.winner = winner;
        this.state.phase = GamePhase.GAME_OVER;
        this.log(`FIN DEL JUEGO. Victoria para ${winner}. Razón: ${reason}`);
    }

    private log(message: string) {
        this.state.history.push(message);
        // Mantener solo los últimos 50 mensajes
        if (this.state.history.length > 50) this.state.history.shift();
    }
}
