using Launcher.Models;
using Launcher.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Launcher
{
    public partial class LoginView : Window
    {
        private readonly AuthenticationService _authenticationService;

        public LoginView()
        {
            InitializeComponent();
            _authenticationService = new AuthenticationService();
            LoadUserCredentials();
            this.Closing += LoginView_Closing;
        }

        private void LoginView_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // Закрываем приложение только если пользователь не вошел в систему
            if (!IsSuccessfulLogin)
            {
                Application.Current.Shutdown();
            }
        }

        private void LoadUserCredentials()
        {
            var savedUser = UserModel.LoadCredentials();
            if (savedUser.RememberMe)
            {
                usernameTextBox.Text = savedUser.Username;
                passwordBox.Password = savedUser.Password;
                rememberMeCheckBox.IsChecked = savedUser.RememberMe;
                autoLoginCheckBox.IsChecked = savedUser.AutoLogin;

                if (savedUser.AutoLogin && !UserModel.HasLoggedOut)
                {
                    AttemptLogin(savedUser);
                }
            }
        }

        private void Login_Click(object sender, RoutedEventArgs e)
        {
            var user = new UserModel
            {
                Username = usernameTextBox.Text,
                Password = passwordBox.Password,
                RememberMe = rememberMeCheckBox.IsChecked ?? false,
                AutoLogin = autoLoginCheckBox.IsChecked ?? false
            };

            AttemptLogin(user);
        }

        public bool IsSuccessfulLogin { get; private set; } = false;

        private async void AttemptLogin(UserModel user)
        {
            var isSuccess = await _authenticationService.LoginAsync(user);
            if (isSuccess)
            {
                IsSuccessfulLogin = true; // Убедитесь, что флаг устанавливается здесь
                user.SaveCredentials();

                // Показываем MainWindow и закрываем LoginView
                ShowMainWindow();
                this.Close();
            }
            else
            {
                MessageBox.Show("Ошибка авторизации. Проверьте введенные данные.");
            }
        }

        private void ShowMainWindow()
        {
            var mainWindow = Application.Current.MainWindow as MainWindow;
            if (mainWindow == null)
            {
                mainWindow = new MainWindow();
                Application.Current.MainWindow = mainWindow;
            }

            mainWindow.Show();
        }

    }
}