package com.reading.platform.controller.parent;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reading.platform.common.response.PageResult;
import com.reading.platform.common.response.Result;
import com.reading.platform.common.security.SecurityUtils;
import com.reading.platform.dto.response.*;
import com.reading.platform.entity.Lesson;
import com.reading.platform.entity.Student;
import com.reading.platform.entity.TaskCompletion;
import com.reading.platform.service.LessonService;
import com.reading.platform.service.StudentService;
import com.reading.platform.service.TaskService;
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.*;

@Tag(name = "家长 - 孩子", description = "孩子信息接口（家长专用）")
@RestController
@RequestMapping("/api/v1/parent/children")
@RequiredArgsConstructor
public class ParentChildController {

    private final StudentService studentService;
    private final LessonService lessonService;
    private final TaskService taskService;

    @Operation(summary = "获取我的孩子")
    @GetMapping
    public Result<List<ChildInfoResponse>> getMyChildren() {
        String parentId = SecurityUtils.getCurrentUserId();
        List<Student> students = studentService.getStudentsByParentId(parentId);

        List<ChildInfoResponse> result = new ArrayList<>();
        for (Student student : students) {
            ChildInfoResponse response = new ChildInfoResponse();
            response.setId(student.getId());
            response.setName(student.getName());
            response.setGender(student.getGender());
            response.setBirthDate(student.getBirthDate() != null ? student.getBirthDate().toString() : null);
            response.setReadingCount(student.getReadingCount() != null ? student.getReadingCount() : 0);
            response.setLessonCount(student.getLessonCount() != null ? student.getLessonCount() : 0);
            response.setClassInfo(new ChildInfoResponse.ClassInfo());
            response.setRelationship("parent");
            result.add(response);
        }
        return Result.success(result);
    }

    @Operation(summary = "根据 ID 获取孩子详情")
    @GetMapping("/{id}")
    public Result<ChildDetailResponse> getChild(@PathVariable String id) {
        Student student = studentService.getStudentById(id);

        ChildDetailResponse response = new ChildDetailResponse();
        response.setId(student.getId());
        response.setName(student.getName());
        response.setGender(student.getGender());
        response.setBirthDate(student.getBirthDate() != null ? student.getBirthDate().toString() : null);
        response.setReadingCount(student.getReadingCount() != null ? student.getReadingCount() : 0);
        response.setLessonCount(student.getLessonCount() != null ? student.getLessonCount() : 0);

        ChildDetailResponse.ChildStats stats = new ChildDetailResponse.ChildStats();
        stats.setLessonRecords(student.getLessonCount() != null ? student.getLessonCount() : 0);
        stats.setGrowthRecords(0);
        stats.setTaskCompletions(0);
        response.setStats(stats);

        response.setClassInfo(new ChildDetailResponse.ClassInfo());
        response.setRelationship("parent");

        return Result.success(response);
    }

    @Operation(summary = "获取孩子的课时记录")
    @GetMapping("/{childId}/lessons")
    public Result<CommonPageResponse<Lesson>> getChildLessons(
            @PathVariable String childId,
            @RequestParam(value = "page", required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize) {

        if (pageNum == null) pageNum = 1;
        if (pageSize == null) pageSize = 10;

        Page<Lesson> page = lessonService.getLessonPage(null, pageNum, pageSize, null, null, "completed", null, null);

        return Result.success(CommonPageResponse.of(page.getRecords(), page.getTotal(), (int) page.getCurrent(), (int) page.getSize()));
    }

    @Operation(summary = "获取孩子的任务")
    @GetMapping("/{childId}/tasks")
    public Result<CommonPageResponse<TaskCompletionInfoResponse>> getChildTasks(
            @PathVariable String childId,
            @RequestParam(value = "page", required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String status) {

        if (pageNum == null) pageNum = 1;
        if (pageSize == null) pageSize = 10;

        Page<TaskCompletion> completionsPage = taskService.getTaskCompletions(null, childId, pageNum, pageSize, status);

        List<TaskCompletionInfoResponse> items = new ArrayList<>();
        for (TaskCompletion completion : completionsPage.getRecords()) {
            TaskCompletionInfoResponse response = new TaskCompletionInfoResponse();
            response.setId(completion.getId());
            response.setTaskId(completion.getTaskId());
            response.setStudentId(completion.getStudentId());
            response.setStatus(completion.getStatus());
            response.setCompletedAt(completion.getCreatedAt() != null ? completion.getCreatedAt().toString() : null);
            response.setFeedback(completion.getFeedback());
            response.setParentFeedback(completion.getFeedback());
            items.add(response);
        }

        return Result.success(CommonPageResponse.of(items, completionsPage.getTotal(), (int) completionsPage.getCurrent(), (int) completionsPage.getSize()));
    }

}
