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 WritingHandler struct {
	writingService *services.WritingService
}

func NewWritingHandler(writingService *services.WritingService) *WritingHandler {
	return &WritingHandler{writingService: writingService}
}

// GetWritingPrompts 获取写作题目列表
func (h *WritingHandler) GetWritingPrompts(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"))

    // 转换为 limit/offset 以匹配服务方法签名
    limit := pageSize
    offset := (page - 1) * pageSize
    prompts, err := h.writingService.GetWritingPrompts(level, category, limit, offset)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

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

// GetWritingPrompt 获取单个写作题目
func (h *WritingHandler) GetWritingPrompt(c *gin.Context) {
	id := c.Param("id")

	prompt, err := h.writingService.GetWritingPrompt(id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Writing prompt not found"})
		return
	}

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

// CreateWritingPrompt 创建写作题目
func (h *WritingHandler) CreateWritingPrompt(c *gin.Context) {
	var prompt models.WritingPrompt
	if err := c.ShouldBindJSON(&prompt); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

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

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

// UpdateWritingPrompt 更新写作题目
func (h *WritingHandler) UpdateWritingPrompt(c *gin.Context) {
	id := c.Param("id")

	var prompt models.WritingPrompt
	if err := c.ShouldBindJSON(&prompt); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	prompt.ID = id // 确保ID匹配
	if err := h.writingService.UpdateWritingPrompt(id, &prompt); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

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

// DeleteWritingPrompt 删除写作题目
func (h *WritingHandler) DeleteWritingPrompt(c *gin.Context) {
	id := c.Param("id")

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

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

// SearchWritingPrompts 搜索写作题目
func (h *WritingHandler) SearchWritingPrompts(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"))

    // 转换为 limit/offset 以匹配服务方法签名
    limit := pageSize
    offset := (page - 1) * pageSize
    prompts, err := h.writingService.SearchWritingPrompts(keyword, level, category, limit, offset)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

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

// GetRecommendedPrompts 获取推荐写作题目
func (h *WritingHandler) GetRecommendedPrompts(c *gin.Context) {
    userID := c.GetString("user_id") // 假设用户ID已经通过中间件设置
    limit, _ := strconv.Atoi(c.DefaultQuery("limit", "5"))
    prompts, err := h.writingService.GetRecommendedPrompts(userID, limit)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

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

// CreateWritingSubmission 创建写作提交
func (h *WritingHandler) CreateWritingSubmission(c *gin.Context) {
	var submission models.WritingSubmission
	if err := c.ShouldBindJSON(&submission); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

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

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

// UpdateWritingSubmission 更新写作提交
func (h *WritingHandler) UpdateWritingSubmission(c *gin.Context) {
	id := c.Param("id")

	var submission models.WritingSubmission
	if err := c.ShouldBindJSON(&submission); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	submission.ID = id // 确保ID匹配
	if err := h.writingService.UpdateWritingSubmission(id, &submission); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

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

// GetWritingSubmission 获取写作提交详情
func (h *WritingHandler) GetWritingSubmission(c *gin.Context) {
	id := c.Param("id")

	submission, err := h.writingService.GetWritingSubmission(id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Writing submission not found"})
		return
	}

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

// GetUserWritingSubmissions 获取用户写作提交列表
func (h *WritingHandler) GetUserWritingSubmissions(c *gin.Context) {
    userID := c.GetString("user_id") // 假设用户ID已经通过中间件设置
    page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
    pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))
    // 转换为 limit/offset 以匹配服务方法签名
    limit := pageSize
    offset := (page - 1) * pageSize
    submissions, err := h.writingService.GetUserWritingSubmissions(userID, limit, offset)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

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

// SubmitWriting 提交写作作业
func (h *WritingHandler) SubmitWriting(c *gin.Context) {
    id := c.Param("id")
    var req struct {
        Content   string `json:"content"`
        TimeSpent int    `json:"time_spent"`
    }
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    if err := h.writingService.SubmitWriting(id, req.Content, req.TimeSpent); err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{"id": id, "message": "Writing submitted successfully"})
}

// GradeWriting AI批改写作
func (h *WritingHandler) GradeWriting(c *gin.Context) {
	id := c.Param("id")

	var req struct {
		Score           float64 `json:"score" binding:"required"`
		GrammarScore    float64 `json:"grammar_score"`
		VocabularyScore float64 `json:"vocabulary_score"`
		CoherenceScore  float64 `json:"coherence_score"`
		Feedback        string  `json:"feedback"`
		Suggestions     string  `json:"suggestions"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := h.writingService.GradeWriting(id, req.Score, req.GrammarScore, req.VocabularyScore, req.CoherenceScore, req.Feedback, req.Suggestions); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"id": id, "message": "Writing graded successfully"})
}

// GetUserWritingStats 获取用户写作统计
func (h *WritingHandler) GetUserWritingStats(c *gin.Context) {
	userID := c.GetString("user_id") // 假设用户ID已经通过中间件设置

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

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

// GetWritingProgress 获取写作进度
func (h *WritingHandler) GetWritingProgress(c *gin.Context) {
	userID := c.GetString("user_id") // 假设用户ID已经通过中间件设置
	promptID := c.Param("prompt_id")

	progress, err := h.writingService.GetWritingProgress(userID, promptID)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Writing progress not found"})
		return
	}

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