import { Component, Input, OnInit, inject } from '@angular/core';
//import { DecimalPipe } from '@angular/common';
import { MatCardModule } from '@angular/material/card';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';

import { FortificationCardContentComponent } from '../fortification-card-content/fortification-card-content.component';
//import { HWMember } from '@models';
import { HWGuildWarFortification, HWGuildWarHeroTeam, HWGuildWarSlots, HWGuildWarTitanTeam, HWMember } from '@models';
import { HWDataService } from '@services';
import { combineLatest } from 'rxjs';

@Component({
    selector: 'app-guildwar-defence',
    imports: [MatCardModule, MatDividerModule, MatIconModule, FortificationCardContentComponent],
    templateUrl: './guildwar-defence.component.html',
    styleUrl: './guildwar-defence.component.scss',
})
export class GuildwarDefenceComponent implements OnInit {
    private _dataService = inject(HWDataService);
    private _championsByPower: HWMember[] = [];
    private _championSlots: number[] = [];
    private _slots: HWGuildWarSlots = {};
    public guildMembers: HWMember[] = [];
    public teamType: string = '';
    public title = 'Fortifications';
    public subtitle = 'Guild War Defence';

    @Input() set members(value: HWMember[]) {
        this.guildMembers = value;
    }

    @Input() set type(value: string) {
        this.teamType = value;
    }

    ngOnInit() {
        combineLatest([this._dataService.guildWarData$, this._dataService.guildWarSlots$]).subscribe({
            next: ([guildWarData, guildWarSlotsData]) => {
                this._slots = guildWarSlotsData.slots;
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                for (const [teamId, teamValues] of Object.entries(guildWarData.teams as Record<string, any>)) {
                    const index = this.guildMembers.findIndex((member) => member.id === teamId);
                    if (index === -1) continue;
                    let totalHeroPower = 0;
                    let totalTitanPower = 0;
                    const heroes: HWGuildWarHeroTeam[] = [];
                    const titans: HWGuildWarTitanTeam[] = [];
                    this.guildMembers[index].heroes = { power: totalHeroPower, teams: heroes };
                    this.guildMembers[index].titans = { power: totalTitanPower, teams: titans };
                    for (const unit of Object.entries(
                        teamValues.clanDefence_heroes.units as Record<string, HWGuildWarHeroTeam>,
                    )) {
                        heroes.push(unit[1]);
                        totalHeroPower += unit[1].power;
                    }
                    for (const unit of Object.entries(
                        teamValues.clanDefence_titans.units as Record<string, HWGuildWarTitanTeam>,
                    )) {
                        titans.push(unit[1]);
                        totalTitanPower += unit[1].power;
                    }
                    this.guildMembers[index].heroes = { power: totalHeroPower, teams: heroes };
                    this.guildMembers[index].titans = { power: totalTitanPower, teams: titans };
                }
                for (const data of Object.entries(guildWarData.slots as Record<string, number>)) {
                    this._championSlots[parseInt(data[0])] = data[1];
                }
                switch (this.teamType) {
                    case 'heroes':
                        this.title = 'Heroes Fortifications';
                        this.guildMembers.sort((a, b) => (a.heroes.power > b.heroes.power ? -1 : 1));
                        break;
                    case 'titans':
                        this.title = 'Titans Fortifications';
                        this.guildMembers.sort((a, b) => (a.titans.power > b.titans.power ? -1 : 1));
                        break;
                    default:
                        break;
                }
                this._championsByPower = this.guildMembers.filter((member) => member.champion === true);
            },
            error: (err) => console.error(err),
        });
    }

    private _getFortification(indexes: number[], type: string, name: string): HWGuildWarFortification {
        const teams: HWMember[] = [];
        const slots: HWGuildWarSlots = this._slots;
        let count = 0;
        indexes.forEach((data) => {
            const member = this._championsByPower[data];
            if (!member) return;
            switch (type) {
                case 'heroes':
                    teams.push(member);
                    count += member.heroes.power;
                    break;
                case 'titans':
                    teams.push(member);
                    count += member.titans.power;
                    break;
                default:
                    break;
            }
        });
        return {
            name: name,
            type: type,
            count: count,
            teams: teams,
            positions: this._championSlots,
            slots: slots[name],
        };
    }

    /*
    --------------------------------
    0 - 3 - 6
    1 - 4 - 7
    2 - 5 - 8
    --------------------------------
    9 - 10 - 11 - 12
    --------------------------------
    13 - 14 - 15 - 16 - 17 - 18 - 19
    --------------------------------
    Mage Academy    1-2-31
    Lighthouse      3-4-32
    Barracks        5-6-33
    Foundry         13-14-15-36
    Citadel         25-26-28-28-29-30-40
    */

    getLighthouse(): HWGuildWarFortification {
        const indexes: number[] = [0, 4, 8];
        return this._getFortification(indexes, 'heroes', 'Lighthouse');
    }

    getBarracks(): HWGuildWarFortification {
        const indexes: number[] = [1, 5, 6];
        return this._getFortification(indexes, 'heroes', 'Barracks');
    }

    getMageAcademy(): HWGuildWarFortification {
        const indexes: number[] = [2, 3, 7];
        return this._getFortification(indexes, 'heroes', 'Mage Academy');
    }

    getFoundry(): HWGuildWarFortification {
        const indexes: number[] = [9, 11, 12, 13];
        return this._getFortification(indexes, 'heroes', 'Foundry');
    }

    getCitadel(): HWGuildWarFortification {
        const indexes: number[] = [10, 14, 15, 16, 17, 18, 19];
        return this._getFortification(indexes, 'heroes', 'Citadel');
    }

    /*
    --------------------------------
    0 - 1 - 2 - 3
    --------------------------------
    4 - 8 - 12 - 16
    5 - 9 - 13 - 17
    6 - 10 - 14 - 18
    7 - 11 - 15 - 19
    --------------------------------
    Bridge              7-8-9-34
    Spring of Elements  10-11-12-35
    Gates of Nature     16-17-18-37
    Bastion of Fire     19-20-21-38
    Bastion of Ice      22-23-24-39
    */

    getBridge(): HWGuildWarFortification {
        const indexes: number[] = [0, 1, 2, 3];
        return this._getFortification(indexes, 'titans', 'Bridge');
    }

    getGatesOfNature(): HWGuildWarFortification {
        const indexes: number[] = [5, 10, 15, 16];
        return this._getFortification(indexes, 'titans', 'Gates Of Nature');
    }

    getBastionOfFire(): HWGuildWarFortification {
        const indexes: number[] = [6, 11, 12, 17];
        return this._getFortification(indexes, 'titans', 'Bastion Of Fire');
    }

    getBastionOfIce(): HWGuildWarFortification {
        const indexes: number[] = [4, 9, 14, 19];
        return this._getFortification(indexes, 'titans', 'Bastion Of Ice');
    }

    getSpringOfElements(): HWGuildWarFortification {
        const indexes: number[] = [7, 8, 13, 18];
        return this._getFortification(indexes, 'titans', 'Spring Of Elements');
    }
}
