using CartWise.Application.Interfaces;
using CartWise.Infrastructure.Identity;
using CartWise.Web.ViewModels.Household;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace CartWise.Web.Controllers;

[Authorize]
public class HouseholdController : Controller
{
    private readonly IHouseholdService _householdService;
    private readonly UserManager<ApplicationUser> _userManager;

    public HouseholdController(IHouseholdService householdService, UserManager<ApplicationUser> userManager)
    {
        _householdService = householdService;
        _userManager = userManager;
    }

    [HttpGet]
    [Route("household")]
    public async Task<IActionResult> Index()
    {
        var userId = _userManager.GetUserId(User)!;
        var household = await _householdService.GetCurrentHouseholdAsync(userId);

        if (household is null)
        {
            return RedirectToAction(nameof(Create));
        }

        var members = new List<HouseholdMemberViewModel>();
        foreach (var member in household.Members.OrderBy(m => m.JoinedUtc))
        {
            var memberUser = await _userManager.FindByIdAsync(member.UserId);
            var displayName = !string.IsNullOrWhiteSpace(memberUser?.DisplayName)
                ? memberUser.DisplayName
                : memberUser?.Email ?? "Unknown";

            members.Add(new HouseholdMemberViewModel
            {
                UserId = member.UserId,
                DisplayName = displayName,
                Role = member.Role,
                JoinedUtc = member.JoinedUtc
            });
        }

        var viewModel = new HouseholdIndexViewModel
        {
            HouseholdId = household.HouseholdId,
            Name = household.Name,
            CreatedUtc = household.CreatedUtc,
            Members = members
        };

        return View(viewModel);
    }

    [HttpGet]
    [Route("household/create")]
    public async Task<IActionResult> Create()
    {
        var userId = _userManager.GetUserId(User)!;
        var existingHousehold = await _householdService.GetCurrentHouseholdAsync(userId);

        if (existingHousehold is not null)
        {
            return RedirectToAction(nameof(Index));
        }

        return View(new CreateHouseholdViewModel());
    }

    [HttpPost]
    [Route("household/create")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(CreateHouseholdViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var userId = _userManager.GetUserId(User)!;
        var result = await _householdService.CreateHouseholdAsync(model.Name, userId);

        if (!result.IsSuccess)
        {
            ModelState.AddModelError(string.Empty, result.Error!);
            return View(model);
        }

        return RedirectToAction(nameof(Index));
    }
}
