using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Http.Json;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace LSFE.MobApp.ViewModels.Authentication
{
    public class ForgotPasswordVM : INotifyPropertyChanged
    {
        private readonly HttpClient _httpClient;
        private readonly Services.INavigationService _navigationService;

        private string _username;
        private string _errorMessage;
        private bool _hasError;
        private bool _isLoading;
        private bool _isFormVisible = true;
        private bool _isSuccessVisible = false;

        public ForgotPasswordVM(Services.INavigationService navigationService)
        {
            _httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://your-api-url.com/api/") // Configure your API URL
            };
            _navigationService = navigationService;

            SendResetCommand = new Command(async () => await SendResetAsync(), () => CanSendReset());
            BackCommand = new Command(async () => await NavigateBackAsync());
        }

        #region Properties

        public string Username
        {
            get => _username;
            set
            {
                _username = value;
                OnPropertyChanged();
                ((Command)SendResetCommand).ChangeCanExecute();
            }
        }

        public string ErrorMessage
        {
            get => _errorMessage;
            set
            {
                _errorMessage = value;
                OnPropertyChanged();
            }
        }

        public bool HasError
        {
            get => _hasError;
            set
            {
                _hasError = value;
                OnPropertyChanged();
            }
        }

        public bool IsLoading
        {
            get => _isLoading;
            set
            {
                _isLoading = value;
                OnPropertyChanged();
            }
        }

        public bool IsFormVisible
        {
            get => _isFormVisible;
            set
            {
                _isFormVisible = value;
                OnPropertyChanged();
            }
        }

        public bool IsSuccessVisible
        {
            get => _isSuccessVisible;
            set
            {
                _isSuccessVisible = value;
                OnPropertyChanged();
            }
        }

        #endregion

        #region Commands

        public ICommand SendResetCommand { get; }
        public ICommand BackCommand { get; }

        #endregion

        #region Methods

        private bool CanSendReset()
        {
            return !string.IsNullOrWhiteSpace(Username) && !IsLoading;
        }

        private async Task SendResetAsync()
        {
            if (IsLoading) return;

            try
            {
                IsLoading = true;
                HasError = false;
                ErrorMessage = string.Empty;

                // Create reset request
                var resetRequest = new ForgotPasswordRequest
                {
                    Username = Username
                };

                // Call API
                var response = await _httpClient.PostAsJsonAsync("auth/forgot-password", resetRequest);

                if (response.IsSuccessStatusCode)
                {
                    // Show success message
                    IsFormVisible = false;
                    IsSuccessVisible = true;
                }
                else
                {
                    // Handle error response
                    if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
                    {
                        ShowError("Username not found");
                    }
                    else
                    {
                        ShowError("Failed to send reset instructions. Please try again.");
                    }
                }
            }
            catch (HttpRequestException)
            {
                ShowError("Unable to connect to server. Check your internet connection.");
            }
            catch (Exception ex)
            {
                ShowError($"An error occurred: {ex.Message}");
            }
            finally
            {
                IsLoading = false;
            }
        }

        private async Task NavigateBackAsync()
        {
            await Shell.Current.GoToAsync("..");
        }

        private void ShowError(string message)
        {
            ErrorMessage = message;
            HasError = true;
        }

        #endregion

        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
    }

    #region Models

    public class ForgotPasswordRequest
    {
        public string Username { get; set; }
    }

    #endregion
}
