package handlers

import (
	"encoding/json"
	"net/http"

	"furry-sos-backend/config"
)

// ============================================================
// ADMIN PERFORMANCE REVIEW
//
// GET /api/admin/performance
//
// อ่านข้อมูลจากฐานข้อมูลโดยตรง:
// volunteers
// users
// case_assignments
// volunteer_reviews
// volunteer_quiz_results
// volunteer_training
// ============================================================

func GetAdminPerformance(
	w http.ResponseWriter,
	r *http.Request,
) {

	if r.Method != http.MethodGet {
		http.Error(
			w,
			"Method not allowed",
			http.StatusMethodNotAllowed,
		)
		return
	}

	type VolunteerPerformance struct {
		VolunteerID       int     `json:"volunteer_id"`
		UserID            int     `json:"user_id"`
		Username          string  `json:"username"`
		FullName          string  `json:"full_name"`
		Email             string  `json:"email"`
		Phone             string  `json:"phone"`
		WorkingArea       string  `json:"working_area"`
		TierLevel         string  `json:"tier_level"`
		IsApproved        bool    `json:"is_approved"`
		IsOnline          bool    `json:"is_online"`
		CompletedMissions int     `json:"completed_missions"`
		ReviewCount       int     `json:"review_count"`
		AvgRating         float64 `json:"avg_rating"`
		PassedCourses     int     `json:"passed_courses"`
		TotalCourses      int     `json:"total_courses"`
	}

	rows, err := config.DB.Query(`
		SELECT
			v.volunteer_id,
			v.user_id,
			COALESCE(u.username, ''),
			COALESCE(u.full_name, ''),
			COALESCE(u.email, ''),
			COALESCE(u.phone, ''),
			COALESCE(v.working_area, ''),
			COALESCE(v.tier_level, 'basic'),
			COALESCE(v.is_approved, 0),
			COALESCE(v.is_online, 0),

			(
				SELECT COUNT(*)
				FROM case_assignments ca
				WHERE ca.volunteer_id = v.volunteer_id
				  AND ca.status = 'completed'
			) AS completed_missions,

			(
				SELECT COUNT(*)
				FROM volunteer_reviews vr
				WHERE vr.volunteer_id = v.volunteer_id
			) AS review_count,

			COALESCE(
				(
					SELECT AVG(vr.rating)
					FROM volunteer_reviews vr
					WHERE vr.volunteer_id = v.volunteer_id
				),
				0
			) AS avg_rating,

			(
				SELECT COUNT(DISTINCT vqr.training_id)
				FROM volunteer_quiz_results vqr
				WHERE vqr.volunteer_id = v.volunteer_id
				  AND vqr.approval_status = 'approved'
			) AS passed_courses,

			(
				SELECT COUNT(*)
				FROM volunteer_training vt
				WHERE vt.is_active = 1
				  AND vt.training_id IN (1, 2, 3)
			) AS total_courses

		FROM volunteers v

		INNER JOIN users u
			ON u.user_id = v.user_id

		ORDER BY
			v.created_at DESC
	`)

	if err != nil {
		http.Error(
			w,
			"โหลด Performance Review ไม่สำเร็จ: "+err.Error(),
			http.StatusInternalServerError,
		)
		return
	}

	defer rows.Close()

	volunteers := []VolunteerPerformance{}

	for rows.Next() {

		var item VolunteerPerformance

		if err := rows.Scan(
			&item.VolunteerID,
			&item.UserID,
			&item.Username,
			&item.FullName,
			&item.Email,
			&item.Phone,
			&item.WorkingArea,
			&item.TierLevel,
			&item.IsApproved,
			&item.IsOnline,
			&item.CompletedMissions,
			&item.ReviewCount,
			&item.AvgRating,
			&item.PassedCourses,
			&item.TotalCourses,
		); err != nil {
			http.Error(
				w,
				"อ่านข้อมูล Performance Review ไม่สำเร็จ: "+err.Error(),
				http.StatusInternalServerError,
			)
			return
		}

		volunteers = append(
			volunteers,
			item,
		)
	}

	if err := rows.Err(); err != nil {
		http.Error(
			w,
			"เกิดข้อผิดพลาดในการอ่านข้อมูล Performance Review: "+err.Error(),
			http.StatusInternalServerError,
		)
		return
	}

	var (
		totalVolunteers        = len(volunteers)
		onlineVolunteers       int
		totalCompletedMissions int
		averageRating          float64
	)

	for _, item := range volunteers {

		if item.IsOnline {
			onlineVolunteers++
		}

		totalCompletedMissions +=
			item.CompletedMissions
	}

	_ = config.DB.QueryRow(`
		SELECT COALESCE(
			AVG(rating),
			0
		)
		FROM volunteer_reviews
	`).Scan(
		&averageRating,
	)

	w.Header().Set(
		"Content-Type",
		"application/json; charset=utf-8",
	)

	_ = json.NewEncoder(w).Encode(
		map[string]interface{}{
			"success": true,

			"summary": map[string]interface{}{
				"total_volunteers": totalVolunteers,

				"online_volunteers": onlineVolunteers,

				"total_completed_missions": totalCompletedMissions,

				"average_rating": averageRating,
			},

			"volunteers": volunteers,
		},
	)
}
