using System.Security.Claims;
using HoneyBox.Core.Interfaces;
using HoneyBox.Model.Base;
using HoneyBox.Model.Models.Address;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace HoneyBox.Api.Controllers;

/// <summary>
/// 地址控制器 - 处理用户收货地址相关功能
/// </summary>
/// <remarks>
/// 提供地址的增删改查、设置默认地址等功能
/// Requirements: 1.1-1.7
/// </remarks>
[ApiController]
[Route("api")]
public class AddressController : ControllerBase
{
    private readonly IAddressService _addressService;
    private readonly ILogger<AddressController> _logger;

    public AddressController(IAddressService addressService, ILogger<AddressController> logger)
    {
        _addressService = addressService;
        _logger = logger;
    }

    /// <summary>
    /// 添加收货地址
    /// </summary>
    /// <remarks>
    /// POST /api/addAddress
    /// 
    /// 每位用户最多只能添加10条收货地址
    /// Requirements: 1.1
    /// </remarks>
    [HttpPost("addAddress")]
    [Authorize]
    [ProducesResponseType(typeof(ApiResponse<AddressDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<AddressDto>> AddAddress([FromBody] AddAddressRequest request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<AddressDto>.Unauthorized();
        }

        // 参数验证
        if (string.IsNullOrWhiteSpace(request.ReceiverName))
        {
            return ApiResponse<AddressDto>.Fail("请输入收货人姓名");
        }
        if (string.IsNullOrWhiteSpace(request.ReceiverPhone))
        {
            return ApiResponse<AddressDto>.Fail("请输入收货人电话");
        }
        if (!IsValidMobile(request.ReceiverPhone))
        {
            return ApiResponse<AddressDto>.Fail("请输入正确的手机号");
        }
        if (string.IsNullOrWhiteSpace(request.DetailedAddress))
        {
            return ApiResponse<AddressDto>.Fail("请输入详细地址");
        }

        try
        {
            var address = await _addressService.AddAddressAsync(userId.Value, request);
            return ApiResponse<AddressDto>.Success(address, "添加成功");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Add address failed: UserId={UserId}, Error={Error}", userId, ex.Message);
            return ApiResponse<AddressDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to add address: UserId={UserId}", userId);
            return ApiResponse<AddressDto>.Fail("添加失败");
        }
    }

    /// <summary>
    /// 更新收货地址
    /// </summary>
    /// <remarks>
    /// POST /api/updateAddress
    /// Requirements: 1.2
    /// </remarks>
    [HttpPost("updateAddress")]
    [Authorize]
    [ProducesResponseType(typeof(ApiResponse<AddressDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<AddressDto>> UpdateAddress([FromBody] UpdateAddressRequest request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<AddressDto>.Unauthorized();
        }

        // 参数验证
        if (request.Id <= 0)
        {
            return ApiResponse<AddressDto>.Fail("请选择要修改的地址");
        }
        if (string.IsNullOrWhiteSpace(request.ReceiverName))
        {
            return ApiResponse<AddressDto>.Fail("请输入收货人姓名");
        }
        if (string.IsNullOrWhiteSpace(request.ReceiverPhone))
        {
            return ApiResponse<AddressDto>.Fail("请输入收货人电话");
        }
        if (!IsValidMobile(request.ReceiverPhone))
        {
            return ApiResponse<AddressDto>.Fail("请输入正确的手机号");
        }
        if (string.IsNullOrWhiteSpace(request.DetailedAddress))
        {
            return ApiResponse<AddressDto>.Fail("请输入详细地址");
        }

        try
        {
            var address = await _addressService.UpdateAddressAsync(userId.Value, request);
            return ApiResponse<AddressDto>.Success(address, "修改成功");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Update address failed: UserId={UserId}, Error={Error}", userId, ex.Message);
            return ApiResponse<AddressDto>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to update address: UserId={UserId}", userId);
            return ApiResponse<AddressDto>.Fail("修改失败");
        }
    }

    /// <summary>
    /// 获取默认收货地址
    /// </summary>
    /// <remarks>
    /// GET /api/getDefaultAddress
    /// Requirements: 1.3
    /// </remarks>
    [HttpGet("getDefaultAddress")]
    [Authorize]
    [ProducesResponseType(typeof(ApiResponse<AddressDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<AddressDto?>> GetDefaultAddress()
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<AddressDto?>.Unauthorized();
        }

        try
        {
            var address = await _addressService.GetDefaultAddressAsync(userId.Value);
            return ApiResponse<AddressDto?>.Success(address, "获取成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get default address: UserId={UserId}", userId);
            return ApiResponse<AddressDto?>.Fail("获取失败");
        }
    }


    /// <summary>
    /// 获取收货地址列表
    /// </summary>
    /// <remarks>
    /// GET /api/getAddressList
    /// Requirements: 1.4
    /// </remarks>
    [HttpGet("getAddressList")]
    [Authorize]
    [ProducesResponseType(typeof(ApiResponse<List<AddressDto>>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<List<AddressDto>>> GetAddressList()
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<List<AddressDto>>.Unauthorized();
        }

        try
        {
            var addresses = await _addressService.GetAddressListAsync(userId.Value);
            return ApiResponse<List<AddressDto>>.Success(addresses, "获取成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get address list: UserId={UserId}", userId);
            return ApiResponse<List<AddressDto>>.Fail("获取失败");
        }
    }

    /// <summary>
    /// 删除收货地址
    /// </summary>
    /// <remarks>
    /// POST /api/deleteAddress
    /// Requirements: 1.5
    /// </remarks>
    [HttpPost("deleteAddress")]
    [Authorize]
    [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)]
    public async Task<ApiResponse> DeleteAddress([FromBody] AddressIdRequest request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse.Unauthorized();
        }

        if (request.Id <= 0)
        {
            return ApiResponse.Fail("请选择要删除的地址");
        }

        try
        {
            await _addressService.DeleteAddressAsync(userId.Value, request.Id);
            return ApiResponse.Success("删除成功");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Delete address failed: UserId={UserId}, Error={Error}", userId, ex.Message);
            return ApiResponse.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to delete address: UserId={UserId}", userId);
            return ApiResponse.Fail("删除失败");
        }
    }

    /// <summary>
    /// 设置默认收货地址
    /// </summary>
    /// <remarks>
    /// POST /api/setDefaultAddress
    /// Requirements: 1.6
    /// </remarks>
    [HttpPost("setDefaultAddress")]
    [Authorize]
    [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)]
    public async Task<ApiResponse> SetDefaultAddress([FromBody] AddressIdRequest request)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse.Unauthorized();
        }

        if (request.Id <= 0)
        {
            return ApiResponse.Fail("请选择要设为默认的地址");
        }

        try
        {
            await _addressService.SetDefaultAddressAsync(userId.Value, request.Id);
            return ApiResponse.Success("设置成功");
        }
        catch (InvalidOperationException ex)
        {
            _logger.LogWarning("Set default address failed: UserId={UserId}, Error={Error}", userId, ex.Message);
            return ApiResponse.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to set default address: UserId={UserId}", userId);
            return ApiResponse.Fail("设置失败");
        }
    }

    /// <summary>
    /// 获取地址详情
    /// </summary>
    /// <remarks>
    /// GET /api/getAddressDetail
    /// Requirements: 1.7
    /// </remarks>
    [HttpGet("getAddressDetail")]
    [Authorize]
    [ProducesResponseType(typeof(ApiResponse<AddressDto>), StatusCodes.Status200OK)]
    public async Task<ApiResponse<AddressDto?>> GetAddressDetail([FromQuery] int id)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return ApiResponse<AddressDto?>.Unauthorized();
        }

        if (id <= 0)
        {
            return ApiResponse<AddressDto?>.Fail("请选择要查看的地址");
        }

        try
        {
            var address = await _addressService.GetAddressDetailAsync(userId.Value, id);
            if (address == null)
            {
                return ApiResponse<AddressDto?>.Fail("地址不存在");
            }
            return ApiResponse<AddressDto?>.Success(address, "获取成功");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get address detail: UserId={UserId}, AddressId={AddressId}", userId, id);
            return ApiResponse<AddressDto?>.Fail("获取失败");
        }
    }

    #region Private Helper Methods

    /// <summary>
    /// 获取当前登录用户ID
    /// </summary>
    private int? GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
        if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out var userId))
        {
            return null;
        }
        return userId;
    }

    /// <summary>
    /// 验证手机号格式
    /// </summary>
    private static bool IsValidMobile(string mobile)
    {
        if (string.IsNullOrWhiteSpace(mobile))
            return false;
        
        // 中国大陆手机号：11位数字，以1开头
        return mobile.Length == 11 && mobile.StartsWith("1") && mobile.All(char.IsDigit);
    }

    #endregion
}
