package server

import (
	"net/http"
	"net/url"
	"sort"
	"strconv"
	"strings"
	"time"

	"gitlab.com/Timfa/bluegit/internal/access"
	"gitlab.com/Timfa/bluegit/internal/i18n"
	"gitlab.com/Timfa/bluegit/internal/store"
)

// FlowBoard is de lijst van merge requests of issues, in de opbouw van GitLab.
type FlowBoard struct {
	Base     string
	Query    string
	Sort     string
	Dir      string
	State    string
	FlipHref string
	CanNew   bool
	NewHref  string
	NewKey   string
	EmptyKey string
	Filters  bool
	Label    string
	Assignee string
	Labels   []IssueChoice
	People   []IssueChoice
	Tabs     []FlowTab
	Rows     []FlowRow
}

// FlowTab is één statusfilter met een teller.
type FlowTab struct {
	Href  string
	Key   string
	Count int
	On    bool
}

// FlowRow is één regel in die lijst.
type FlowRow struct {
	Href         string
	Title        string
	Ref          string
	State        string
	StateLabel   string
	Created      string
	Updated      string
	Author       string
	AuthorURL    string
	Target       string
	Comments     int
	PipeStatus   string
	PipeLabel    string
	PipeHref     string
	Draft        bool
	Confidential bool
	Labels       []store.Label
	People       []AccountLink
	Extra        string
}

type flowPerson struct {
	Name string
	URL  string
}

func (s *Server) flowMRs(r *http.Request, repo store.Repo, role access.Role, all []store.MergeRequest) *FlowBoard {
	q := strings.TrimSpace(r.URL.Query().Get("q"))
	sortKey := flowSortKey(r.URL.Query().Get("sort"))
	dir := flowDirKey(r.URL.Query().Get("dir"))
	state := flowStateKey(r.URL.Query().Get("state"), true)
	base := "/" + repo.FullPath() + "/-/merge-requests"
	people := map[string]flowPerson{}

	var matched []store.MergeRequest
	openN, mergedN, closedN := 0, 0, 0
	for _, mr := range all {
		name, _ := s.flowAuthor(r, mr.Author, people)
		if !flowHit(q, mr.Title, mr.Description, strconv.FormatInt(mr.Number, 10), "!"+strconv.FormatInt(mr.Number, 10), mr.Author, name, mr.SourceBranch, mr.TargetBranch) {
			continue
		}
		matched = append(matched, mr)
		switch mr.Status {
		case "merged":
			mergedN++
		case "closed":
			closedN++
		default:
			openN++
		}
	}
	var shown []store.MergeRequest
	for _, mr := range matched {
		if state == "all" || mr.Status == state || (state == "open" && mr.Status != "merged" && mr.Status != "closed") {
			shown = append(shown, mr)
		}
	}
	sortFlow(shown, sortKey, dir, func(i int) (time.Time, time.Time, int64) {
		return shown[i].CreatedAt, shown[i].UpdatedAt, shown[i].Number
	})

	rows := make([]FlowRow, 0, len(shown))
	for _, mr := range shown {
		name, href := s.flowAuthor(r, mr.Author, people)
		row := FlowRow{
			Href:       base + "/" + strconv.FormatInt(mr.Number, 10),
			Title:      mr.Title,
			Ref:        "!" + strconv.FormatInt(mr.Number, 10),
			State:      flowBadge(mr.Status),
			StateLabel: s.flowStateLabel(r, mr.Status),
			Created:    s.ago(r, mr.CreatedAt),
			Updated:    s.ago(r, mr.UpdatedAt),
			Author:     name,
			AuthorURL:  href,
			Draft:      mr.Draft,
		}
		if row.State == "open" {
			row.Target = mr.TargetBranch
			if notes, err := s.Store.ListNotes(r.Context(), mr.ID); err == nil {
				row.Comments = len(notes)
			}
			s.attachFlowPipe(r, repo, mr, &row)
		}
		rows = append(rows, row)
	}
	board := &FlowBoard{
		Base: base, Query: q, Sort: sortKey, Dir: dir, State: state,
		FlipHref: flowHref(base, state, q, sortKey, flipDir(dir), "", ""),
		CanNew:   role.CanWriteCode(),
		NewHref:  base + "/new",
		NewKey:   "list.newMR",
		EmptyKey: "mr.none",
		Rows:     rows,
	}
	board.Tabs = []FlowTab{
		{Href: flowHref(base, "open", q, sortKey, dir, "", ""), Key: "issue.open", Count: openN, On: state == "open"},
		{Href: flowHref(base, "merged", q, sortKey, dir, "", ""), Key: "list.merged", Count: mergedN, On: state == "merged"},
		{Href: flowHref(base, "closed", q, sortKey, dir, "", ""), Key: "issue.closed", Count: closedN, On: state == "closed"},
		{Href: flowHref(base, "all", q, sortKey, dir, "", ""), Key: "issue.all", Count: openN + mergedN + closedN, On: state == "all"},
	}
	return board
}

