package handler

import (
    "net/http"
    "strconv"

    "github.com/gin-gonic/gin"
    "github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/services"
    "github.com/Nanqipro/YunQue-Tech-Projects/ai_english_learning/serve/internal/models"
)

type ListeningHandler struct {
    listeningService *services.ListeningService
}

func NewListeningHandler(listeningService *services.ListeningService) *ListeningHandler {
    return &ListeningHandler{listeningService: listeningService}
}

func getUserIDString(c *gin.Context) string {
    uid, exists := c.Get("user_id")
    if !exists || uid == nil {
        return ""
    }
    switch v := uid.(type) {
    case string:
        return v
    case int:
        return strconv.Itoa(v)
    case int64:
        return strconv.FormatInt(v, 10)
    default:
        return ""
    }
}

// GetListeningMaterials 获取听力材料列表
func (h *ListeningHandler) GetListeningMaterials(c *gin.Context) {
	level := c.Query("level")
	category := c.Query("category")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))

    materials, total, err := h.listeningService.GetListeningMaterials(level, category, page, pageSize)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{"materials": materials, "total": total})
}

// GetListeningMaterial 获取听力材料详情
func (h *ListeningHandler) GetListeningMaterial(c *gin.Context) {
	id := c.Param("id")

	material, err := h.listeningService.GetListeningMaterial(id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Listening material not found"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"material": material})
}

// CreateListeningMaterial 创建听力材料
func (h *ListeningHandler) CreateListeningMaterial(c *gin.Context) {
    var material models.ListeningMaterial
    if err := c.ShouldBindJSON(&material); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    if err := h.listeningService.CreateListeningMaterial(&material); err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusCreated, gin.H{"material": material})
}

// UpdateListeningMaterial 更新听力材料
func (h *ListeningHandler) UpdateListeningMaterial(c *gin.Context) {
	id := c.Param("id")

	var updates map[string]interface{}
	if err := c.ShouldBindJSON(&updates); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

    if err := h.listeningService.UpdateListeningMaterial(id, updates); err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    // 返回最新数据
    material, err := h.listeningService.GetListeningMaterial(id)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    c.JSON(http.StatusOK, gin.H{"material": material})
}

// DeleteListeningMaterial 删除听力材料
func (h *ListeningHandler) DeleteListeningMaterial(c *gin.Context) {
	id := c.Param("id")

	if err := h.listeningService.DeleteListeningMaterial(id); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Listening material deleted successfully"})
}

// SearchListeningMaterials 搜索听力材料
func (h *ListeningHandler) SearchListeningMaterials(c *gin.Context) {
	keyword := c.Query("keyword")
	level := c.Query("level")
	category := c.Query("category")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))

    materials, total, err := h.listeningService.SearchListeningMaterials(keyword, level, category, page, pageSize)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{"materials": materials, "total": total})
}

// 已移除未实现的 GetRecommendedMaterials，避免编译错误

// CreateListeningRecord 创建听力记录
func (h *ListeningHandler) CreateListeningRecord(c *gin.Context) {
    var record models.ListeningRecord
    if err := c.ShouldBindJSON(&record); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    record.UserID = getUserIDString(c)
    if err := h.listeningService.CreateListeningRecord(&record); err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

	c.JSON(http.StatusCreated, gin.H{"record": record})
}

// UpdateListeningRecord 更新听力记录
func (h *ListeningHandler) UpdateListeningRecord(c *gin.Context) {
	id := c.Param("id")

	var updates map[string]interface{}
	if err := c.ShouldBindJSON(&updates); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

    if err := h.listeningService.UpdateListeningRecord(id, updates); err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    record, err := h.listeningService.GetListeningRecord(id)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    c.JSON(http.StatusOK, gin.H{"record": record})
}

// GetListeningRecord 获取听力记录详情
func (h *ListeningHandler) GetListeningRecord(c *gin.Context) {
	id := c.Param("id")

	record, err := h.listeningService.GetListeningRecord(id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Listening record not found"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"record": record})
}

// GetUserListeningRecords 获取用户听力记录列表
func (h *ListeningHandler) GetUserListeningRecords(c *gin.Context) {
    userID := getUserIDString(c)
    page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
    pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))

	records, total, err := h.listeningService.GetUserListeningRecords(userID, page, pageSize)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"data": records, "total": total})
}

// 移除未实现的 SubmitListening 与 GradeListening，避免编译错误

// GetUserListeningStats 获取用户听力统计
func (h *ListeningHandler) GetUserListeningStats(c *gin.Context) {
    userID := getUserIDString(c)

    stats, err := h.listeningService.GetUserListeningStats(userID)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

	c.JSON(http.StatusOK, gin.H{"stats": stats})
}

// GetListeningProgress 获取听力进度
func (h *ListeningHandler) GetListeningProgress(c *gin.Context) {
    userID := getUserIDString(c)
    materialID := c.Param("material_id")

    progress, err := h.listeningService.GetListeningProgress(userID, materialID)
    if err != nil {
        c.JSON(http.StatusNotFound, gin.H{"error": "Listening progress not found"})
        return
    }

	c.JSON(http.StatusOK, gin.H{"progress": progress})
}