package handlers

import (
	"log"
	"net/http"

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

type AssignedAddress struct {
	AddressID        int
	Address          string
	StreetName       string
	StreetType       string
	StreetQuadrant   string
	HouseNumber      string
	HouseAlpha       *string
	Longitude        float64
	Latitude         float64
	VisitedValidated bool
	CreatedAt        string
	UpdatedAt        string
	Assigned         bool
	UserName         string
	UserEmail        string
	UserPhone        string
	AppointmentDate  *string
	AppointmentTime  *string
}

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

	rows, err := models.DB.Query(`
		SELECT 
			a.address_id, a.address, a.street_name, a.street_type, a.street_quadrant, 
			a.house_number, a.house_alpha, a.longitude, a.latitude, a.visited_validated, 
			a.created_at, a.updated_at,
			CASE WHEN ap.user_id IS NOT NULL THEN true ELSE false END as assigned,
			COALESCE(u.first_name || ' ' || u.last_name, '') as user_name,
			COALESCE(u.email, '') as user_email,
			COALESCE(u.phone, '') as user_phone,
			TO_CHAR(ap.appointment_date, 'YYYY-MM-DD') as appointment_date,
			TO_CHAR(ap.appointment_time, 'HH24:MI') as appointment_time
		FROM address_database a
		LEFT JOIN appointment ap ON a.address_id = ap.address_id
		LEFT JOIN users u ON ap.user_id = u.user_id
		ORDER BY a.address_id;
	`)
	if err != nil {
		log.Printf("query error: %v", err)
		http.Error(w, "query error", http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	var assignedAddresses []AssignedAddress
	for rows.Next() {
		var addr AssignedAddress
		err := rows.Scan(
			&addr.AddressID, &addr.Address, &addr.StreetName, &addr.StreetType, &addr.StreetQuadrant,
			&addr.HouseNumber, &addr.HouseAlpha, &addr.Longitude, &addr.Latitude, &addr.VisitedValidated,
			&addr.CreatedAt, &addr.UpdatedAt, &addr.Assigned, &addr.UserName, &addr.UserEmail,
			&addr.UserPhone, &addr.AppointmentDate, &addr.AppointmentTime,
		)
		if err != nil {
			log.Printf("scan error: %v", err)
			continue
		}
		assignedAddresses = append(assignedAddresses, addr)
	}

	utils.Render(w, "address_assigned.html", map[string]interface{}{
		"Title":           "Assigned Addresses",
		"IsAuthenticated": true,
		"AssignedList":    assignedAddresses,
		"ShowAdminNav":    true,
		"Role":            "admin",
		"UserName": 	username,
		"ActiveSection":   "assigned",
	})
}