func (s *Server) flowIssues(r *http.Request, repo store.Repo, b *IssueBoard, all []store.Issue) *FlowBoard {
	q := b.Query
	sortKey := flowSortKey(r.URL.Query().Get("sort"))
	dir := flowDirKey(r.URL.Query().Get("dir"))
	state := flowStateKey(r.URL.Query().Get("state"), false)
	base := "/" + repo.FullPath() + "/-/issues"
	people := map[string]flowPerson{}

	var matched []store.Issue
	openN, closedN := 0, 0
	for _, iss := range all {
		name, _ := s.flowAuthor(r, iss.Author, people)
		bits := append(issueSearchBits(iss), name)
		if !flowHit(q, bits...) {
			continue
		}
		matched = append(matched, iss)
		if iss.Status == "closed" {
			closedN++
		} else {
			openN++
		}
	}
	var shown []store.Issue
	for _, iss := range matched {
		if state == "all" || iss.Status == state || (state == "open" && iss.Status != "closed") {
			shown = append(shown, iss)
		}
	}
	sortFlow(shown, sortKey, dir, func(i int) (time.Time, time.Time, int64) {
		return shown[i].CreatedAt, shown[i].UpdatedAt, shown[i].Number
	})

	rows := make([]FlowRow, 0, len(shown))
	for _, iss := range shown {
		name, href := s.flowAuthor(r, iss.Author, people)
		var assigned []AccountLink
		for _, who := range iss.Assignees {
			n, href := s.flowAuthor(r, who, people)
			if n == "" {
				continue
			}
			assigned = append(assigned, AccountLink{Name: n, URL: href})
		}
		row := FlowRow{
			Href:         base + "/" + strconv.FormatInt(iss.Number, 10),
			Title:        iss.Title,
			Ref:          "#" + strconv.FormatInt(iss.Number, 10),
			State:        flowBadge(iss.Status),
			StateLabel:   s.flowStateLabel(r, iss.Status),
			Created:      s.ago(r, iss.CreatedAt),
			Updated:      s.ago(r, iss.UpdatedAt),
			Author:       name,
			AuthorURL:    href,
			Confidential: iss.Confidential,
			Labels:       iss.Labels,
			People:       assigned,
			Extra:        iss.Milestone,
		}
		if row.State == "open" {
			if notes, err := s.Store.ListIssueNotes(r.Context(), iss.ID); err == nil {
				row.Comments = len(notes)
			}
		}
		rows = append(rows, row)
	}
	return &FlowBoard{
		Base: base, Query: q, Sort: sortKey, Dir: dir, State: state,
		FlipHref: flowHref(base, state, q, sortKey, flipDir(dir), b.Label, b.Assignee),
		CanNew:   b.CanCreate,
		NewHref:  base + "/new",
		NewKey:   "issue.new",
		EmptyKey: "issue.none",
		Filters:  true,
		Label:    b.Label,
		Assignee: b.Assignee,
		Labels:   b.Labels,
		People:   b.People,
		Rows:     rows,
		Tabs: []FlowTab{
			{Href: flowHref(base, "open", q, sortKey, dir, b.Label, b.Assignee), Key: "issue.open", Count: openN, On: state == "open"},
			{Href: flowHref(base, "closed", q, sortKey, dir, b.Label, b.Assignee), Key: "issue.closed", Count: closedN, On: state == "closed"},
			{Href: flowHref(base, "all", q, sortKey, dir, b.Label, b.Assignee), Key: "issue.all", Count: openN + closedN, On: state == "all"},
		},
	}
}

