package handlers

import (
	"net/http"
	"time"

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

func VolunteerAppointmentHandler(w http.ResponseWriter, r *http.Request) {
	// Fetch appointments joined with address info
	currentUserID := models.GetCurrentUserID(w, r)
	username, _ := models.GetCurrentUserName(r)

	rows, err := models.DB.Query(`
		SELECT 
			a.sched_id,
			a.user_id,
			ad.address_id,
			ad.address,
			ad.latitude,
			ad.longitude,
			a.appointment_date,
			a.appointment_time
		FROM appointment a
		JOIN address_database ad ON a.address_id = ad.address_id
		WHERE a.user_id = $1
	`, currentUserID)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	// Struct to hold appointment + address info
	type AppointmentWithAddress struct {
		SchedID         int
		UserID          int
		AddressID       int
		Address         string
		Latitude        float64
		Longitude       float64
		AppointmentDate time.Time
		AppointmentTime time.Time
		HasPollResponse bool   // New field to track poll status
		PollButtonText  string // New field for button text
		PollButtonClass string // New field for button styling
	}

	var appointments []AppointmentWithAddress
	for rows.Next() {
		var a AppointmentWithAddress
		if err := rows.Scan(&a.SchedID, &a.UserID, &a.AddressID, &a.Address, &a.Latitude, &a.Longitude, &a.AppointmentDate, &a.AppointmentTime); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		// Check if poll response exists for this address
		var pollResponseExists bool
		err = models.DB.QueryRow(`
			SELECT EXISTS(
				SELECT 1 
				FROM poll p
				JOIN poll_response pr ON p.poll_id = pr.poll_id
				WHERE p.address_id = $1 AND p.user_id = $2
			)
		`, a.AddressID, currentUserID).Scan(&pollResponseExists)

		if err != nil {
			// If there's an error checking, default to no response
			pollResponseExists = false
		}

		// Set button properties based on poll response status
		a.HasPollResponse = pollResponseExists
		if pollResponseExists {
			a.PollButtonText = "Poll"
			a.PollButtonClass = "px-1 py-1 bg-green-600 text-white text-sm rounded cursor-not-allowed"
		} else {
			a.PollButtonText = "Ask"
			a.PollButtonClass = "px-1 py-1 bg-blue-600 text-white text-sm hover:bg-blue-700 rounded"
		}

		appointments = append(appointments, a)
	}

	role := r.Context().Value("user_role").(int)
	adminnav := false
	volunteernav := false

	if role == 1 {
		adminnav = true
		volunteernav = false
	} else {
		adminnav = false
		volunteernav = true
	}

	// Render template
	utils.Render(w, "/appointment.html", map[string]interface{}{
		"Title":            "My Profile",
		"IsAuthenticated":  true,
		"ShowAdminNav":     adminnav,
		"ShowVolunteerNav": volunteernav,
		"ActiveSection":    "address",
		"UserName":         username,
		"Appointments":     appointments,
	})
}