package handlers

import (
	"log"
	"net/http"

	"github.com/patel-mann/poll-system/app/internal/models"
	"github.com/patel-mann/poll-system/app/internal/utils"
)


func AdminDashboardHandler(w http.ResponseWriter, r *http.Request) {
	currentAdminID := r.Context().Value("user_id").(int)
	username,_ := models.GetCurrentUserName(r)
	role, _ := r.Context().Value("uesr_role").(int)

    var volunteerCount int
	var totalDonations float64
	var validatedCount int
	var housesLeftPercent float64

	// 1. Count volunteers assigned to this admin
	err := models.DB.QueryRow(`
		SELECT COUNT(av.volunteer_id) 
		FROM admin_volunteers av
		WHERE av.admin_id = $1 AND av.is_active = TRUE;
	`, currentAdminID).Scan(&volunteerCount)
	if err != nil {
		log.Println("Volunteer query error:", err)
		volunteerCount = 0 // Set default value on error
	}

	// 2. Total donations from polls
	err = models.DB.QueryRow(`
		SELECT COALESCE(SUM(amount_donated), 0) 
		FROM poll;
	`).Scan(&totalDonations)
	if err != nil {
		log.Println("Donation query error:", err)
		totalDonations = 0 // Set default value on error
	}

	// 3. Count validated addresses
	err = models.DB.QueryRow(`
		SELECT COUNT(*) 
		FROM address_database
		WHERE visited_validated = TRUE;
	`).Scan(&validatedCount)
	if err != nil {
		log.Println("Validated addresses query error:", err)
		validatedCount = 0 // Set default value on error
	}

	// 4. Calculate percentage of houses left to visit
	err = models.DB.QueryRow(`
		SELECT 
			CASE 
				WHEN COUNT(*) = 0 THEN 0
				ELSE ROUND(
					(COUNT(*) FILTER (WHERE visited_validated = FALSE)::numeric / COUNT(*)::numeric) * 100, 2
				)
			END
		FROM address_database;
	`).Scan(&housesLeftPercent)
	if err != nil {
		log.Println("Houses left query error:", err)
		housesLeftPercent = 0 // Set default value on error
	}

	utils.Render(w, "dashboard/dashboard.html", map[string]interface{}{
		"Title":              "Admin Dashboard",
		"IsAuthenticated":    true,
		"VolunteerCount":     volunteerCount,
		"TotalDonations":     totalDonations,
		"ValidatedCount":     validatedCount,
		"HousesLeftPercent":  housesLeftPercent,
		"ShowAdminNav": 	  true,
		"UserName": 	username,
		"Role": 			  role,
		"ActiveSection":      "dashboard",
	})
}