using System.ComponentModel.DataAnnotations;
using System.Text;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using PowderCoating.Application.Interfaces;
using PowderCoating.Core.Entities;

namespace PowderCoating.Web.Areas.Identity.Pages.Account;

public class ForgotPasswordModel : PageModel
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly IEmailService _emailService;
    private readonly ILogger<ForgotPasswordModel> _logger;

    public ForgotPasswordModel(
        UserManager<ApplicationUser> userManager,
        IEmailService emailService,
        ILogger<ForgotPasswordModel> logger)
    {
        _userManager = userManager;
        _emailService = emailService;
        _logger = logger;
    }

    [BindProperty]
    public InputModel Input { get; set; } = new();

    public bool EmailSent { get; set; }

    public class InputModel
    {
        [Required(ErrorMessage = "Email address is required.")]
        [EmailAddress(ErrorMessage = "Please enter a valid email address.")]
        public string Email { get; set; } = string.Empty;
    }

    public void OnGet() { }

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
            return Page();

        // Always show the confirmation view regardless of whether the email exists —
        // this prevents user enumeration attacks.
        EmailSent = true;

        var user = await _userManager.FindByEmailAsync(Input.Email);
        if (user == null || !user.IsActive)
        {
            _logger.LogInformation("Password reset requested for unknown or inactive email: {Email}", Input.Email);
            return Page();
        }

        var token = await _userManager.GeneratePasswordResetTokenAsync(user);
        var encodedToken = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(token));

        var resetLink = Url.Page(
            "/Account/ResetPassword",
            pageHandler: null,
            values: new { area = "Identity", token = encodedToken, email = Input.Email },
            protocol: Request.Scheme)!;

        var htmlBody = $"""
            <div style="font-family: Arial, sans-serif; max-width: 560px; margin: 0 auto;">
                <div style="background: linear-gradient(135deg,#1a1a2e,#0f3460); padding: 2rem; text-align: center; border-radius: 8px 8px 0 0;">
                    <img src="https://powdercoatinglogix.com/images/pcl-logo.png" alt="Powder Coating Logix" style="max-width:180px; display:block; margin:0 auto 0.5rem;" onerror="this.style.display='none'" />
                    <h1 style="color:#4fc3f7; margin:0; font-size:1.5rem;">Powder Coating Logix</h1>
                </div>
                <div style="background:#fff; padding: 2rem; border: 1px solid #e2e8f0; border-top:none; border-radius: 0 0 8px 8px;">
                    <h2 style="color:#0f172a; margin-top:0;">Reset your password</h2>
                    <p style="color:#475569;">
                        We received a request to reset the password for your account (<strong>{HtmlEncoder.Default.Encode(Input.Email)}</strong>).
                        Click the button below to choose a new password.
                    </p>
                    <div style="text-align:center; margin: 2rem 0;">
                        <a href="{HtmlEncoder.Default.Encode(resetLink)}"
                           style="background:#0d6efd; color:#fff; padding: 0.85rem 2rem; border-radius: 6px;
                                  text-decoration:none; font-weight:600; font-size:1rem; display:inline-block;">
                            Reset Password
                        </a>
                    </div>
                    <p style="color:#64748b; font-size:0.875rem;">
                        This link expires in <strong>24 hours</strong>. If you didn't request a password reset,
                        you can safely ignore this email — your password will not change.
                    </p>
                    <hr style="border:none; border-top:1px solid #e2e8f0; margin:1.5rem 0;">
                    <p style="color:#94a3b8; font-size:0.8rem;">
                        If the button above doesn't work, copy and paste this URL into your browser:<br>
                        <a href="{HtmlEncoder.Default.Encode(resetLink)}" style="color:#0d6efd; word-break:break-all;">{HtmlEncoder.Default.Encode(resetLink)}</a>
                    </p>
                </div>
            </div>
            """;

        var plainBody = $"Reset your Powder Coating Logix password\n\n" +
                        $"We received a request to reset the password for {Input.Email}.\n\n" +
                        $"Click the link below to reset your password (expires in 24 hours):\n{resetLink}\n\n" +
                        $"If you didn't request this, you can safely ignore this email.";

        var result = await _emailService.SendEmailAsync(
            toEmail: user.Email!,
            toName: user.FullName,
            subject: "Reset your Powder Coating Logix password",
            plainTextBody: plainBody,
            htmlBody: htmlBody);

        if (!result.Success)
            _logger.LogWarning("Failed to send password reset email to {Email}: {Error}", Input.Email, result.ErrorMessage);
        else
            _logger.LogInformation("Password reset email sent to {Email}", Input.Email);

        return Page();
    }
}
