using Microsoft.AspNetCore.Mvc;
using TodoList.Api.Models;
using TodoTask = TodoList.Core.Entities.Task;
using TodoList.Core.Entities;
using TodoList.Core.Interfaces;

namespace TodoList.Api.Controllers;

/// <summary>
/// 任务控制器，提供任务的 RESTful API 接口
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class TasksController : ControllerBase
{
    private readonly ITaskService _taskService;

    /// <summary>
    /// 构造函数，注入任务服务
    /// </summary>
    /// <param name="taskService">任务服务接口</param>
    public TasksController(ITaskService taskService)
    {
        _taskService = taskService;
    }

    /// <summary>
    /// 获取任务列表
    /// </summary>
    /// <param name="completed">可选参数，true 获取已完成任务，false 获取未完成任务，不传则获取所有任务</param>
    /// <returns>任务列表响应</returns>
    [HttpGet]
    public async Task<ActionResult<ApiResponse<List<TaskDto>>>> GetTasks([FromQuery] bool? completed = null)
    {
        try
        {
            List<TodoTask> tasks;
            
            if (completed.HasValue)
            {
                tasks = completed.Value 
                    ? await _taskService.GetCompletedTasksAsync()
                    : await _taskService.GetActiveTasksAsync();
            }
            else
            {
                tasks = await _taskService.GetAllTasksAsync();
            }

            var taskDtos = tasks.Select(MapToDto).ToList();
            
            return Ok(new ApiResponse<List<TaskDto>>
            {
                Success = true,
                Data = taskDtos,
                Message = "获取任务列表成功"
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new ApiResponse<List<TaskDto>>
            {
                Success = false,
                Message = "获取任务列表失败",
                Errors = new List<string> { ex.Message }
            });
        }
    }

    /// <summary>
    /// 根据ID获取指定任务
    /// </summary>
    /// <param name="id">任务ID</param>
    /// <returns>任务详情响应</returns>
    [HttpGet("{id}")]
    public async Task<ActionResult<ApiResponse<TaskDto>>> GetTask(int id)
    {
        try
        {
            var task = await _taskService.GetTaskByIdAsync(id);
            if (task == null)
            {
                return NotFound(new ApiResponse<TaskDto>
                {
                    Success = false,
                    Message = $"未找到ID为 {id} 的任务"
                });
            }

            return Ok(new ApiResponse<TaskDto>
            {
                Success = true,
                Data = MapToDto(task),
                Message = "获取任务成功"
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new ApiResponse<TaskDto>
            {
                Success = false,
                Message = "获取任务失败",
                Errors = new List<string> { ex.Message }
            });
        }
    }

    /// <summary>
    /// 创建新任务
    /// </summary>
    /// <param name="dto">创建任务的数据传输对象</param>
    /// <returns>创建的任务响应</returns>
    [HttpPost]
    public async Task<ActionResult<ApiResponse<TaskDto>>> CreateTask([FromBody] CreateTaskDto dto)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(dto.Title))
            {
                return BadRequest(new ApiResponse<TaskDto>
                {
                    Success = false,
                    Message = "任务标题不能为空",
                    Errors = new List<string> { "Title is required" }
                });
            }

            var task = await _taskService.CreateTaskAsync(dto.Title, dto.Priority, dto.ParentTaskId);
            
            return CreatedAtAction(nameof(GetTask), new { id = task.Id }, new ApiResponse<TaskDto>
            {
                Success = true,
                Data = MapToDto(task),
                Message = "创建任务成功"
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new ApiResponse<TaskDto>
            {
                Success = false,
                Message = "创建任务失败",
                Errors = new List<string> { ex.Message }
            });
        }
    }

    /// <summary>
    /// 更新任务
    /// </summary>
    /// <param name="id">任务ID</param>
    /// <param name="dto">更新任务的数据传输对象</param>
    /// <returns>更新后的任务响应</returns>
    [HttpPut("{id}")]
    public async Task<ActionResult<ApiResponse<TaskDto>>> UpdateTask(int id, [FromBody] UpdateTaskDto dto)
    {
        try
        {
            var task = await _taskService.UpdateTaskAsync(id, dto.Title, dto.Priority);
            
            return Ok(new ApiResponse<TaskDto>
            {
                Success = true,
                Data = MapToDto(task),
                Message = "更新任务成功"
            });
        }
        catch (KeyNotFoundException)
        {
            return NotFound(new ApiResponse<TaskDto>
            {
                Success = false,
                Message = $"未找到ID为 {id} 的任务"
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new ApiResponse<TaskDto>
            {
                Success = false,
                Message = "更新任务失败",
                Errors = new List<string> { ex.Message }
            });
        }
    }

    /// <summary>
    /// 切换任务的完成状态
    /// </summary>
    /// <param name="id">任务ID</param>
    /// <returns>更新后的任务响应</returns>
    [HttpPatch("{id}/complete")]
    public async Task<ActionResult<ApiResponse<TaskDto>>> ToggleComplete(int id)
    {
        try
        {
            var task = await _taskService.ToggleCompleteAsync(id);
            
            return Ok(new ApiResponse<TaskDto>
            {
                Success = true,
                Data = MapToDto(task),
                Message = task.IsCompleted ? "任务已完成" : "任务已取消完成"
            });
        }
        catch (KeyNotFoundException)
        {
            return NotFound(new ApiResponse<TaskDto>
            {
                Success = false,
                Message = $"未找到ID为 {id} 的任务"
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new ApiResponse<TaskDto>
            {
                Success = false,
                Message = "更新任务状态失败",
                Errors = new List<string> { ex.Message }
            });
        }
    }

    /// <summary>
    /// 删除任务
    /// </summary>
    /// <param name="id">任务ID</param>
    /// <returns>删除结果响应</returns>
    [HttpDelete("{id}")]
    public async Task<ActionResult<ApiResponse<object>>> DeleteTask(int id)
    {
        try
        {
            await _taskService.DeleteTaskAsync(id);
            
            return Ok(new ApiResponse<object>
            {
                Success = true,
                Message = "删除任务成功"
            });
        }
        catch (KeyNotFoundException)
        {
            return NotFound(new ApiResponse<object>
            {
                Success = false,
                Message = $"未找到ID为 {id} 的任务"
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new ApiResponse<object>
            {
                Success = false,
                Message = "删除任务失败",
                Errors = new List<string> { ex.Message }
            });
        }
    }

    /// <summary>
    /// 将任务实体映射为数据传输对象
    /// </summary>
    /// <param name="task">任务实体</param>
    /// <returns>任务数据传输对象</returns>
    private static TaskDto MapToDto(TodoTask task)
    {
        return new TaskDto
        {
            Id = task.Id,
            Title = task.Title,
            Priority = task.Priority,
            IsCompleted = task.IsCompleted,
            CreatedAt = task.CreatedAt,
            UpdatedAt = task.UpdatedAt,
            ParentTaskId = task.ParentTaskId,
            SubTasks = task.SubTasks?.Select(st => new TaskDto
            {
                Id = st.Id,
                Title = st.Title,
                Priority = st.Priority,
                IsCompleted = st.IsCompleted,
                CreatedAt = st.CreatedAt,
                UpdatedAt = st.UpdatedAt,
                ParentTaskId = st.ParentTaskId,
                SubTasks = new List<TaskDto>()
            }).ToList() ?? new List<TaskDto>()
        };
    }
}
