package templates

import (
	"strings"

	. "primesys_email/src/models/report"
	"primesys_email/src/templates/utils"

	"github.com/xuri/excelize/v2"
)

const overSpeedLimit = 8

// BuildSectionCounts groups the reports by section name, keeping the order in
// which sections first appear, and counts completed / not completed / off / over speed.
func BuildSectionCounts(reports []DivisionTripReportModel) []SectionCountReport {
	if len(reports) == 0 {
		return []SectionCountReport{}
	}

	// Go maps are unordered, so keep section order separately (LinkedHashMap in Java)
	grouped := make(map[string][]DivisionTripReportModel)
	var sectionOrder []string

	for _, r := range reports {
		section := "Unknown"
		if r.SectionName != nil {
			section = *r.SectionName
		}

		if _, ok := grouped[section]; !ok {
			sectionOrder = append(sectionOrder, section)
		}
		grouped[section] = append(grouped[section], r)
	}

	result := make([]SectionCountReport, 0, len(sectionOrder))
	for _, section := range sectionOrder {
		result = append(result, buildSingleSection(section, grouped[section]))
	}
	return result
}

func buildSingleSection(sectionName string, reports []DivisionTripReportModel) SectionCountReport {
	count := SectionCountReport{
		SectionName: sectionName,
		Total:       len(reports),
	}

	var notDoneNames, offNames, speedNames []string

	for _, r := range reports {
		remark := ""
		if r.Remark != nil {
			remark = *r.Remark
		}

		name := "-"
		if r.DeviceName != nil {
			name = *r.DeviceName
		}

		switch {
		case strings.Contains(remark, "Device was Off"):
			count.Off++
			offNames = append(offNames, name)
		case strings.Contains(remark, "All work done successfully"):
			count.Completed++
		case strings.Contains(remark, "Trip not completed"),
			strings.Contains(remark, "Trip not schedule"),
			strings.Contains(remark, "Working on off track"),
			strings.Contains(remark, "Off Track"):
			count.NotCompleted++
			notDoneNames = append(notDoneNames, name)
		}

		if r.TripMaxSpeed != nil && *r.TripMaxSpeed > overSpeedLimit {
			count.OverSpeed++
			speedNames = append(speedNames, name)
		}
	}

	count.NotCompletedNames = strings.Join(notDoneNames, ", ")
	count.OffNames = strings.Join(offNames, ", ")
	count.OverSpeedNames = strings.Join(speedNames, ", ")

	return count
}

// TotalRowStyle is the dark teal style for the section count total row
func TotalRowStyle(f *excelize.File) int {
	return utils.CreateStyle(f, map[string]any{
		"font": &excelize.Font{Family: "Arial", Size: 8, Bold: true, Color: "FFFFFF"},
		"fill": excelize.Fill{Type: "pattern", Pattern: 1, Color: []string{"014545"}},
		"alignment": &excelize.Alignment{
			Horizontal: "center", Vertical: "center",
		},
		"border": utils.ThinBorders("013232"),
	})
}
