using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using pavesys_iRAP.Business;
using pavesys_iRAP.Helper;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


public class IRapUser
{
    public int id { get; set; }
    public string username { get; set; }
    public string email { get; set; }
    public string role { get; set; }
    public string empresa { get; set; }
    public string datExpiracao { get; set; }
    public string datHorUltimoLogin {get;set;}
    public string status { get; set; }
     public string viaSegura { get; set; }

    public IRapUser(int _id, string _username, string _email, string _role, string _empresa, string _datExpiracao, string _datHorUltimoLogin, string _status, string _viaSeguraEnabled)
    {
        this.id = _id;
        this.username = _username;
        this.email = _email;
        this.role = _role;
        this.empresa = _empresa;
        this.datExpiracao = _datExpiracao;
        this.datHorUltimoLogin = _datHorUltimoLogin;
        this.status = _status;
        this.viaSegura = _viaSeguraEnabled;   
    }

}
namespace pavesys_iRAP.ViewModels
{



    public partial class GerenciamentoPageViewModel : ViewModelBase
    {
        [ObservableProperty]
        private ObservableCollection<IRapUser> users;
        [ObservableProperty]
        private IRapUser selectedUser;
        [ObservableProperty]
        private string username = string.Empty;
        [ObservableProperty]
        private string email = string.Empty;
        [ObservableProperty]
        private string empresa = string.Empty;
        [ObservableProperty]
        private string password = string.Empty;
        [ObservableProperty]
        private DateTimeOffset? datExpiracao = null;
        [ObservableProperty]
        private int role = 1;
        [ObservableProperty]
        private bool showWrapPanel = false;
        [ObservableProperty]
        private bool showUsernameField = false;
        [ObservableProperty]
        private bool showEmailField = false;
        [ObservableProperty]
        private bool showRoleField = false;
        [ObservableProperty]
        private bool showEmpresaField = false;
        [ObservableProperty]
        private bool showPasswordField = false;
        [ObservableProperty]
        private bool showDateField = false;
        [ObservableProperty]
        private bool showCancelField = false;

        private int selectedUserWhenChangePasswordClicked;

        private string currentCommand;
        public RelayCommand deleteUser { get; }
        public RelayCommand showCreateUserFields { get; }

        public RelayCommand showChangePasswordFields { get; }
        public RelayCommand changeRole { get; }
        public RelayCommand runSaveButton { get; }
        public RelayCommand changeUserStatus { get; }

        public GerenciamentoPageViewModel()
        {

            Users = new();
            deleteUser = new(DeleteUser);
            showCreateUserFields = new(ShowCreateUserFields);
            runSaveButton = new(SaveButton);
            changeRole = new(ChangeRole);
            showChangePasswordFields  = new(ShowChangePasswordFields);  
            changeUserStatus = new(ChangeUserStatus);
        }
        [RelayCommand]
        public void CancelOperation() 
        {
            HideCreateUserFields();
            Username = string.Empty;
            Email = string.Empty;
            Password = string.Empty;
            DatExpiracao = null;
        }

        public void ShowCreateUserFields()
        {
            ShowWrapPanel = true;
            ShowUsernameField = true;
            ShowEmailField = true;
            ShowPasswordField = true;
            ShowRoleField = true;
            ShowEmpresaField = true;
            ShowDateField = true;
            ShowCancelField = true;

            currentCommand = "Create";
        }

        public async void ShowChangePasswordFields()
        {
            HideCreateUserFields();
            if (SelectedUser is null)
            {
                await DialogHelper.ShowOkDialog("Attention", "", nonLocalizedContent: "Selecione um usuário primeiro.");
                return;
            }

            ShowWrapPanel = true;
            ShowPasswordField = true;
            ShowCancelField = true;

            selectedUserWhenChangePasswordClicked = SelectedUser.id;
            currentCommand = "ChangePassword";
        }
        [RelayCommand]
        public async void ShowChangeExpireDateFields() 
        {
            HideCreateUserFields();
            if (SelectedUser is null)
            {
                await DialogHelper.ShowOkDialog("Attention", "", nonLocalizedContent: "Selecione um usuário primeiro.");
                return;
            }
            ShowWrapPanel = true;
            ShowDateField = true;
            ShowCancelField = true;

            selectedUserWhenChangePasswordClicked = SelectedUser.id;
            currentCommand = "ChangeExpireDate";
        }

        public void HideCreateUserFields()
        {
            Username = string.Empty;
            Password = string.Empty;
            Email = string.Empty;
            Role = 1;
            Empresa = string.Empty;
            DatExpiracao = null;
            ShowWrapPanel = false;
            ShowUsernameField = false;
            ShowEmailField = false;
            ShowPasswordField = false;
            ShowRoleField = false;
            ShowEmpresaField = false;
            ShowDateField = false;
            ShowCancelField = false;
            currentCommand = "";
        }

