package renders

import (
	"cangui/whatsapp/backend/models"
	"net/http"
	"strconv"
	"text/template"
	"time"

	"github.com/gorilla/mux"
	"gorm.io/gorm"
)


func Login(w http.ResponseWriter, r *http.Request){
	renderTemplate(w,"login",nil)
}
func JwtTest(w http.ResponseWriter, r *http.Request){
	renderTemplate(w,"jwt",nil)
}
func TestMessagesPages(w http.ResponseWriter, r *http.Request){
	renderTemplate(w,"test-send",nil)
}
func TestMessagesPages2(w http.ResponseWriter, r *http.Request){
	renderTemplate(w,"test",nil)
}
func AdminUserEdit(db *gorm.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		id, _ := strconv.Atoi(mux.Vars(r)["id"])
		var user models.User
		if err := db.First(&user, id).Error; err != nil {
			http.Error(w, "Utilisateur introuvable", http.StatusNotFound)
			return
		}

		data := map[string]interface{}{
			"User": user,
		}
		renderPartial(w, "admin_user_edit", data)
	}
}
func AdminUserCreate() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		data := map[string]interface{}{
			"User": models.User{},
		}
		renderPartial(w, "admin_user_edit", data)
	}
}
func AdminConversationPage(db *gorm.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		idStr := mux.Vars(r)["id"]
		data := map[string]interface{}{
			"UserID": idStr,
		}
		renderTemplate(w, "admin_conversations", data)
	}
}

func AdminConversationRows(db *gorm.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		idStr := mux.Vars(r)["id"]
		id, _ := strconv.Atoi(idStr)
		typeFilter := r.URL.Query().Get("type")

		var convs []models.Conversation
		query := db.Where("user_id = ?", id)
		if typeFilter != "" {
			query = query.Where("type = ?", typeFilter)
		}
		query.Order("created_at desc").Find(&convs)

		data := map[string]interface{}{
			"Conversations": convs,
			"UserID":        idStr,
		}
		renderPartial(w, "admin_conversations_rows", data)
	}
}

func AdminConversationThread(db *gorm.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		idStr := mux.Vars(r)["id"]
		id, _ := strconv.Atoi(idStr)

		var convs []models.Conversation
		db.Where("user_id = ?", id).Order("created_at asc").Find(&convs)

		data := map[string]interface{}{
			"Conversations": convs,
			"UserID":        idStr,
		}
		renderPartial(w, "admin_conversations_thread", data)
	}
}
func Dashboard(db *gorm.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		val := r.Context().Value("ssoid")
		ssoid, ok := val.(string)
		if !ok || ssoid == "" {
			http.Error(w, "Utilisateur non authentifié", http.StatusUnauthorized)
			return
		}
				

		var user models.User
		if err := db.Where("sso_id = ?", ssoid).First(&user).Error; err != nil {
			http.Error(w, "Utilisateur introuvable", http.StatusUnauthorized)
			return
		}

		filter := r.URL.Query().Get("filter")
		var fromDate time.Time
		now := time.Now()

		switch filter {
		case "today":
			fromDate = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
		case "week":
			fromDate = now.AddDate(0, 0, -7)
		default:
			fromDate = time.Time{} // zero time: no filter
		}

		var totalUsers int64
		var totalCredits uint
		var totalConversations int64
		var conversations []models.Conversation

		if user.Role == models.ROLE_ADMIN {
			db.Model(&models.User{}).Count(&totalUsers)
			db.Model(&models.Consumption{}).Select("SUM(credits_used)").Scan(&totalCredits)
			db.Model(&models.Conversation{}).Where("created_at >= ?", fromDate).Count(&totalConversations)
			db.Where("created_at >= ?", fromDate).Order("created_at desc").Limit(10).Find(&conversations)
		} else {
			db.Model(&models.User{}).Where("id = ?", user.ID).Count(&totalUsers)
			db.Model(&models.Consumption{}).Where("user_id = ?", user.ID).Select("SUM(credits_used)").Scan(&totalCredits)
			db.Model(&models.Conversation{}).Where("user_id = ? AND created_at >= ?", user.ID, fromDate).Count(&totalConversations)
			db.Where("user_id = ? AND created_at >= ?", user.ID, fromDate).Order("created_at desc").Limit(10).Find(&conversations)
		}

		data := map[string]interface{}{
			"User": user,
			"Stats": map[string]interface{}{
				"TotalUsers":         totalUsers,
				"TotalCreditsUsed":  totalCredits,
				"TotalConversations": totalConversations,
			},
			"Conversations": conversations,
		}

		renderTemplate(w, "dashboard", data)
	}
}



func renderTemplate(w http.ResponseWriter, templ string, data map[string]interface{}) {
    t, err := template.ParseFiles(
        "./frontend/templates/head.pages.tmpl",      // Template inclus
        "./frontend/templates/" + templ + ".pages.tmpl", // Template principal
    )

    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    // Exécutez explicitement le template principal
    err = t.ExecuteTemplate(w, templ+".pages.tmpl", data)

    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

func renderPartial(w http.ResponseWriter, templ string, data map[string]interface{}) {
    t, err := template.ParseFiles("./frontend/templates/" + templ + ".pages.tmpl")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    err = t.Execute(w, data)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

