package handler

import (
	"strconv"

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

// WordBookHandler 生词本处理器
type WordBookHandler struct {
	wordBookService *services.WordBookService
}

func NewWordBookHandler(wordBookService *services.WordBookService) *WordBookHandler {
	return &WordBookHandler{wordBookService: wordBookService}
}

// ToggleFavorite 切换单词收藏状态
// POST /api/v1/word-book/toggle/:id
func (h *WordBookHandler) ToggleFavorite(c *gin.Context) {
	userID := c.GetInt64("user_id")
	wordIDStr := c.Param("id")
	
	wordID, err := strconv.ParseInt(wordIDStr, 10, 64)
	if err != nil {
		common.ErrorResponse(c, 400, "无效的单词ID")
		return
	}
	
	isFavorite, err := h.wordBookService.ToggleFavorite(userID, wordID)
	if err != nil {
		common.ErrorResponse(c, 500, "操作失败: "+err.Error())
		return
	}
	
	common.SuccessResponse(c, gin.H{
		"is_favorite": isFavorite,
		"message": func() string {
			if isFavorite {
				return "已添加到生词本"
			}
			return "已从生词本移除"
		}(),
	})
}

// GetFavoriteWords 获取生词本列表
// GET /api/v1/word-book
func (h *WordBookHandler) GetFavoriteWords(c *gin.Context) {
	userID := c.GetInt64("user_id")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
	sortBy := c.DefaultQuery("sort_by", "created_at") // created_at, proficiency, word
	order := c.DefaultQuery("order", "desc")           // asc, desc
	
	words, total, err := h.wordBookService.GetFavoriteWords(userID, page, pageSize, sortBy, order)
	if err != nil {
		common.ErrorResponse(c, 500, "获取生词本失败: "+err.Error())
		return
	}
	
	common.SuccessResponse(c, gin.H{
		"words":      words,
		"total":      total,
		"page":       page,
		"page_size":  pageSize,
		"total_pages": (total + int64(pageSize) - 1) / int64(pageSize),
	})
}

// GetFavoriteWordsByBook 获取指定词汇书的生词本
// GET /api/v1/word-book/books/:id
func (h *WordBookHandler) GetFavoriteWordsByBook(c *gin.Context) {
	userID := c.GetInt64("user_id")
	bookID := c.Param("id")
	
	words, err := h.wordBookService.GetFavoriteWordsByBook(userID, bookID)
	if err != nil {
		common.ErrorResponse(c, 500, "获取生词本失败: "+err.Error())
		return
	}
	
	common.SuccessResponse(c, gin.H{
		"words": words,
		"total": len(words),
	})
}

// GetFavoriteStats 获取生词本统计信息
// GET /api/v1/word-book/stats
func (h *WordBookHandler) GetFavoriteStats(c *gin.Context) {
	userID := c.GetInt64("user_id")
	
	stats, err := h.wordBookService.GetFavoriteStats(userID)
	if err != nil {
		common.ErrorResponse(c, 500, "获取统计信息失败: "+err.Error())
		return
	}
	
	common.SuccessResponse(c, stats)
}

// BatchAddToFavorite 批量添加到生词本
// POST /api/v1/word-book/batch
func (h *WordBookHandler) BatchAddToFavorite(c *gin.Context) {
	userID := c.GetInt64("user_id")
	
	var req struct {
		WordIDs []int64 `json:"word_ids" binding:"required,min=1"`
	}
	
	if err := c.ShouldBindJSON(&req); err != nil {
		common.ErrorResponse(c, 400, "参数错误: "+err.Error())
		return
	}
	
	count, err := h.wordBookService.BatchAddToFavorite(userID, req.WordIDs)
	if err != nil {
		common.ErrorResponse(c, 500, "批量添加失败: "+err.Error())
		return
	}
	
	common.SuccessResponse(c, gin.H{
		"added_count": count,
		"message":     "批量添加成功",
	})
}

// RemoveFromFavorite 从生词本移除单词
// DELETE /api/v1/word-book/:id
func (h *WordBookHandler) RemoveFromFavorite(c *gin.Context) {
	userID := c.GetInt64("user_id")
	wordIDStr := c.Param("id")
	
	wordID, err := strconv.ParseInt(wordIDStr, 10, 64)
	if err != nil {
		common.ErrorResponse(c, 400, "无效的单词ID")
		return
	}
	
	err = h.wordBookService.RemoveFromFavorite(userID, wordID)
	if err != nil {
		common.ErrorResponse(c, 500, "移除失败: "+err.Error())
		return
	}
	
	common.SuccessResponse(c, gin.H{
		"message": "已从生词本移除",
	})
}
