package handlers

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"furry-sos-backend/config"
)

// ======================================================
// GET USER REPORTS
// History ของผู้แจ้งเหตุ
//
// GET /api/reports?user_id=X&type=emergency
// GET /api/reports?user_id=X&type=deceased
// ======================================================
func GetUserReports(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	userID := r.URL.Query().Get("user_id")
	reportType := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("type")))

	if userID == "" {
		http.Error(w, "Missing user_id", http.StatusBadRequest)
		return
	}

	fmt.Printf("🔍 user_id=%s, type=%s\n", userID, reportType)

	var query string
	var rows *sql.Rows
	var err error

	// ==================================================
	// DECEASED
	// ==================================================
	if reportType == "deceased" {

		query = `
			SELECT
				dr.report_id,
				dr.animal_type,
				dr.location_address,
				dr.image_url,
				COALESCE(ct.status, dr.status) AS status,
				dr.created_at
			FROM deceased_reports dr
			LEFT JOIN case_tracking ct
				ON ct.report_id = dr.report_id
				AND ct.report_type = 'deceased'
				AND ct.is_current = 1
			WHERE dr.user_id = ?
			ORDER BY dr.created_at DESC
		`

		rows, err = config.DB.Query(query, userID)

	} else {

		// ==================================================
		// EMERGENCY
		// ==================================================
		query = `
			SELECT
				er.report_id,
				er.case_code,
				er.animal_type,
				er.injury_type,
				er.severity_level,
				er.location_address,
				er.image_url,
				COALESCE(ct.status, er.status) AS status,
				er.created_at
			FROM emergency_reports er
			LEFT JOIN case_tracking ct
				ON ct.report_id = er.report_id
				AND ct.report_type = 'emergency'
				AND ct.is_current = 1
			WHERE er.user_id = ?
			ORDER BY er.created_at DESC
		`

		rows, err = config.DB.Query(query, userID)
	}

	if err != nil {
		fmt.Println("❌ GET USER REPORTS ERROR:", err)

		http.Error(
			w,
			"Failed to get reports: "+err.Error(),
			http.StatusInternalServerError,
		)
		return
	}

	defer rows.Close()

	reports := make([]map[string]interface{}, 0)

	// ==================================================
	// READ ROWS
	// ==================================================
	for rows.Next() {

		report := make(map[string]interface{})

		// ------------------------------------------------
		// DECEASED
		// ------------------------------------------------
		if reportType == "deceased" {

			var (
				id           int
				animalType   string
				locationAddr string
				imageURL     string
				status       string
				createdAt    string
			)

			err := rows.Scan(
				&id,
				&animalType,
				&locationAddr,
				&imageURL,
				&status,
				&createdAt,
			)

			if err != nil {
				fmt.Println("❌ SCAN deceased ERROR:", err)
				continue
			}

			report["report_id"] = id
			report["case_code"] = "DEC-" + strconv.Itoa(id)
			report["animal_type"] = animalType
			report["location_address"] = locationAddr
			report["image_url"] = imageURL
			report["status"] = status
			report["created_at"] = createdAt

		} else {

			// ------------------------------------------------
			// EMERGENCY
			// ------------------------------------------------
			var (
				id           int
				caseCode     string
				animalType   string
				injuryType   string
				severity     string
				locationAddr string
				imageURL     string
				status       string
				createdAt    string
			)

			err := rows.Scan(
				&id,
				&caseCode,
				&animalType,
				&injuryType,
				&severity,
				&locationAddr,
				&imageURL,
				&status,
				&createdAt,
			)

			if err != nil {
				fmt.Println("❌ SCAN emergency ERROR:", err)
				continue
			}

			report["report_id"] = id
			report["case_code"] = caseCode
			report["animal_type"] = animalType
			report["injury_type"] = injuryType
			report["severity"] = severity
			report["location_address"] = locationAddr
			report["image_url"] = imageURL
			report["status"] = status
			report["created_at"] = createdAt
		}

		// ------------------------------------------------
		// แปลงประเภทสัตว์สำหรับฝั่งแอป
		// ------------------------------------------------
		animalTypeValue, _ := report["animal_type"].(string)

		displayAnimalType := animalTypeValue

		switch strings.ToLower(strings.TrimSpace(animalTypeValue)) {
		case "dog":
			displayAnimalType = "สุนัข"
		case "cat":
			displayAnimalType = "แมว"
		case "bird":
			displayAnimalType = "นก"
		case "other":
			displayAnimalType = "สัตว์อื่น ๆ"
		}

		report["animal_type_text"] = displayAnimalType

		reports = append(reports, report)
	}

	if err := rows.Err(); err != nil {
		fmt.Println("❌ ROWS USER REPORT ERROR:", err)

		http.Error(
			w,
			"Failed to read reports: "+err.Error(),
			http.StatusInternalServerError,
		)
		return
	}

	// ==================================================
	// DEBUG
	// ==================================================
	fmt.Printf("📋 found %d reports\n", len(reports))

	for _, report := range reports {
		if code, ok := report["case_code"].(string); ok {
			fmt.Printf(
				"   - %s → status = %v\n",
				code,
				report["status"],
			)
		}
	}

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

	_ = json.NewEncoder(w).Encode(reports)
}

