package handlers

import (
	"encoding/json"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/niangaodev/art-code/models"
	"github.com/niangaodev/art-code/repositories"
	"github.com/niangaodev/art-code/utils"
)

// GetWorkByID 根据ID获取作品
func GetWorkByID(c *gin.Context) {
	id := c.Param("id")

	work, err := repositories.GetWorkByID(id)
	if err != nil {
		utils.ServerError(c, err)
		return
	}
	if work == nil {
		utils.Error(c, 404, "Work not found")
		return
	}

	response, err := repositories.BuildWorkResponse(work)
	if err != nil {
		utils.ServerError(c, err)
		return
	}

	utils.Success(c, response)
}

// GetWorks 获取所有作品
func GetWorks(c *gin.Context) {
	works, err := repositories.GetWorks()
	if err != nil {
		utils.ServerError(c, err)
		return
	}

	// 构建响应
	responses := repositories.BuildWorksResponse(works)
	if responses == nil {
		utils.Success(c, []interface{}{})
	} else {
		utils.Success(c, responses)
	}
}

// AdminGetWorks 获取作品列表 (后台)
func AdminGetWorks(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))

	works, total, err := repositories.GetAdminWorks(page, pageSize)
	if err != nil {
		utils.ServerError(c, err)
		return
	}

	list := repositories.BuildWorksResponse(works)
	res := gin.H{
		"list":  list,
		"total": total,
		"page":  page,
		"size":  pageSize,
	}
	if list == nil {
		res["list"] = []interface{}{}
	}

	utils.Success(c, res)
}

// AdminCreateWork 创建作品
func AdminCreateWork(c *gin.Context) {
	var req struct {
		models.Work
		TechStack []map[string]interface{} `json:"techStack"`
		Gallery   []string                 `json:"gallery"`
		Links     map[string]interface{}   `json:"links"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}

	// 生成作品ID（如果没有提供）
	if req.Work.ID == "" {
		req.Work.ID = "work_" + strconv.FormatInt(time.Now().UnixNano(), 10)
	}

	// 将links转换为JSON字符串
	if req.Links != nil {
		linksJSON, err := json.Marshal(req.Links)
		if err != nil {
			utils.Error(c, 400, "Invalid links format")
			return
		}
		req.Work.Links = string(linksJSON)
	}

	// 创建作品
	if err := repositories.CreateWork(&req.Work); err != nil {
		utils.ServerError(c, err)
		return
	}

	// 保存技术栈
	if req.TechStack != nil && len(req.TechStack) > 0 {
		if err := repositories.CreateWorkTechStack(req.Work.ID, req.TechStack); err != nil {
			utils.ServerError(c, err)
			return
		}
	}

	// 保存图库
	if req.Gallery != nil && len(req.Gallery) > 0 {
		if err := repositories.CreateWorkGallery(req.Work.ID, req.Gallery); err != nil {
			utils.ServerError(c, err)
			return
		}
	}

	utils.SuccessWithMsg(c, "Work created successfully", gin.H{"id": req.Work.ID})
}

// AdminUpdateWork 更新作品
func AdminUpdateWork(c *gin.Context) {
	id := c.Param("id")

	var req struct {
		models.Work
		TechStack []map[string]interface{} `json:"techStack"`
		Gallery   []string                 `json:"gallery"`
		Links     map[string]interface{}   `json:"links"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}

	req.Work.ID = id

	// 将links转换为JSON字符串
	if req.Links != nil {
		linksJSON, err := json.Marshal(req.Links)
		if err != nil {
			utils.Error(c, 400, "Invalid links format")
			return
		}
		req.Work.Links = string(linksJSON)
	}

	// 更新作品
	if err := repositories.UpdateWork(&req.Work); err != nil {
		utils.ServerError(c, err)
		return
	}

	// 更新技术栈（先删除旧的，再创建新的）
	if req.TechStack != nil {
		if err := repositories.CreateWorkTechStack(id, req.TechStack); err != nil {
			utils.ServerError(c, err)
			return
		}
	}

	// 更新图库（先删除旧的，再创建新的）
	if req.Gallery != nil {
		if err := repositories.CreateWorkGallery(id, req.Gallery); err != nil {
			utils.ServerError(c, err)
			return
		}
	}

	utils.SuccessWithMsg(c, "Work updated successfully", nil)
}

// AdminDeleteWork 删除作品
func AdminDeleteWork(c *gin.Context) {
	id := c.Param("id")

	if err := repositories.DeleteWork(id); err != nil {
		utils.ServerError(c, err)
		return
	}

	utils.SuccessWithMsg(c, "Work deleted successfully", nil)
}
