package handlers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"furry-sos-backend/config"
)

// ======================================================
// 📝 SUBMIT HOSPITAL REVIEW
// POST /api/hospital/review
// Header: X-User-ID
// Body: { "hospital_id": 1, "rating": 5, "comment": "..." }
// ======================================================
func SubmitHospitalReview(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	if r.Method != http.MethodPost {
		w.WriteHeader(http.StatusMethodNotAllowed)
		json.NewEncoder(w).Encode(map[string]interface{}{"success": false, "message": "Method not allowed"})
		return
	}

	// อ่าน User ID
	userIDStr := r.Header.Get("X-User-ID")
	if userIDStr == "" {
		userIDStr = r.URL.Query().Get("user_id")
	}
	userID, err := strconv.Atoi(userIDStr)
	if err != nil || userID <= 0 {
		w.WriteHeader(http.StatusUnauthorized)
		json.NewEncoder(w).Encode(map[string]interface{}{"success": false, "message": "ไม่พบ User ID"})
		return
	}

	// อ่าน Body
	var body struct {
		HospitalID int    `json:"hospital_id"`
		Rating     int    `json:"rating"`
		Comment    string `json:"comment"`
	}
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		w.WriteHeader(http.StatusBadRequest)
		json.NewEncoder(w).Encode(map[string]interface{}{"success": false, "message": "ข้อมูลไม่ถูกต้อง"})
		return
	}

	if body.HospitalID <= 0 || body.Rating < 1 || body.Rating > 5 {
		w.WriteHeader(http.StatusBadRequest)
		json.NewEncoder(w).Encode(map[string]interface{}{"success": false, "message": "hospital_id หรือ rating ไม่ถูกต้อง"})
		return
	}

	// ตรวจโรงพยาบาลมีอยู่จริง
	var exists int
	config.DB.QueryRow(`SELECT COUNT(*) FROM hospitals WHERE hospital_id = ?`, body.HospitalID).Scan(&exists)
	if exists == 0 {
		w.WriteHeader(http.StatusNotFound)
		json.NewEncoder(w).Encode(map[string]interface{}{"success": false, "message": "ไม่พบโรงพยาบาล"})
		return
	}

	// INSERT หรือ UPDATE (ถ้า user เคยรีวิวแล้ว)
	_, err = config.DB.Exec(`
		INSERT INTO hospital_reviews (hospital_id, user_id, rating, comment, created_at)
		VALUES (?, ?, ?, ?, NOW())
		ON DUPLICATE KEY UPDATE
			rating = VALUES(rating),
			comment = VALUES(comment),
			updated_at = NOW()
	`, body.HospitalID, userID, body.Rating, body.Comment)

	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(map[string]interface{}{"success": false, "message": err.Error()})
		return
	}

	// 🌟 อัปเดต hospitals.rating อัตโนมัติ
	recalcHospitalRating(body.HospitalID)

	// ดึงคะแนนใหม่ส่งกลับ
	var newRating float64
	var reviewCount int
	config.DB.QueryRow(`
		SELECT COALESCE(AVG(rating), 0), COUNT(*)
		FROM hospital_reviews
		WHERE hospital_id = ?
	`, body.HospitalID).Scan(&newRating, &reviewCount)

	fmt.Printf("⭐ USER %d รีวิว รพ.%d = %d ดาว\n", userID, body.HospitalID, body.Rating)

	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]interface{}{
		"success":      true,
		"message":      "ขอบคุณสำหรับการรีวิว",
		"hospital_id":  body.HospitalID,
		"new_rating":   newRating,
		"review_count": reviewCount,
	})
}

