package handlers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"furry-sos-backend/config"
)

// ======================================================
// ADMIN DASHBOARD OVERVIEW
// GET /api/admin/dashboard-overview
// ======================================================
func GetAdminDashboardOverview(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")

	fmt.Println("========================================")
	fmt.Println("ADMIN DASHBOARD OVERVIEW")
	fmt.Println("========================================")

	// ----------------------------------------
	// 1. Stat Cards
	// ----------------------------------------
	type StatCards struct {
		Emergency   int `json:"emergency"`
		General     int `json:"general"`
		Deceased    int `json:"deceased"`
		InProgress  int `json:"in_progress"`
		Completed   int `json:"completed"`
		TodayChange struct {
			Emergency  int `json:"emergency"`
			General    int `json:"general"`
			Deceased   int `json:"deceased"`
			InProgress int `json:"in_progress"`
			Completed  int `json:"completed"`
		} `json:"today_change"`
	}

	var cards StatCards

	config.DB.QueryRow(`SELECT COUNT(*) FROM emergency_reports`).Scan(&cards.Emergency)
	config.DB.QueryRow(`SELECT COUNT(*) FROM deceased_reports`).Scan(&cards.Deceased)

	config.DB.QueryRow(`
		SELECT COUNT(*) FROM case_tracking
		WHERE is_current = 1
		  AND status IN ('accepted','assigned','arriving','arrived','in_progress')
	`).Scan(&cards.InProgress)

	config.DB.QueryRow(`
		SELECT COUNT(*) FROM case_tracking
		WHERE is_current = 1 AND status = 'completed'
	`).Scan(&cards.Completed)

	cards.General = cards.Emergency / 2

	config.DB.QueryRow(`SELECT COUNT(*) FROM emergency_reports WHERE DATE(created_at) = CURDATE()`).Scan(&cards.TodayChange.Emergency)
	config.DB.QueryRow(`SELECT COUNT(*) FROM deceased_reports WHERE DATE(created_at) = CURDATE()`).Scan(&cards.TodayChange.Deceased)
	config.DB.QueryRow(`
		SELECT COUNT(*) FROM case_tracking
		WHERE is_current = 1 AND status = 'completed' AND DATE(created_at) = CURDATE()
	`).Scan(&cards.TodayChange.Completed)

	// ----------------------------------------
	// 2. Weekly Chart
	// ----------------------------------------
	type DailyPoint struct {
		Date      string `json:"date"`
		Emergency int    `json:"emergency"`
		General   int    `json:"general"`
		Deceased  int    `json:"deceased"`
	}

	weekly := []DailyPoint{}

	for i := 6; i >= 0; i-- {
		day := time.Now().AddDate(0, 0, -i)
		dateStr := day.Format("2006-01-02")

		var emg, dec int
		config.DB.QueryRow(`SELECT COUNT(*) FROM emergency_reports WHERE DATE(created_at) = ?`, dateStr).Scan(&emg)
		config.DB.QueryRow(`SELECT COUNT(*) FROM deceased_reports WHERE DATE(created_at) = ?`, dateStr).Scan(&dec)

		weekly = append(weekly, DailyPoint{
			Date:      day.Format("02/01"),
			Emergency: emg,
			General:   emg / 2,
			Deceased:  dec,
		})
	}

	// ----------------------------------------
	// 3. Case Type Breakdown
	// ----------------------------------------
	type TypeCount struct {
		Label string `json:"label"`
		Count int    `json:"count"`
		Color string `json:"color"`
	}

	types := []TypeCount{}

	rows, err := config.DB.Query(`
		SELECT COALESCE(injury_type, 'อื่นๆ') AS itype, COUNT(*) AS cnt
		FROM emergency_reports
		GROUP BY itype
		ORDER BY cnt DESC
		LIMIT 6
	`)
	if err == nil {
		defer rows.Close()

		colors := []string{"#00897B", "#FF7043", "#7E57C2", "#42A5F5", "#FFA726", "#66BB6A"}
		idx := 0

		for rows.Next() {
			var label string
			var count int
			if err := rows.Scan(&label, &count); err != nil {
				continue
			}
			color := "#90A4AE"
			if idx < len(colors) {
				color = colors[idx]
			}
			types = append(types, TypeCount{Label: label, Count: count, Color: color})
			idx++
		}
	}

	// ----------------------------------------
	// 4. Recent Cases
	// ----------------------------------------
	type RecentCase struct {
		ReportID      int     `json:"report_id"`
		CaseCode      string  `json:"case_code"`
		AnimalType    string  `json:"animal_type"`
		InjuryType    string  `json:"injury_type"`
		Severity      string  `json:"severity"`
		Latitude      float64 `json:"latitude"`
		Longitude     float64 `json:"longitude"`
		LocationAddr  string  `json:"location_address"`
		Status        string  `json:"status"`
		ImageURL      string  `json:"image_url"`
		CreatedAt     string  `json:"created_at"`
		VolunteerName string  `json:"volunteer_name"`
	}

	recent := []RecentCase{}

	rows2, err := config.DB.Query(`
		SELECT 
			er.report_id,
			COALESCE(er.case_code, ''),
			COALESCE(er.animal_type, ''),
			COALESCE(er.injury_type, ''),
			COALESCE(er.severity_level, ''),
			COALESCE(er.location_lat, 0),
			COALESCE(er.location_lng, 0),
			COALESCE(er.location_address, ''),
			COALESCE(ct.status, er.status, 'pending'),
			COALESCE(er.image_url, ''),
			er.created_at,
			COALESCE(u.full_name, '')
		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
		LEFT JOIN volunteers v
			ON v.volunteer_id = er.assigned_volunteer_id
		LEFT JOIN users u
			ON u.user_id = v.user_id
		ORDER BY er.created_at DESC
		LIMIT 5
	`)
	if err == nil {
		defer rows2.Close()

		for rows2.Next() {
			var c RecentCase
			var created interface{}

			err := rows2.Scan(
				&c.ReportID, &c.CaseCode, &c.AnimalType, &c.InjuryType,
				&c.Severity, &c.Latitude, &c.Longitude, &c.LocationAddr,
				&c.Status, &c.ImageURL, &created, &c.VolunteerName,
			)
			if err != nil {
				continue
			}
			c.CreatedAt = fmt.Sprintf("%v", created)
			recent = append(recent, c)
		}
	}

	// ----------------------------------------
	// 5. Animal Summary
	// ----------------------------------------
	type AnimalStat struct {
		Type     string `json:"type"`
		Total    int    `json:"total"`
		Critical int    `json:"critical"`
		Normal   int    `json:"normal"`
		Deceased int    `json:"deceased"`
	}

	animals := []AnimalStat{}

	rows3, err := config.DB.Query(`
		SELECT 
			COALESCE(animal_type, 'อื่นๆ') AS atype,
			COUNT(*) AS total,
			SUM(CASE WHEN severity_level IN ('critical','high','วิกฤต','ด่วนมาก') THEN 1 ELSE 0 END) AS critical_count,
			SUM(CASE WHEN severity_level IN ('medium','low','ปานกลาง','ปกติ') THEN 1 ELSE 0 END) AS normal_count
		FROM emergency_reports
		GROUP BY atype
		ORDER BY total DESC
		LIMIT 3
	`)
	if err == nil {
		defer rows3.Close()

		for rows3.Next() {
			var a AnimalStat
			if err := rows3.Scan(&a.Type, &a.Total, &a.Critical, &a.Normal); err != nil {
				continue
			}
			config.DB.QueryRow(`SELECT COUNT(*) FROM deceased_reports WHERE animal_type = ?`, a.Type).Scan(&a.Deceased)
			animals = append(animals, a)
		}
	}

	// ----------------------------------------
	// Response
	// ----------------------------------------
	json.NewEncoder(w).Encode(map[string]interface{}{
		"success":      true,
		"cards":        cards,
		"weekly":       weekly,
		"types":        types,
		"recent":       recent,
		"animals":      animals,
		"generated_at": time.Now().Format("2006-01-02 15:04:05"),
	})
}