        public async Task CreateUser()
        {
            var userRole = Role switch
            {
                0 => "ADMIN",
                _ => "USER"
            };
            string dataExpiracaoFormata = string.Empty;
            if (DatExpiracao is not null)
                dataExpiracaoFormata = DatExpiracao.Value.ToString("yyyy-MM-dd");
            if (Password == string.Empty || Empresa == string.Empty || Username == string.Empty || Email == string.Empty || DatExpiracao == null) 
            {
                await DialogHelper.ShowOkDialog("Attention", "", nonLocalizedContent: "Preencha todos os campos para cadatrar um usuário");
                return;
            }
            if (Password.Length < 8) 
            {
                await DialogHelper.ShowOkDialog("Attention", "", nonLocalizedContent: "A senha deve ter mais de 8 caracteres");
                return;
            }
            if(DatExpiracao.Value < DateTimeOffset.Now) 
            {
                await DialogHelper.ShowOkDialog("Attention", "", nonLocalizedContent: "A data de expiração não pode ser anterior a data atual");
                return;
            }

            foreach (var item in this.Users) {
                if (item.email == Email) 
                {
                    await DialogHelper.ShowOkDialog("Error", "", nonLocalizedContent: $"Este email já foi cadastrado");
                    return;
                }
                if (item.username == Username) {
                    await DialogHelper.ShowOkDialog("Error", "", nonLocalizedContent: $"Este nome de usuário já foi cadastrado.");
                    return;
                }
            }

            (bool,string) resultCreateUser = await AuthModule.CreateUser(Username, userRole, Email, Password, Empresa, dataExpiracaoFormata);
            if (!resultCreateUser.Item1) 
            {
                await DialogHelper.ShowOkDialog("Error", "", nonLocalizedContent: $" {resultCreateUser.Item2}");
                return;
            }

            HideCreateUserFields();
            Users = await AuthModule.GetIRapUsersAsync();
        }
        public async void ChangeRole()
        {
            if (SelectedUser is null)
            {
                await DialogHelper.ShowOkDialog("Attention","", nonLocalizedContent: "Selecione um usuário primeiro.");
                return;
            }

            if (await DialogHelper.ShowYesNoDialog("Attention", "", $"Atenção, Deseja mesmo modificar o cargo do usuário: {SelectedUser.username}", MsBox.Avalonia.Enums.Icon.Warning))
            {

                var _role = SelectedUser.role switch
                {
                    "ADMIN" => "USER",
                    "USER" => "ADMIN"
                };
                await AuthModule.ChangeRole(SelectedUser.id, _role);
            }
            Users =  await AuthModule.GetIRapUsersAsync();
        }
        [RelayCommand]
        public async void ChangeUserViaSeguraAccess() 
        {
            if (SelectedUser is null)
            {
                await DialogHelper.ShowOkDialog("Attention", "", nonLocalizedContent: "Selecione um usuário primeiro.");
                return;
            }

            if (await DialogHelper.ShowYesNoDialog("Attention", "", $"Atenção, Deseja mesmo modificar o acesso a ViaSegura do usuário: {SelectedUser.username}", MsBox.Avalonia.Enums.Icon.Warning))
            {

                var accessType = SelectedUser.viaSegura switch
                {
                    "GRANTED" => 0,
                    "DENIED" => 1,
                    _ => 0
                };
                await AuthModule.ChangeViaSegura(SelectedUser.id, accessType);
            }
            Users = await AuthModule.GetIRapUsersAsync();
        }
        public async void ChangePassword()  
        {
            

            await AuthModule.ChangePassword(selectedUserWhenChangePasswordClicked, Password);

            HideCreateUserFields();

        }

        public async void SaveButton()
        {

            if (currentCommand == "Create")
                await CreateUser();
            if (currentCommand == "ChangePassword")
                ChangePassword();
            if (currentCommand == "ChangeExpireDate")
                ChangeExpireDate();
        }
        public async void DeleteUser()
        {
            if (SelectedUser is null)
            {
                await DialogHelper.ShowOkDialog("Attention", "", nonLocalizedContent: "Selecione um usuário primeiro.");
                return;
            }

            if (await DialogHelper.ShowYesNoDialog("Attention", "", $"Atenção \n Deseja mesmo deletar o usuário: {SelectedUser.email}?", MsBox.Avalonia.Enums.Icon.Warning))
            {
                if (await AuthModule.DeleteUser(SelectedUser.id))
                {
                    Users = await AuthModule.GetIRapUsersAsync();
                }
                else
                {
                    await DialogHelper.ShowOkDialog("Error", "", nonLocalizedContent: "Erro ao deletar usuário");
                }
            }

        }

        public async void ChangeUserStatus() 
        {
            if (SelectedUser is null)
            {
                await DialogHelper.ShowOkDialog("Attention", "", nonLocalizedContent: "Selecione um usuário primeiro.");
                return;
            }

            if (selectedUser.status != "EXPIRADO") 
            {
                if (selectedUser.status == "ATIVO")
                    await AuthModule.SuspendUser(selectedUser.id);
                else
                    await AuthModule.ActivateUser(selectedUser.id);
            }

            Users = await AuthModule.GetIRapUsersAsync();
        }

        public async void ChangeExpireDate() 
        {

            if (DatExpiracao.Value < DateTimeOffset.Now)
            {
                await DialogHelper.ShowOkDialog("Attention", "", nonLocalizedContent: "A data de expiração não pode ser anterior a data atual");
                return;
            }

            await AuthModule.ExtendExpiration(selectedUserWhenChangePasswordClicked, DatExpiracao.Value.ToString("yyyy-MM-dd"));
            HideCreateUserFields();
            Users = await AuthModule.GetIRapUsersAsync();

        }

    }
}
