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 PollHandler(w http.ResponseWriter, r *http.Request) {
	username, _ := models.GetCurrentUserName(r)
	
	if r.Method == http.MethodGet {
		addressID := r.URL.Query().Get("address_id")
		if addressID == "" {
			http.Error(w, "Address ID required", http.StatusBadRequest)
			return
		}

		// Get address details
		var address string
		var userID int
		fmt.Print(addressID, userID)
		err := models.DB.QueryRow(`
			SELECT a.address, ap.user_id 
			FROM appointment AS ap
			JOIN address_database a ON a.address_id = ap.address_id
			WHERE ap.address_id = $1
		`, addressID).Scan(&address, &userID)

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

		// Check if poll already exists for this address
		var pollID int
		err = models.DB.QueryRow(`
			SELECT poll_id 
			FROM poll 
			WHERE address_id = $1 AND user_id = $2
		`, addressID, userID).Scan(&pollID)

		// If no poll exists, create one
		if err == sql.ErrNoRows {
			err = models.DB.QueryRow(`
				INSERT INTO poll (user_id, address_id, poll_title, poll_description, is_active)
				VALUES ($1, $2, 'Door-to-Door Poll', 'Campaign polling questions', true)
				RETURNING poll_id
			`, userID, addressID).Scan(&pollID)
			
			if err != nil {
				log.Printf("Failed to create poll: %v", err)
				http.Error(w, "Failed to create poll", http.StatusInternalServerError)
				return
			}
		} else if err != nil {
			log.Printf("Database error: %v", err)
			http.Error(w, "Database error", http.StatusInternalServerError)
			return
		}

		utils.Render(w, "volunteer/poll_form.html", map[string]interface{}{
			"Title":           "Poll Questions",
			"IsAuthenticated": true,
			"ShowAdminNav":    true,
			"UserName":        username,
			"ActiveSection":   "appointments",
			"PollID":          pollID,
			"AddressID":       addressID,
			"Address":         address,
			"PageIcon":        "fas fa-poll",
		})
		return
	}

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

		pollID := r.FormValue("poll_id")
		postalCode := r.FormValue("postal_code")
		question5Thoughts := r.FormValue("question5_thoughts")

		// Parse boolean values
		var question1VotedBefore *bool
		if val := r.FormValue("question1_voted_before"); val != "" {
			if val == "true" {
				b := true
				question1VotedBefore = &b
			} else if val == "false" {
				b := false
				question1VotedBefore = &b
			}
		}

		var question2VoteAgain *bool
		if val := r.FormValue("question2_vote_again"); val != "" {
			if val == "true" {
				b := true
				question2VoteAgain = &b
			} else if val == "false" {
				b := false
				question2VoteAgain = &b
			}
		}

		// Parse integer values
		question3LawnSigns, _ := strconv.Atoi(r.FormValue("question3_lawn_signs"))
		question4BannerSigns, _ := strconv.Atoi(r.FormValue("question4_banner_signs"))

		// Insert poll response
		_, err = models.DB.Exec(`
			INSERT INTO poll_response (
				poll_id, respondent_postal_code, question1_voted_before, 
				question2_vote_again, question3_lawn_signs, question4_banner_signs,
				question5_thoughts
			) VALUES ($1, $2, $3, $4, $5, $6, $7)
		`, pollID, postalCode, question1VotedBefore, question2VoteAgain, 
		   question3LawnSigns, question4BannerSigns, question5Thoughts)

		if err != nil {
			fmt.Print(err)
			http.Error(w, "Failed to save poll response", http.StatusInternalServerError)
			return
		}

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