using LSFE.MobApp.Services;
using System.Diagnostics;

namespace LSFE.MobApp
{
    public partial class App : Application
    {
        private readonly Services.INavigationService _navigationService;

        public App(IDatabaseService databaseService, INavigationService navigationService)
        {
            InitializeComponent();
            _navigationService = navigationService;

            // Initialize database in background
            Task.Run(async () => await databaseService.InitializeAsync());

            // Setup exception handlers
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                var exception = e.ExceptionObject as Exception;
                var message = $"Unhandled exception: {exception?.GetType().Name}\n" +
                             $"Message: {exception?.Message}\n" +
                             $"Stack: {exception?.StackTrace}";
                Debug.WriteLine(message);
                LogToFile(message);
            };

            TaskScheduler.UnobservedTaskException += (s, e) =>
            {
                var message = $"Unobserved task exception: {e.Exception?.GetType().Name}\n" +
                             $"Message: {e.Exception?.Message}\n" +
                             $"Stack: {e.Exception?.StackTrace}\n" +
                             $"Inner: {e.Exception?.InnerException?.Message}";
                Debug.WriteLine(message);
                LogToFile(message);
                e.SetObserved();
            };

            // Create and set MainPage
            MainPage = new AppShell(_navigationService);
        }

        protected override Window CreateWindow(IActivationState? activationState)
        {
            var window = base.CreateWindow(activationState);

            // Perform authentication check after window is created
            window.Created += async (s, e) =>
            {
                await CheckAuthenticationAsync();
            };

            return window;
        }

        private async Task CheckAuthenticationAsync()
        {
            try
            {
                // Small delay to ensure Shell is fully initialized
                await Task.Delay(50);

                var token = await SecureStorage.GetAsync("auth_token");

                if (string.IsNullOrEmpty(token) || token == "N/A")
                {
                    // No valid token - navigate to login page
                    await MainThread.InvokeOnMainThreadAsync(async () =>
                    {
                        await Shell.Current.GoToAsync("//LoginPage");
                    });
                }
                else
                {
                    // Has valid token - navigate to main tabs
                    await MainThread.InvokeOnMainThreadAsync(async () =>
                    {
                        await Shell.Current.GoToAsync("//MainTabs");
                    });
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Auth check error: {ex.Message}");
                // On error, default to login page
                await MainThread.InvokeOnMainThreadAsync(async () =>
                {
                    try
                    {
                        await Shell.Current.GoToAsync("//LoginPage");
                    }
                    catch (Exception navEx)
                    {
                        Debug.WriteLine($"Navigation error: {navEx.Message}");
                    }
                });
            }
        }

        private void LogToFile(string message)
        {
            try
            {
                var logPath = Path.Combine(FileSystem.AppDataDirectory, "crash_log.txt");
                var logMessage = $"\n{new string('=', 60)}\n{DateTime.Now:yyyy-MM-dd HH:mm:ss}\n{message}\n";
                File.AppendAllText(logPath, logMessage);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Failed to log to file: {ex.Message}");
            }
        }
    }
}
/*using LSFE.MobApp.Services;
using System.Diagnostics;

namespace LSFE.MobApp
{
    public partial class App : Application
    {
        public App(IDatabaseService databaseService)
        {
            InitializeComponent();
            Task.Run(async () => await databaseService.InitializeAsync());

            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                var exception = e.ExceptionObject as Exception;
                var message = $"Unhandled exception: {exception?.GetType().Name}\n" +
                             $"Message: {exception?.Message}\n" +
                             $"Stack: {exception?.StackTrace}";

                Debug.WriteLine(message);
                LogToFile(message);
            };

            TaskScheduler.UnobservedTaskException += (s, e) =>
            {
                var message = $"Unobserved task exception: {e.Exception?.GetType().Name}\n" +
                             $"Message: {e.Exception?.Message}\n" +
                             $"Stack: {e.Exception?.StackTrace}\n" +
                             $"Inner: {e.Exception?.InnerException?.Message}";

                Debug.WriteLine(message);
                LogToFile(message);
                e.SetObserved();
            };
        }

        private void LogToFile(string message)
        {
            try
            {
                var logPath = Path.Combine(FileSystem.AppDataDirectory, "crash_log.txt");
                var logMessage = $"\n{'=' * 60}\n{DateTime.Now:yyyy-MM-dd HH:mm:ss}\n{message}\n";
                File.AppendAllText(logPath, logMessage);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Failed to log to file: {ex.Message}");
            }
        }

        protected override Window CreateWindow(IActivationState? activationState)
        {
            return new Window(new AppShell());
        }
    }
}*/