package renderer

import (
	"encoding/json"
	"html/template"
	"net/http"

	mobilityaccountsstorage "git.coopgo.io/coopgo-platform/mobility-accounts/storage"
)

const groupMenu = "group_module"

type BeneficiariesList struct {
	Group         string `json:"group"`
	Count         int    `json:"count"`
	CacheId       string `json:"cache_id"`
	Beneficiaries []any  `json:"beneficiaries"`
}

func (s BeneficiariesList) JSON() template.JS {
	result, _ := json.Marshal(s)
	return template.JS(result)
}

func (s BeneficiariesList) JSONWithLimits(a int, b int) template.JS {
	if b < len(s.Beneficiaries) {
		s.Beneficiaries = s.Beneficiaries[a:b]
	}
	return s.JSON()
}

func (renderer *Renderer) Groups(w http.ResponseWriter, r *http.Request, groups any) {
	files := renderer.ThemeConfig.GetStringSlice("views.group_module.home.files")
	state := NewState(r, renderer.ThemeConfig, groupMenu)
	state.ViewState = map[string]any{
		"groups": groups,
	}

	renderer.Render("group_module", w, r, files, state)
}

func (renderer *Renderer) CreateGroupModule(w http.ResponseWriter, r *http.Request, group_types []string) {
	files := renderer.ThemeConfig.GetStringSlice("views.group_module.create_group.files")
	state := NewState(r, renderer.ThemeConfig, groupMenu)
	state.ViewState = map[string]any{
		"group_types": group_types,
	}
	renderer.Render("group_module", w, r, files, state)
}

func (renderer *Renderer) DisplayGroupModule(w http.ResponseWriter, r *http.Request, groupid string, accounts []any, cacheid string, searched bool, beneficiary any, group any, beneficiaries []mobilityaccountsstorage.Account) {
	files := renderer.ThemeConfig.GetStringSlice("views.group_module.display_group.files")
	state := NewState(r, renderer.ThemeConfig, groupMenu)

	viewstate := map[string]any{
		"beneficiaries": beneficiaries,
		"searched":      searched,
		"group":         group,
		"list": BeneficiariesList{
			Group:         groupid,
			Count:         len(accounts),
			CacheId:       cacheid,
			Beneficiaries: accounts,
		},
	}

	if searched {
		viewstate["search"] = map[string]any{
			"beneficiary": beneficiary,
		}

	}

	state.ViewState = viewstate

	renderer.Render("beneficiaries_list", w, r, files, state)
}