// ======================================================
// 📖 GET HOSPITAL REVIEWS
// GET /api/hospital/reviews?hospital_id=1
// ======================================================
func GetHospitalReviews(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	if r.Method != http.MethodGet {
		w.WriteHeader(http.StatusMethodNotAllowed)
		json.NewEncoder(w).Encode(map[string]interface{}{"success": false, "message": "Method not allowed"})
		return
	}

	hospitalID, err := strconv.Atoi(r.URL.Query().Get("hospital_id"))
	if err != nil || hospitalID <= 0 {
		w.WriteHeader(http.StatusBadRequest)
		json.NewEncoder(w).Encode(map[string]interface{}{"success": false, "message": "ไม่พบ hospital_id"})
		return
	}

	rows, err := config.DB.Query(`
		SELECT 
			hr.review_id,
			hr.user_id,
			hr.rating,
			COALESCE(hr.comment, '') AS comment,
			hr.created_at,
			COALESCE(u.full_name, 'ผู้ใช้') AS user_name,
			COALESCE(u.profile_image, '') AS user_image
		FROM hospital_reviews hr
		LEFT JOIN users u ON u.user_id = hr.user_id
		WHERE hr.hospital_id = ?
		ORDER BY hr.created_at DESC
		LIMIT 50
	`, hospitalID)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(map[string]interface{}{"success": false, "message": err.Error()})
		return
	}
	defer rows.Close()

	reviews := []map[string]interface{}{}

	for rows.Next() {
		var (
			reviewID   int
			userID     int
			rating     int
			comment    string
			createdAt  time.Time
			userName   string
			userImage  string
		)
		if err := rows.Scan(&reviewID, &userID, &rating, &comment, &createdAt, &userName, &userImage); err != nil {
			continue
		}
		reviews = append(reviews, map[string]interface{}{
			"review_id":   reviewID,
			"user_id":     userID,
			"rating":      rating,
			"comment":     comment,
			"created_at":  createdAt.Format("2006-01-02 15:04:05"),
			"user_name":   userName,
			"user_image":  userImage,
		})
	}

	// ค่าเฉลี่ย
	var avgRating float64
	config.DB.QueryRow(`
		SELECT COALESCE(AVG(rating), 0)
		FROM hospital_reviews
		WHERE hospital_id = ?
	`, hospitalID).Scan(&avgRating)

	json.NewEncoder(w).Encode(map[string]interface{}{
		"success":      true,
		"hospital_id":  hospitalID,
		"average":      avgRating,
		"count":        len(reviews),
		"reviews":      reviews,
	})
}

// ======================================================
// ⭐ GET HOSPITAL RATING SUMMARY
// GET /api/hospital/rating?hospital_id=1
// ======================================================
func GetHospitalRatingSummary(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	hospitalID, err := strconv.Atoi(r.URL.Query().Get("hospital_id"))
	if err != nil || hospitalID <= 0 {
		w.WriteHeader(http.StatusBadRequest)
		json.NewEncoder(w).Encode(map[string]interface{}{"success": false, "message": "ไม่พบ hospital_id"})
		return
	}

	var avgRating float64
	var totalCount int
	config.DB.QueryRow(`
		SELECT COALESCE(AVG(rating), 0), COUNT(*)
		FROM hospital_reviews
		WHERE hospital_id = ?
	`, hospitalID).Scan(&avgRating, &totalCount)

	// นับจำนวนแต่ละดาว (1-5)
	type StarCount struct {
		Star  int `json:"star"`
		Count int `json:"count"`
	}
	breakdown := []StarCount{}
	for i := 5; i >= 1; i-- {
		var c int
		config.DB.QueryRow(`
			SELECT COUNT(*) FROM hospital_reviews
			WHERE hospital_id = ? AND rating = ?
		`, hospitalID, i).Scan(&c)
		breakdown = append(breakdown, StarCount{Star: i, Count: c})
	}

	json.NewEncoder(w).Encode(map[string]interface{}{
		"success":     true,
		"hospital_id": hospitalID,
		"average":     avgRating,
		"total":       totalCount,
		"breakdown":   breakdown,
	})
}

// ======================================================
// 🔧 HELPER: คำนวณ Rating ใหม่
// ======================================================
func recalcHospitalRating(hospitalID int) {
	_, err := config.DB.Exec(`
		UPDATE hospitals h
		SET rating = COALESCE(
			(SELECT AVG(r.rating) FROM hospital_reviews r
			 WHERE r.hospital_id = h.hospital_id),
			0
		)
		WHERE h.hospital_id = ?
	`, hospitalID)
	if err != nil {
		fmt.Println("⚠️ recalcHospitalRating ERROR:", err)
	}
}