using Microsoft.UI.Xaml.Controls;
using Sonex.Data.Database;
using Sonex.Data.Records;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Logger = Sonex.Client.Helpers.Logger;

namespace Sonex.Client.Dialogs;

public sealed partial class ChangePasswordDialog : ContentDialog
{
    private ChangePasswordMode _mode;
    private AccountRecord? _currentAccount;
    private string? _accountName;

    public ChangePasswordDialog()
    {
        InitializeComponent();
        UpdateDescription();
    }

    public string Password => PasswordBox.Password;

    public static ChangePasswordDialog CreateForAccount(string accountName)
    {
        var dialog = new ChangePasswordDialog();
        dialog.ConfigureForAccount(accountName);
        return dialog;
    }

    public static ChangePasswordDialog CreateForCurrentAccount(AccountRecord account)
    {
        var dialog = new ChangePasswordDialog();
        dialog.ConfigureForCurrentAccount(account);
        return dialog;
    }

    public void ConfigureForAccount(string accountName)
    {
        _mode = ChangePasswordMode.SelectedAccount;
        _currentAccount = null;
        _accountName = accountName;
        UpdateDescription();
    }

    public void ConfigureForCurrentAccount(AccountRecord account)
    {
        _mode = ChangePasswordMode.CurrentAccount;
        _currentAccount = account;
        _accountName = account.AccountName;
        UpdateDescription();
    }

    private void UpdateDescription()
    {
        _Message.Text = string.Empty;
        _Description.Text = _mode == ChangePasswordMode.CurrentAccount
            ? "Enter a new password for your account."
            : string.IsNullOrWhiteSpace(_accountName)
                ? "Enter a new password for this account."
                : $"Enter a new password for account '{_accountName}'.";
    }

    private async void ChangePasswordDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
    {
        var deferral = args.GetDeferral();
        args.Cancel = true;

        try
        {
            _Message.Text = string.Empty;
            IsPrimaryButtonEnabled = false;
            IsSecondaryButtonEnabled = false;

            if (string.IsNullOrEmpty(Password))
            {
                _Message.Text = "Password cannot be empty.";
                return;
            }

            var result = await ChangePasswordAsync();
            if (result.Success)
            {
                args.Cancel = false;
            }
            else
            {
                _Message.Text = result.ErrorMessage ?? "Password change failed.";
                Debug.WriteLine(result.ErrorMessage ?? "ChangePasswordDialog failed.");
            }
        }
        catch (Exception ex)
        {
            string errorId = Logger.Error(
                ex,
                source: nameof(ChangePasswordDialog),
                operation: "ChangePasswordDialog_PrimaryButtonClick");
            _Message.Text = Logger.BuildUserMessage(errorId);
        }
        finally
        {
            IsPrimaryButtonEnabled = true;
            IsSecondaryButtonEnabled = true;
            deferral.Complete();
        }
    }

    private Task<DB.SingleResult<bool>> ChangePasswordAsync()
    {
        if (_mode == ChangePasswordMode.CurrentAccount && _currentAccount != null)
            return _currentAccount.ChangeCurrentPassword(Password);

        if (_mode == ChangePasswordMode.SelectedAccount && !string.IsNullOrWhiteSpace(_accountName))
        {
            return new AccountRecord
            {
                AccountName = _accountName
            }.ChangePassword(Password);
        }

        return Task.FromResult(new DB.SingleResult<bool>
        {
            Success = false,
            ErrorMessage = "Password change is not configured."
        });
    }

    private enum ChangePasswordMode
    {
        SelectedAccount,
        CurrentAccount
    }
}
