package pages

import (
	"net/http"
	"errors"
	"log"
	"strconv"

	"forge.capytal.company/capytalcode/project-comicverse/lib/router/rerrors"
	"forge.capytal.company/capytalcode/project-comicverse/lib/cookies"
	"forge.capytal.company/capytalcode/project-comicverse/lib/forms"
	"forge.capytal.company/capytalcode/project-comicverse/templates/layouts"
)

type Dashboard struct {
	Message  string  `form:"message"`
	Limit    int     `form:"limit"`
	Optional *string `form:"optional"`
}

type DashboardCookie struct {
	Hello string `cookie:"dashboard-cookie"`
	Bool  bool
	Test  int
}

func (p *Dashboard) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if err := forms.Unmarshal(r, p); err != nil {
		forms.RerrUnsmarshal(err).ServeHTTP(w, r)
		return
	}

	hasCookie := true

	var c DashboardCookie
	if err := cookies.UnmarshalRequest(r, &c); errors.Is(err, cookies.ErrNoCookie{}) {
		hasCookie = false
		c = DashboardCookie{Hello: "Hello world", Bool: true, Test: 69420}
	} else if err != nil {
		rerrors.InternalError(err).ServeHTTP(w, r)
		return
	} else {
		hasCookie = true
	}

	log.Print(hasCookie, c)

	if ck, err := cookies.Marshal(c); err != nil {
		rerrors.InternalError(err).ServeHTTP(w, r)
	} else {
		http.SetCookie(w, ck)
	}

	if err := p.Component().Render(r.Context(), w); err != nil {
		rerrors.InternalError(err).ServeHTTP(w, r)
		return
	}
}

templ (p *Dashboard) Component() {
	@layouts.Page() {
		<div class="text-danger-100 font-sans">
			<p>{ p.Message }</p>
			<p>{ strconv.Itoa(p.Limit) }</p>
			if p.Optional != nil {
				<p>{ *p.Optional }</p>
			} else {
				<p>nil</p>
			}
		</div>
	}
}
