using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using BookmarkApi.Core.Interfaces;
using BookmarkApi.Shared.DTOs;

namespace BookmarkApi.Controllers;

/// <summary>
/// 标签控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class TagsController : ControllerBase
{
    private readonly ITagService _tagService;

    public TagsController(ITagService tagService)
    {
        _tagService = tagService;
    }

    /// <summary>
    /// 获取标签列表
    /// </summary>
    [HttpGet]
    [ProducesResponseType(typeof(ApiResponse<List<TagDto>>), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse<List<TagDto>>>> GetTags()
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return BadRequest(ApiResponse<List<TagDto>>.Fail("无效的用户"));
        }

        var tags = await _tagService.GetUserTagsAsync(userId.Value);

        return Ok(ApiResponse<List<TagDto>>.Ok(tags));
    }

    /// <summary>
    /// 获取标签详情
    /// </summary>
    [HttpGet("{id:guid}")]
    [ProducesResponseType(typeof(ApiResponse<TagDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse<TagDto>>> GetTag(Guid id)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return BadRequest(ApiResponse<TagDto>.Fail("无效的用户"));
        }

        var tag = await _tagService.GetTagAsync(id, userId.Value);

        if (tag == null)
        {
            return NotFound(ApiResponse<TagDto>.Fail("标签不存在"));
        }

        return Ok(ApiResponse<TagDto>.Ok(tag));
    }

    /// <summary>
    /// 创建标签
    /// </summary>
    [HttpPost]
    [ProducesResponseType(typeof(ApiResponse<TagDto>), StatusCodes.Status201Created)]
    public async Task<ActionResult<ApiResponse<TagDto>>> CreateTag([FromBody] CreateTagRequest request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return BadRequest(ApiResponse<TagDto>.Fail("无效的用户"));
        }

        try
        {
            var tag = await _tagService.CreateTagAsync(userId.Value, request.Name, request.Color, request.Icon);
            return CreatedAtAction(nameof(GetTag), new { id = tag.Id }, ApiResponse<TagDto>.Ok(tag));
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(ApiResponse<TagDto>.Fail(ex.Message));
        }
    }

    /// <summary>
    /// 更新标签
    /// </summary>
    [HttpPut("{id:guid}")]
    [ProducesResponseType(typeof(ApiResponse<TagDto>), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse<TagDto>>> UpdateTag(Guid id, [FromBody] UpdateTagRequest request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return BadRequest(ApiResponse<TagDto>.Fail("无效的用户"));
        }

        try
        {
            var tag = await _tagService.UpdateTagAsync(id, userId.Value, request.Name, request.Color, request.Icon);

            if (tag == null)
            {
                return NotFound(ApiResponse<TagDto>.Fail("标签不存在"));
            }

            return Ok(ApiResponse<TagDto>.Ok(tag));
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(ApiResponse<TagDto>.Fail(ex.Message));
        }
    }

    /// <summary>
    /// 重命名标签（按名称）
    /// </summary>
    [HttpPut("rename/{name}")]
    [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse>> RenameTag(string name, [FromBody] RenameTagRequest request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return BadRequest(ApiResponse.Fail("无效的用户"));
        }

        try
        {
            var success = await _tagService.RenameTagAsync(userId.Value, name, request.NewName);

            if (!success)
            {
                return NotFound(ApiResponse.Fail("标签不存在"));
            }

            return Ok(ApiResponse.Ok("标签已重命名"));
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(ApiResponse.Fail(ex.Message));
        }
    }

    /// <summary>
    /// 删除标签
    /// </summary>
    [HttpDelete("{id:guid}")]
    [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse>> DeleteTag(Guid id)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return BadRequest(ApiResponse.Fail("无效的用户"));
        }

        var success = await _tagService.DeleteTagAsync(id, userId.Value);

        if (!success)
        {
            return NotFound(ApiResponse.Fail("标签不存在"));
        }

        return Ok(ApiResponse.Ok("标签已删除"));
    }

    /// <summary>
    /// 合并标签
    /// </summary>
    [HttpPost("merge")]
    [ProducesResponseType(typeof(ApiResponse<int>), StatusCodes.Status200OK)]
    public async Task<ActionResult<ApiResponse<int>>> MergeTags([FromBody] MergeTagsRequest request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return BadRequest(ApiResponse<int>.Fail("无效的用户"));
        }

        try
        {
            var count = await _tagService.MergeTagsAsync(userId.Value, request.SourceTagIds, request.TargetTagId);
            return Ok(ApiResponse<int>.Ok(count, $"已合并 {count} 个书签的标签"));
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(ApiResponse<int>.Fail(ex.Message));
        }
    }

    private Guid? GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        return Guid.TryParse(userIdClaim, out var userId) ? userId : null;
    }
}

/// <summary>
/// 创建标签请求
/// </summary>
public class CreateTagRequest
{
    /// <summary>
    /// 标签名称
    /// </summary>
    public string Name { get; set; } = string.Empty;

    /// <summary>
    /// 颜色值
    /// </summary>
    public string? Color { get; set; }

    /// <summary>
    /// 图标
    /// </summary>
    public string? Icon { get; set; }
}

/// <summary>
/// 更新标签请求
/// </summary>
public class UpdateTagRequest
{
    /// <summary>
    /// 标签名称
    /// </summary>
    public string? Name { get; set; }

    /// <summary>
    /// 颜色值
    /// </summary>
    public string? Color { get; set; }

    /// <summary>
    /// 图标
    /// </summary>
    public string? Icon { get; set; }
}

/// <summary>
/// 重命名标签请求
/// </summary>
public class RenameTagRequest
{
    /// <summary>
    /// 新标签名称
    /// </summary>
    public string NewName { get; set; } = string.Empty;
}

/// <summary>
/// 合并标签请求
/// </summary>
public class MergeTagsRequest
{
    /// <summary>
    /// 源标签ID数组
    /// </summary>
    public Guid[] SourceTagIds { get; set; } = Array.Empty<Guid>();

    /// <summary>
    /// 目标标签ID
    /// </summary>
    public Guid TargetTagId { get; set; }
}
