package handlers

import (
	"database/sql"
	"fmt"
	"log"
	"net/http"
	"strconv"

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


func VolunteerHandler(w http.ResponseWriter, r *http.Request) {
	// TODO: Replace this with actual session/jwt extraction
	currentAdminID := r.Context().Value("user_id").(int)
	username,_ := models.GetCurrentUserName(r)

	rows, err := models.DB.Query(`
		SELECT u.user_id, u.email, u.role_id, u.first_name, u.last_name, u.phone
		FROM "users" u
		JOIN admin_volunteers av ON u.user_id = av.volunteer_id
		WHERE av.admin_id = $1 AND ( u.role_id = 3 OR u.role_id = 2 )
	`, currentAdminID)
	if err != nil {
		http.Error(w, "Query error", http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	var user []models.User
	for rows.Next() {
		var b models.User
		err := rows.Scan(&b.UserID, &b.Email, &b.RoleID, &b.FirstName, &b.LastName, &b.Phone)
		if err != nil {
			log.Println("Scan error:", err)
			continue
		}
		user = append(user, b)
	}

	utils.Render(w, "volunteer/volunteer.html", map[string]interface{}{
		"Title":           "Assigned Volunteers",
		"IsAuthenticated": true,
		"ShowAdminNav":    true,
		"UserName": 	username,
		"Users":           user,
		"ActiveSection":   "volunteer",
	})
}

func EditVolunteerHandler(w http.ResponseWriter, r *http.Request) {
	username,_ := models.GetCurrentUserName(r)

	if r.Method == http.MethodGet {
		volunteerID := r.URL.Query().Get("id")
		var user models.User
		err := models.DB.QueryRow(`
			SELECT user_id, email, role_id, first_name, last_name, phone
			FROM "users"
			WHERE user_id = $1 AND (role_id = 3 OR role_id = 2)
		`, volunteerID).Scan(&user.UserID, &user.Email, &user.RoleID, &user.FirstName, &user.LastName, &user.Phone)

		if err != nil {
			http.Error(w, "Volunteer not found", http.StatusNotFound)
			return
		}

		utils.Render(w, "volunteer/edit_volunteer.html", map[string]interface{}{
			"Title":           "Edit Volunteer",
			"IsAuthenticated": true,
			"ShowAdminNav":    true,
			"UserName": 	username,
			"Volunteer":       user,
			"ActiveSection":   "volunteer",
		})
		return
	}

	if r.Method == http.MethodPost {
		err := r.ParseForm()
		if err != nil {
			http.Error(w, "Invalid form", http.StatusBadRequest)
			return
		}

		volunteerID := r.FormValue("user_id")
		firstName := r.FormValue("first_name")
		lastName := r.FormValue("last_name")
		email := r.FormValue("email")
		phone := r.FormValue("phone")
		roleID := r.FormValue("role_id")

		rid, err := strconv.Atoi(roleID)
		if err != nil || (rid != 2 && rid != 3) {
			http.Error(w, "Invalid role selection", http.StatusBadRequest)
			return
		}

		// If role is being updated to Team Leader
		if rid == 2 {
			// Check if the volunteer is in any team
			var teamID int
			err := models.DB.QueryRow(`SELECT team_id FROM team WHERE volunteer_id = $1`, volunteerID).Scan(&teamID)
			if err != nil && err != sql.ErrNoRows {
				log.Printf("DB error checking team for user %s: %v", volunteerID, err)
				http.Error(w, "Internal server error", http.StatusInternalServerError)
				return
			}

			// If found, remove from the team
			if err == nil {
				_, err := models.DB.Exec(`UPDATE team SET volunteer_id = NULL WHERE team_id = $1`, teamID)
				if err != nil {
					log.Printf("Failed to remove volunteer %s from team %d: %v", volunteerID, teamID, err)
					http.Error(w, "Failed to update team assignment", http.StatusInternalServerError)
					return
				}
			}
		}

		_, err = models.DB.Exec(`
			UPDATE "users"
			SET first_name = $1, last_name = $2, email = $3, phone = $4, role_id = $5
			WHERE user_id = $6
		`, firstName, lastName, email, phone, rid, volunteerID)

		if err != nil {
			fmt.Print(err)
			http.Error(w, "Update failed", http.StatusInternalServerError)
			return
		}

		http.Redirect(w, r, "/volunteers", http.StatusSeeOther)
	}
}




//assign volunterr the title of team_leader
//Team View
//edit volnteer data
//
