package handlers

import (
	"html/template"
	"log"
	"net/http"
	"os"
	"strconv"

	"decor-by-hannahs/internal/auth"
	"decor-by-hannahs/internal/db"
)

type BookingWithService struct {
	ID                   int64
	ServiceName          string
	ServiceDescription   string
	ServicePriceCents    int32
	EventDate            string
	Address              string
	Notes                string
	Status               string
	CreatedAt            string
}

type ProfileData struct {
	Authenticated   bool
	Email           string
	DisplayName     string
	ID              string
	ActivePage      string
	Bookings        []BookingWithService
	OrySettingsURL  string
}

func ProfileHandler(q *db.Queries, tmpl *template.Template) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		pd := ProfileData{ActivePage: "profile"}

		user, err := auth.GetUser(r.Context())
		if err == nil {
			pd.Authenticated = true
			pd.Email = user.Email
			pd.ID = strconv.FormatInt(user.ID, 10)
			pd.DisplayName = user.Email

			bookings, err := q.ListBookingsWithServiceByUser(r.Context(), user.ID)
			if err != nil {
				log.Printf("Error fetching bookings: %v", err)
			} else {
				for _, b := range bookings {
					pd.Bookings = append(pd.Bookings, BookingWithService{
						ID:                 b.ID,
						ServiceName:        b.ServiceName,
						ServiceDescription: nullStringToString(b.ServiceDescription),
						ServicePriceCents:  b.ServicePriceCents,
						EventDate:          b.EventDate.Format("January 2, 2006"),
						Address:            nullStringToString(b.Address),
						Notes:              nullStringToString(b.Notes),
						Status:             b.Status,
						CreatedAt:          b.CreatedAt.Time.Format("Jan 2, 2006"),
					})
				}
			}

			oryAPIURL := os.Getenv("ORY_API_URL")
			if oryAPIURL == "" {
				tunnelPort := os.Getenv("TUNNEL_PORT")
				if tunnelPort == "" {
					tunnelPort = "4000"
				}
				oryAPIURL = "http://localhost:" + tunnelPort
			}
			pd.OrySettingsURL = oryAPIURL + "/ui/settings"
		}

		if err := tmpl.ExecuteTemplate(w, "profile.tmpl", pd); err != nil {
			http.Error(w, "failed to render profile", http.StatusInternalServerError)
			return
		}
	}
}
