package com.reading.platform.controller.admin;

import com.reading.platform.common.annotation.RequireRole;
import com.reading.platform.common.enums.UserRole;
import com.reading.platform.common.response.Result;
import com.reading.platform.dto.response.*;
import com.reading.platform.service.AdminStatsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.ArrayList;

@Tag(name = "管理员 - 统计", description = "管理员统计仪表盘")
@RestController
@RequestMapping("/api/v1/admin/stats")
@RequiredArgsConstructor
@RequireRole(UserRole.ADMIN)
public class AdminStatsController {

    private final AdminStatsService adminStatsService;

    @Operation(summary = "获取整体统计数据")
    @GetMapping
    public Result<AdminStatsResponse> getStats() {
        Map<String, Object> stats = adminStatsService.getStats();

        AdminStatsResponse response = new AdminStatsResponse();
        response.setTenantCount((Integer) stats.get("tenantCount"));
        response.setActiveTenantCount((Integer) stats.get("activeTenantCount"));
        response.setTeacherCount((Integer) stats.get("teacherCount"));
        response.setStudentCount((Integer) stats.get("studentCount"));
        response.setCourseCount((Integer) stats.get("courseCount"));
        response.setPublishedCourseCount((Integer) stats.get("publishedCourseCount"));
        response.setLessonCount((Integer) stats.get("lessonCount"));
        response.setMonthlyLessons((Integer) stats.get("monthlyLessons"));

        return Result.success(response);
    }

    @Operation(summary = "获取趋势数据（近6个月）")
    @GetMapping("/trend")
    public Result<List<TrendDataPointResponse>> getTrendData() {
        List<Map<String, Object>> trend = adminStatsService.getTrendData();

        List<TrendDataPointResponse> result = new ArrayList<>();
        for (Map<String, Object> item : trend) {
            TrendDataPointResponse response = new TrendDataPointResponse();
            response.setMonth((String) item.get("month"));
            response.setTenantCount((Integer) item.get("tenantCount"));
            response.setLessonCount((Integer) item.get("lessonCount"));
            response.setStudentCount((Integer) item.get("studentCount"));
            result.add(response);
        }
        return Result.success(result);
    }

    @Operation(summary = "获取活跃租户")
    @GetMapping("/tenants/active")
    public Result<List<TenantStatsResponse>> getActiveTenants(
            @RequestParam(defaultValue = "10") int limit) {
        List<Map<String, Object>> tenants = adminStatsService.getActiveTenants(limit);

        List<TenantStatsResponse> result = new ArrayList<>();
        for (Map<String, Object> item : tenants) {
            TenantStatsResponse response = new TenantStatsResponse();
            response.setId(item.get("id") != null ? item.get("id") != null ? item.get("id").toString() : null : null);
            response.setName((String) item.get("name"));
            response.setCode((String) item.get("code"));
            response.setStatus((String) item.get("status"));
            response.setExpireAt(item.get("expireAt") != null ? item.get("expireAt").toString() : null);
            response.setTeacherCount((Integer) item.get("teacherCount"));
            response.setStudentCount((Integer) item.get("studentCount"));
            response.setLessonCount((Integer) item.get("lessonCount"));
            result.add(response);
        }
        return Result.success(result);
    }

    @Operation(summary = "获取热门课程")
    @GetMapping("/courses/popular")
    public Result<List<CourseStatsResponse>> getPopularCourses(
            @RequestParam(defaultValue = "10") int limit) {
        List<Map<String, Object>> courses = adminStatsService.getPopularCourses(limit);

        List<CourseStatsResponse> result = new ArrayList<>();
        for (Map<String, Object> item : courses) {
            CourseStatsResponse response = new CourseStatsResponse();
            response.setId(item.get("id") != null ? item.get("id") != null ? item.get("id").toString() : null : null);
            response.setName((String) item.get("name"));
            response.setCategory((String) item.get("category"));
            response.setStatus((String) item.get("status"));
            response.setUsageCount((Integer) item.get("usageCount"));
            response.setTeacherCount((Integer) item.get("teacherCount"));
            result.add(response);
        }
        return Result.success(result);
    }

    @Operation(summary = "获取最近活动")
    @GetMapping("/activities")
    public Result<List<LessonActivityResponse>> getActivities(
            @RequestParam(defaultValue = "10") int limit) {
        List<Map<String, Object>> activities = adminStatsService.getRecentActivities(limit);

        List<LessonActivityResponse> result = new ArrayList<>();
        for (Map<String, Object> item : activities) {
            LessonActivityResponse response = new LessonActivityResponse();
            response.setId(item.get("id") != null ? item.get("id") != null ? item.get("id").toString() : null : null);
            response.setTitle((String) item.get("title"));
            response.setLessonDate(item.get("lessonDate") != null ? item.get("lessonDate").toString() : null);
            response.setStatus((String) item.get("status"));
            result.add(response);
        }
        return Result.success(result);
    }

    @Operation(summary = "获取课时趋势（近 N 个月）")
    @GetMapping("/lesson-trend")
    public Result<List<Map<String, Object>>> getLessonTrend(
            @RequestParam(value = "months", required = false, defaultValue = "6") Integer months) {
        return Result.success(adminStatsService.getLessonTrend(months));
    }
}