// ======================================================
// GET VOLUNTEER LATEST TASK
// ภารกิจล่าสุดของอาสาสมัคร
//
// GET /api/volunteer/latest-task
// Header: X-User-ID
//
// รองรับ:
// - emergency
// - deceased
// ======================================================
func GetVolunteerLatestTask(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

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

	w.Header().Set(
		"Cache-Control",
		"no-store, no-cache, must-revalidate, max-age=0",
	)
	w.Header().Set("Pragma", "no-cache")
	w.Header().Set("Expires", "0")

	// ==================================================
	// READ 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
	}

	fmt.Printf("\n========================================\n")
	fmt.Printf("📋 GET VOLUNTEER LATEST TASK\n")
	fmt.Printf("user_id = %d\n", userID)
	fmt.Printf("========================================\n")

	// ==================================================
	// FIND VOLUNTEER ID
	// ==================================================
	var volunteerID int

	err = config.DB.QueryRow(`
		SELECT volunteer_id
		FROM volunteers
		WHERE user_id = ?
		LIMIT 1
	`, userID).Scan(&volunteerID)

	if err != nil {

		if err == sql.ErrNoRows {
			w.WriteHeader(http.StatusNotFound)

			_ = json.NewEncoder(w).Encode(map[string]interface{}{
				"success": false,
				"message": "ไม่พบข้อมูลอาสาสมัคร",
			})

			return
		}

		w.WriteHeader(http.StatusInternalServerError)

		_ = json.NewEncoder(w).Encode(map[string]interface{}{
			"success": false,
			"message": "ค้นหาอาสาสมัครไม่สำเร็จ: " + err.Error(),
		})

		return
	}

	fmt.Printf("volunteer_id = %d\n", volunteerID)

	// ==================================================
	// GET LATEST TASKS
	//
	// ดึงจาก case_assignments
	// รองรับ emergency + deceased
	//
	// ไม่กรองเฉพาะ completed
	// เพื่อให้ภารกิจที่เพิ่งรับมาแสดงทันที
	// ==================================================
	query := `
		SELECT
			h.report_id,
			h.report_type,
			h.case_code,
			h.animal_type,
			h.injury_type,
			h.location_address,
			h.image_url,
			h.accepted_at,
			h.status,
			h.updated_at
		FROM
		(
			-- =================================================
			-- EMERGENCY
			-- =================================================
			SELECT
				er.report_id,
				'emergency' AS report_type,
				COALESCE(er.case_code, '') AS case_code,
				COALESCE(er.animal_type, '') AS animal_type,
				COALESCE(er.injury_type, '') AS injury_type,
				COALESCE(er.location_address, '') AS location_address,
				COALESCE(er.image_url, '') AS image_url,

				COALESCE(
					ca.accepted_at,
					ca.created_at
				) AS accepted_at,

				COALESCE(
					ct.status,
					ca.status,
					er.status
				) AS status,

				COALESCE(
					ca.updated_at,
					ca.created_at
				) AS updated_at

			FROM case_assignments ca

			INNER JOIN emergency_reports er
				ON er.report_id = ca.report_id

			LEFT JOIN case_tracking ct
				ON ct.report_id = er.report_id
				AND ct.report_type = 'emergency'
				AND ct.is_current = 1

			WHERE ca.volunteer_id = ?
			  AND ca.report_type = 'emergency'

			UNION ALL

			-- =================================================
			-- DECEASED
			-- =================================================
			SELECT
				dr.report_id,
				'deceased' AS report_type,

				CONCAT(
					'DEC-',
					LPAD(dr.report_id, 4, '0')
				) AS case_code,

				COALESCE(
					dr.animal_type,
					''
				) AS animal_type,

				'' AS injury_type,

				COALESCE(
					dr.location_address,
					''
				) AS location_address,

				COALESCE(
					dr.image_url,
					''
				) AS image_url,

				COALESCE(
					ca.accepted_at,
					ca.created_at
				) AS accepted_at,

				COALESCE(
					ct.status,
					ca.status,
					dr.status
				) AS status,

				COALESCE(
					ca.updated_at,
					ca.created_at
				) AS updated_at

			FROM case_assignments ca

			INNER JOIN deceased_reports dr
				ON dr.report_id = ca.report_id

			LEFT JOIN case_tracking ct
				ON ct.report_id = dr.report_id
				AND ct.report_type = 'deceased'
				AND ct.is_current = 1

			WHERE ca.volunteer_id = ?
			  AND ca.report_type = 'deceased'
		) AS h

		ORDER BY
			h.accepted_at DESC,
			h.updated_at DESC

		LIMIT 5
	`

	rows, err := config.DB.Query(
		query,
		volunteerID,
		volunteerID,
	)

	if err != nil {
		fmt.Println("❌ QUERY latest task ERROR:", err)

		w.WriteHeader(http.StatusInternalServerError)

		_ = json.NewEncoder(w).Encode(map[string]interface{}{
			"success": false,
			"message": "โหลดภารกิจล่าสุดไม่สำเร็จ: " + err.Error(),
		})

		return
	}

	defer rows.Close()

	tasks := make([]map[string]interface{}, 0)

	// ==================================================
	// READ TASKS
	// ==================================================
	for rows.Next() {

		var (
			reportID     int
			reportType   string
			caseCode     string
			animalType   string
			injuryType   string
			locationAddr string
			imageURL     string
			acceptedAt   interface{}
			status       string
			updatedAt    interface{}
		)

		err := rows.Scan(
			&reportID,
			&reportType,
			&caseCode,
			&animalType,
			&injuryType,
			&locationAddr,
			&imageURL,
			&acceptedAt,
			&status,
			&updatedAt,
		)

		if err != nil {
			fmt.Println("❌ SCAN latest task ERROR:", err)
			continue
		}

		// ==================================================
		// DISPLAY ANIMAL TYPE
		// ==================================================
		displayAnimalType := animalType

		switch strings.ToLower(
			strings.TrimSpace(animalType),
		) {
		case "dog":
			displayAnimalType = "สุนัข"

		case "cat":
			displayAnimalType = "แมว"

		case "bird":
			displayAnimalType = "นก"

		case "other":
			displayAnimalType = "สัตว์อื่น ๆ"
		}

		// ==================================================
		// APPEND
		// ==================================================
		tasks = append(tasks, map[string]interface{}{
			"report_id":        reportID,
			"report_type":      reportType,
			"case_code":        caseCode,
			"animal_type":      animalType,
			"animal_type_text": displayAnimalType,
			"injury_type":      injuryType,
			"location_address": locationAddr,
			"location":         locationAddr,
			"image_url":        imageURL,
			"accepted_at":      acceptedAt,
			"status":           status,
			"updated_at":       updatedAt,
		})
	}

	// ==================================================
	// ROW ERROR
	// ==================================================
	if err := rows.Err(); err != nil {

		w.WriteHeader(http.StatusInternalServerError)

		_ = json.NewEncoder(w).Encode(map[string]interface{}{
			"success": false,
			"message": "อ่านภารกิจล่าสุดไม่สำเร็จ: " + err.Error(),
		})

		return
	}

	// ==================================================
	// DEBUG
	// ==================================================
	fmt.Printf("📋 found %d latest tasks\n", len(tasks))

	for i, task := range tasks {
		fmt.Printf(
			"   %d. [%s] %s | report_id=%v | accepted_at=%v | status=%v\n",
			i+1,
			task["report_type"],
			task["case_code"],
			task["report_id"],
			task["accepted_at"],
			task["status"],
		)
	}

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