using System.Diagnostics;
using MemberCenter.Application.Abstractions;
using MemberCenter.Application.Constants;
using MemberCenter.Application.Models.Profile;
using MemberCenter.Infrastructure.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using MemberCenter.Web.Models;
using MemberCenter.Web.Models.Profile;
using MemberCenter.Web.Services;

namespace MemberCenter.Web.Controllers;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly IProfileService _profileService;
    private readonly AdminDashboardFactory _adminDashboardFactory;
    private readonly UserManager<ApplicationUser> _userManager;

    public HomeController(
        ILogger<HomeController> logger,
        IProfileService profileService,
        AdminDashboardFactory adminDashboardFactory,
        UserManager<ApplicationUser> userManager)
    {
        _logger = logger;
        _profileService = profileService;
        _adminDashboardFactory = adminDashboardFactory;
        _userManager = userManager;
    }

    public async Task<IActionResult> Index()
    {
        if (User.IsInRole(AdminPermissions.AdminRole) || User.IsInRole(AdminPermissions.SuperuserRole))
        {
            ViewData["Title"] = "後台管理";
            return View(await _adminDashboardFactory.BuildAsync());
        }

        var user = await _userManager.GetUserAsync(User);
        if (user is null)
        {
            return RedirectToAction("Login", "Account", new { area = string.Empty });
        }

        var profile = await _profileService.GetProfileAsync(user.Id);
        var profileImage = await _profileService.GetProfileImageAsync(user.Id);
        return View("~/Views/Profile/Index.cshtml", new ProfileIndexPageViewModel
        {
            Profile = MapProfile(profile, user.EmailConfirmed),
            Addresses = await _profileService.ListAddressesAsync(user.Id),
            HasProfileImage = profileImage is not null,
            ProfileImageVersion = profileImage?.UpdatedAt.ToUnixTimeSeconds() ?? 0
        });
    }

    [AllowAnonymous]
    public IActionResult Privacy()
    {
        return View();
    }

    [AllowAnonymous]
    public IActionResult Terms()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    [AllowAnonymous]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }

    private static ProfileViewModel MapProfile(UserProfileDto profile, bool emailConfirmed) =>
        new()
        {
            Email = profile.Email,
            EmailConfirmed = emailConfirmed,
            LastName = profile.LastName,
            FirstName = profile.FirstName,
            NickName = profile.NickName,
            MobilePhone = profile.MobilePhone,
            LandlinePhone = profile.LandlinePhone,
            DateOfBirth = profile.DateOfBirth,
            Gender = profile.Gender,
            CompanyName = profile.CompanyName,
            Department = profile.Department,
            JobTitle = profile.JobTitle,
            CompanyPhone = profile.CompanyPhone,
            TaxId = profile.TaxId,
            InvoiceTitle = profile.InvoiceTitle,
            Remark = profile.Remark
        };
}