func (s *Server) attachFlowPipe(r *http.Request, repo store.Repo, mr store.MergeRequest, row *FlowRow) {
	p, err := s.Store.LatestMergePipeline(r.Context(), repo.ID, mr.ID)
	if err != nil {
		return
	}
	jobs, _ := s.Store.JobsByPipeline(r.Context(), p.ID)
	st := displayStatus(s.pipeStatusFor(p), jobs)
	row.PipeStatus = st
	row.PipeLabel = s.tr(r, "pipe."+st)
	row.PipeHref = "/" + repo.FullPath() + "/-/pipelines/" + strconv.FormatInt(p.ID, 10)
}

func (s *Server) flowAuthor(r *http.Request, username string, cache map[string]flowPerson) (string, string) {
	username = strings.TrimSpace(username)
	if username == "" {
		return "", ""
	}
	if p, ok := cache[username]; ok {
		return p.Name, p.URL
	}
	p := flowPerson{Name: username}
	if u, err := s.Store.UserByUsername(r.Context(), username); err == nil && u.ID != 0 {
		if name := strings.TrimSpace(u.DisplayName); name != "" {
			p.Name = name
		} else {
			p.Name = u.Username
		}
		p.URL = "/users/" + u.Username
	}
	cache[username] = p
	return p.Name, p.URL
}

func (s *Server) flowStateLabel(r *http.Request, status string) string {
	switch status {
	case "merged":
		return s.tr(r, "list.merged")
	case "closed":
		return s.tr(r, "issue.closed")
	default:
		return s.tr(r, "issue.open")
	}
}

func (s *Server) ago(r *http.Request, t time.Time) string {
	if t.IsZero() {
		return ""
	}
	return i18n.Ago(s.langOf(r), t.Unix())
}

func issueSearchBits(iss store.Issue) []string {
	bits := []string{iss.Title, iss.Description, strconv.FormatInt(iss.Number, 10), "#" + strconv.FormatInt(iss.Number, 10), iss.Author, iss.Milestone}
	bits = append(bits, iss.Assignees...)
	for _, l := range iss.Labels {
		bits = append(bits, l.Name)
	}
	return bits
}

func flowHit(q string, parts ...string) bool {
	q = strings.ToLower(strings.TrimSpace(q))
	if q == "" {
		return true
	}
	q = strings.TrimPrefix(q, "!")
	q = strings.TrimPrefix(q, "#")
	for _, p := range parts {
		if strings.Contains(strings.ToLower(p), q) {
			return true
		}
	}
	return false
}

func flowSortKey(raw string) string {
	if raw == "updated" {
		return "updated"
	}
	return "created"
}

func flowDirKey(raw string) string {
	if raw == "asc" {
		return "asc"
	}
	return "desc"
}

func flipDir(dir string) string {
	if dir == "asc" {
		return "desc"
	}
	return "asc"
}

func flowStateKey(raw string, merged bool) string {
	switch raw {
	case "closed", "all":
		return raw
	case "merged":
		if merged {
			return "merged"
		}
	}
	return "open"
}

func flowBadge(status string) string {
	switch status {
	case "merged", "closed":
		return status
	default:
		return "open"
	}
}

func flowHref(base, state, q, sortKey, dir, label, assignee string) string {
	v := url.Values{}
	v.Set("state", state)
	if strings.TrimSpace(q) != "" {
		v.Set("q", q)
	}
	if sortKey == "updated" {
		v.Set("sort", "updated")
	}
	if dir == "asc" {
		v.Set("dir", "asc")
	}
	if label != "" {
		v.Set("label", label)
	}
	if assignee != "" {
		v.Set("assignee", assignee)
	}
	return base + "?" + v.Encode()
}

func sortFlow[T any](rows []T, sortKey, dir string, at func(i int) (created, updated time.Time, number int64)) {
	sort.SliceStable(rows, func(i, j int) bool {
		ac, au, an := at(i)
		bc, bu, bn := at(j)
		a, b := ac, bc
		if sortKey == "updated" {
			a, b = au, bu
		}
		if dir == "asc" {
			if a.Equal(b) {
				return an < bn
			}
			return a.Before(b)
		}
		if a.Equal(b) {
			return an > bn
		}
		return a.After(b)
	})
}
