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 ReadingHandler struct {
	readingService *services.ReadingService
}

func NewReadingHandler(readingService *services.ReadingService) *ReadingHandler {
	return &ReadingHandler{readingService: readingService}
}

// GetReadingMaterials 获取阅读材料列表
func (h *ReadingHandler) GetReadingMaterials(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.readingService.GetReadingMaterials(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})
}

// GetReadingMaterial 获取阅读材料详情
func (h *ReadingHandler) GetReadingMaterial(c *gin.Context) {
	id := c.Param("id")

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

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

// CreateReadingMaterial 创建阅读材料
func (h *ReadingHandler) CreateReadingMaterial(c *gin.Context) {
	var material models.ReadingMaterial
	if err := c.ShouldBindJSON(&material); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

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

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

// UpdateReadingMaterial 更新阅读材料
func (h *ReadingHandler) UpdateReadingMaterial(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.readingService.UpdateReadingMaterial(id, updates); err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

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

// DeleteReadingMaterial 删除阅读材料
func (h *ReadingHandler) DeleteReadingMaterial(c *gin.Context) {
	id := c.Param("id")

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

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

// SearchReadingMaterials 搜索阅读材料
func (h *ReadingHandler) SearchReadingMaterials(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.readingService.SearchReadingMaterials(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 获取推荐阅读材料
func (h *ReadingHandler) GetRecommendedMaterials(c *gin.Context) {
	userID := c.GetString("user_id")
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "5"))

	materials, err := h.readingService.GetRecommendedMaterials(userID, limit)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

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

// CreateReadingRecord 创建阅读记录
func (h *ReadingHandler) CreateReadingRecord(c *gin.Context) {
	var record models.ReadingRecord
	if err := c.ShouldBindJSON(&record); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	record.UserID = c.GetString("user_id")
	if err := h.readingService.CreateReadingRecord(&record); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

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

// UpdateReadingRecord 更新阅读记录
func (h *ReadingHandler) UpdateReadingRecord(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.readingService.UpdateReadingRecord(id, updates); err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

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

// GetReadingRecord 获取阅读记录详情
func (h *ReadingHandler) GetReadingRecord(c *gin.Context) {
	id := c.Param("id")

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

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

// GetUserReadingRecords 获取用户阅读记录列表
func (h *ReadingHandler) GetUserReadingRecords(c *gin.Context) {
	userID := c.GetString("user_id")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))

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

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

// 已移除未实现的 SubmitReading 与 GradeReading，避免编译错误

// GetUserReadingStats 获取用户阅读统计
func (h *ReadingHandler) GetUserReadingStats(c *gin.Context) {
	userID := c.GetString("user_id")

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

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

// GetReadingProgress 获取阅读进度
func (h *ReadingHandler) GetReadingProgress(c *gin.Context) {
	userID := c.GetString("user_id")
	materialID := c.Param("material_id")

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

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