package web

import (
	"net/http"
	"sort"

	"party.at/party/cmd/party/parlament"
	"party.at/party/cmd/party/common"
	"party.at/party/internal/data"
)

type factionGroup struct {
	Name    string
	Members []parlament.Member
}

func (web *Web) MembersOfParliamentPage(w http.ResponseWriter, r *http.Request) {
	members, err := web.App.Parlament.ListNRMembers("XXVIII")
	if err != nil {
		web.App.LogError(r, err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	// Group by FractionName, preserving insertion order for stable sort later.
	groupMap := make(map[string]*factionGroup)
	var factionOrder []string
	for _, m := range members {
		key := m.FractionName
		if _, exists := groupMap[key]; !exists {
			groupMap[key] = &factionGroup{Name: key}
			factionOrder = append(factionOrder, key)
		}
		groupMap[key].Members = append(groupMap[key].Members, m)
	}

	// Sort factions by descending seat count.
	sort.Slice(factionOrder, func(i, j int) bool {
		return len(groupMap[factionOrder[i]].Members) > len(groupMap[factionOrder[j]].Members)
	})

	// Sort members within each faction by last name.
	groups := make([]factionGroup, 0, len(factionOrder))
	for _, name := range factionOrder {
		g := groupMap[name]
		sort.Slice(g.Members, func(i, j int) bool {
			return g.Members[i].LastName < g.Members[j].LastName
		})
		groups = append(groups, *g)
	}

	web.render(w, r, http.StatusOK, "mps", struct {
		AuthenticatedUser *data.User
		Groups            []factionGroup
		Total             int
	}{
		AuthenticatedUser: common.GetUser(r),
		Groups:            groups,
		Total:             len(members),
	})
}
