package com.example.demo.controller;

import com.example.demo.model.UserWork;
import com.example.demo.service.UserWorkService;
import com.example.demo.util.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户作品API控制器
 */
@RestController
@RequestMapping("/api/works")
public class UserWorkApiController {

    private static final Logger logger = LoggerFactory.getLogger(UserWorkApiController.class);

    @Autowired
    private UserWorkService userWorkService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取我的作品列表
     */
    @GetMapping("/my-works")
    public ResponseEntity<Map<String, Object>> getMyWorks(
            @RequestHeader("Authorization") String token,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 输入验证
            if (page < 0) page = 0;
            if (size <= 0 || size > 100) size = 10;

            Page<UserWork> works = userWorkService.getUserWorks(username, page, size);
            Map<String, Object> workStats = userWorkService.getUserWorkStats(username);

            response.put("success", true);
            response.put("data", works.getContent());
            response.put("totalElements", works.getTotalElements());
            response.put("totalPages", works.getTotalPages());
            response.put("currentPage", page);
            response.put("size", size);
            response.put("stats", workStats);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取我的作品列表失败", e);
            response.put("success", false);
            response.put("message", "获取作品列表失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取作品详情
     */
    @GetMapping("/{workId}")
    public ResponseEntity<Map<String, Object>> getWorkDetail(
            @PathVariable Long workId,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            UserWork work = userWorkService.getUserWorkDetail(workId, username);
            
            // 增加浏览次数
            userWorkService.incrementViewCount(workId);

            response.put("success", true);
            response.put("data", work);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取作品详情失败", e);
            response.put("success", false);
            response.put("message", "获取作品详情失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 更新作品信息
     */
    @PutMapping("/{workId}")
    public ResponseEntity<Map<String, Object>> updateWork(
            @PathVariable Long workId,
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> updateData) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            String title = (String) updateData.get("title");
            String description = (String) updateData.get("description");
            String tags = (String) updateData.get("tags");
            Boolean isPublic = null;
            Object isPublicObj = updateData.get("isPublic");
            if (isPublicObj instanceof Boolean) {
                isPublic = (Boolean) isPublicObj;
            } else if (isPublicObj instanceof String) {
                isPublic = Boolean.parseBoolean((String) isPublicObj);
            }

            UserWork work = userWorkService.updateWork(workId, username, title, description, tags, isPublic);

            response.put("success", true);
            response.put("data", work);
            response.put("message", "作品更新成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("更新作品失败", e);
            response.put("success", false);
            response.put("message", "更新作品失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 删除作品
     */
    @DeleteMapping("/{workId}")
    public ResponseEntity<Map<String, Object>> deleteWork(
            @PathVariable Long workId,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            boolean deleted = userWorkService.deleteWork(workId, username);
            if (deleted) {
                response.put("success", true);
                response.put("message", "作品删除成功");
            } else {
                response.put("success", false);
                response.put("message", "作品不存在");
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("删除作品失败", e);
            response.put("success", false);
            response.put("message", "删除作品失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 点赞作品
     */
    @PostMapping("/{workId}/like")
    public ResponseEntity<Map<String, Object>> likeWork(
            @PathVariable Long workId,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 检查作品是否存在
            try {
                userWorkService.getUserWorkDetail(workId, username);
                userWorkService.incrementLikeCount(workId);
                response.put("success", true);
                response.put("message", "点赞成功");
            } catch (RuntimeException e) {
                response.put("success", false);
                response.put("message", "作品不存在或无权限");
                return ResponseEntity.status(404).body(response);
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("点赞作品失败", e);
            response.put("success", false);
            response.put("message", "点赞失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 下载作品
     */
    @PostMapping("/{workId}/download")
    public ResponseEntity<Map<String, Object>> downloadWork(
            @PathVariable Long workId,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 检查作品是否存在
            try {
                userWorkService.getUserWorkDetail(workId, username);
                userWorkService.incrementDownloadCount(workId);
                response.put("success", true);
                response.put("message", "下载记录成功");
            } catch (RuntimeException e) {
                response.put("success", false);
                response.put("message", "作品不存在或无权限");
                return ResponseEntity.status(404).body(response);
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("记录下载失败", e);
            response.put("success", false);
            response.put("message", "记录下载失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取公开作品列表
     */
    @GetMapping("/public")
    public ResponseEntity<Map<String, Object>> getPublicWorks(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String sort) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 输入验证
            if (page < 0) page = 0;
            if (size <= 0 || size > 100) size = 10;
            
            Page<UserWork> works;
            
            if ("popular".equals(sort)) {
                works = userWorkService.getPopularWorks(page, size);
            } else if ("latest".equals(sort)) {
                works = userWorkService.getLatestWorks(page, size);
            } else if (type != null) {
                try {
                    UserWork.WorkType workType = UserWork.WorkType.valueOf(type.toUpperCase());
                    works = userWorkService.getPublicWorksByType(workType, page, size);
                } catch (IllegalArgumentException e) {
                    logger.warn("无效的作品类型: {}", type);
                    works = userWorkService.getPublicWorks(page, size);
                }
            } else {
                works = userWorkService.getPublicWorks(page, size);
            }

            response.put("success", true);
            response.put("data", works.getContent());
            response.put("totalElements", works.getTotalElements());
            response.put("totalPages", works.getTotalPages());
            response.put("currentPage", page);
            response.put("size", size);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取公开作品列表失败", e);
            response.put("success", false);
            response.put("message", "获取作品列表失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 搜索公开作品
     */
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchPublicWorks(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 输入验证
            if (keyword == null || keyword.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "搜索关键词不能为空");
                return ResponseEntity.status(400).body(response);
            }
            if (page < 0) page = 0;
            if (size <= 0 || size > 100) size = 10;

            Page<UserWork> works = userWorkService.searchPublicWorks(keyword.trim(), page, size);

            response.put("success", true);
            response.put("data", works.getContent());
            response.put("totalElements", works.getTotalElements());
            response.put("totalPages", works.getTotalPages());
            response.put("currentPage", page);
            response.put("size", size);
            response.put("keyword", keyword);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("搜索作品失败", e);
            response.put("success", false);
            response.put("message", "搜索作品失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 根据标签搜索作品
     */
    @GetMapping("/tag/{tag}")
    public ResponseEntity<Map<String, Object>> searchWorksByTag(
            @PathVariable String tag,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 输入验证
            if (tag == null || tag.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "标签不能为空");
                return ResponseEntity.status(400).body(response);
            }
            if (page < 0) page = 0;
            if (size <= 0 || size > 100) size = 10;

            Page<UserWork> works = userWorkService.searchPublicWorksByTag(tag.trim(), page, size);

            response.put("success", true);
            response.put("data", works.getContent());
            response.put("totalElements", works.getTotalElements());
            response.put("totalPages", works.getTotalPages());
            response.put("currentPage", page);
            response.put("size", size);
            response.put("tag", tag);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("根据标签搜索作品失败", e);
            response.put("success", false);
            response.put("message", "搜索作品失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 从Token中提取用户名
     */
    private String extractUsernameFromToken(String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return null;
            }
            
            // 提取实际的token
            String actualToken = jwtUtils.extractTokenFromHeader(token);
            if (actualToken == null) {
                return null;
            }
            
            // 验证token并获取用户名
            String username = jwtUtils.getUsernameFromToken(actualToken);
            if (username != null && !jwtUtils.isTokenExpired(actualToken)) {
                return username;
            }
            
            return null;
        } catch (Exception e) {
            logger.error("解析token失败", e);
            return null;
        }
    }
}
