using System.Security.Claims;
using LearningMaterialSystem.Data;
using LearningMaterialSystem.Models;
using LearningMaterialSystem.Services;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace LearningMaterialSystem.Controllers;

[AllowAnonymous]
public class AccountController : Controller
{
    private readonly ApplicationDbContext _context;

    public AccountController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    public IActionResult Login(string? returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel model, string? returnUrl = null, CancellationToken cancellationToken = default)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (string.IsNullOrWhiteSpace(model.TenDangNhap) || string.IsNullOrWhiteSpace(model.MatKhau))
        {
            ModelState.AddModelError("", "Vui lòng nhập tên đăng nhập và mật khẩu.");
            return View(model);
        }

        var user = await _context.NguoiDungs.AsNoTracking()
            .FirstOrDefaultAsync(u => u.TenDangNhap == model.TenDangNhap, cancellationToken);
        if (user == null || !PasswordHelper.Verify(model.MatKhau, user.MatKhauHash))
        {
            ModelState.AddModelError("", "Tên đăng nhập hoặc mật khẩu không đúng.");
            return View(model);
        }

        var claims = new List<Claim>
        {
            new(ClaimTypes.NameIdentifier, user.Id.ToString()),
            new(ClaimTypes.Name, user.HoTen),
            // Quan trọng: IsInRole() dựa vào ClaimTypes.Role
            new(ClaimTypes.Role, user.VaiTro),
            new("VaiTro", user.VaiTro),
            new(ClaimTypes.Email, user.Email ?? "")
        };
        var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        var principal = new ClaimsPrincipal(identity);
        var props = new AuthenticationProperties
        {
            IsPersistent = model.NhoDangNhap,
            ExpiresUtc = DateTimeOffset.UtcNow.AddHours(8)
        };
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, props);

        return LocalRedirect(returnUrl ?? "/");
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Logout()
    {
        await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        return RedirectToAction("Index", "Home");
    }

    public IActionResult AccessDenied()
    {
        return View();
    }
}

public class LoginViewModel
{
    public string TenDangNhap { get; set; } = "";
    public string MatKhau { get; set; } = "";
    public bool NhoDangNhap { get; set; }
}
