package handlers

import (
	"encoding/json"
	"html/template"
	"minecraft-profile/middleware"
	"minecraft-profile/models"
	"net/http"
	"time"
)

func ProfileHandler(w http.ResponseWriter, r *http.Request) {
	session := r.Context().Value(middleware.SessionContextKey).(*middleware.SessionData)
	user, exists := models.GetUser(session.Username)

	if !exists {
		http.Redirect(w, r, "/login", http.StatusSeeOther)
		return
	}

	historyJSON, _ := json.Marshal(user.SkinHistory)

	data := map[string]interface{}{
		"Username":    user.Username,
		"Email":       user.Email,
		"Role":        user.Role,
		"CurrentSkin": user.CurrentSkin,
		"SkinHistory": string(historyJSON),
	}

	tmpl := template.Must(template.ParseFiles("templates/profile.html"))
	tmpl.Execute(w, data)
}

func UpdateUserHandler(w http.ResponseWriter, r *http.Request) {
	session := r.Context().Value(middleware.SessionContextKey).(*middleware.SessionData)

	var updates map[string]string
	if err := json.NewDecoder(r.Body).Decode(&updates); err != nil {
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	if !models.UpdateUser(session.Username, updates) {
		http.Error(w, "Failed to update user", http.StatusInternalServerError)
		return
	}

	user, _ := models.GetUser(session.Username)

	newSession := middleware.CreateSession(user.Username, user.Role)
	http.SetCookie(w, &http.Cookie{
		Name:     "session",
		Value:    newSession,
		Path:     "/",
		HttpOnly: true,
		SameSite: http.SameSiteStrictMode,
	})

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"status":       "success",
		"username":     user.Username,
		"email":        user.Email,
		"role":         user.Role,
		"current_skin": user.CurrentSkin,
		"skin_history": user.SkinHistory,
	})
}

func AddToSkinHistoryHandler(w http.ResponseWriter, r *http.Request) {
	session := r.Context().Value(middleware.SessionContextKey).(*middleware.SessionData)

	var request struct {
		URL  string `json:"url"`
		Name string `json:"name"`
	}

	if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	user, exists := models.GetUser(session.Username)
	if !exists {
		http.Error(w, "User not found", http.StatusNotFound)
		return
	}

	newHistory := []models.SkinHistoryItem{}
	for _, item := range user.SkinHistory {
		if item.URL != request.URL {
			newHistory = append(newHistory, item)
		}
	}

	newHistory = append([]models.SkinHistoryItem{{
		URL:       request.URL,
		Name:      request.Name,
		Timestamp: time.Now(),
	}}, newHistory...)

	if len(newHistory) > 10 {
		newHistory = newHistory[:10]
	}

	user.SkinHistory = newHistory

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"status":       "success",
		"skin_history": user.SkinHistory,
	})
}
