using System.Diagnostics;
using FrymasterBadgeApp.Services;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.PlatformConfiguration.WindowsSpecific;

namespace FrymasterBadgeApp;

public partial class App : Microsoft.Maui.Controls.Application
{
    private readonly SqlService _db;
    private readonly PrinterService _printerService;
    private Microsoft.Maui.Controls.TabbedPage _rootTabbedPage;

    public App(SqlService db, PrinterService printerService)
    {
        InitializeComponent();
        _db = db;
        _printerService = printerService;

        Debug.WriteLine("=== APP STARTUP ===");

        _rootTabbedPage = new Microsoft.Maui.Controls.TabbedPage
        {
            Title = "Frymaster Badge System",
            BarBackgroundColor = Colors.SlateGray,
            BarTextColor = Colors.White,
        };

        _rootTabbedPage
            .On<Microsoft.Maui.Controls.PlatformConfiguration.Windows>()
            .SetHeaderIconsEnabled(false);

        var loadingPage = new Microsoft.Maui.Controls.ContentPage
        {
            Title = "Loading",
            BackgroundColor = Colors.DarkSlateBlue,
            Content = new StackLayout
            {
                VerticalOptions = LayoutOptions.Center,
                HorizontalOptions = LayoutOptions.Center,
                Children =
                {
                    new ActivityIndicator
                    {
                        IsRunning = true,
                        Color = Colors.White,
                        Scale = 2,
                    },
                    new Microsoft.Maui.Controls.Label
                    {
                        Text = "Loading companies...",
                        TextColor = Colors.White,
                        FontSize = 18,
                    },
                },
            },
        };

        _rootTabbedPage.Children.Add(loadingPage);
        MainPage = _rootTabbedPage;

        Debug.WriteLine("App: Resources loaded, loading page added, TabbedPage set as MainPage");
    }

    protected override async void OnStart()
    {
        base.OnStart();
        Debug.WriteLine("App: OnStart - calling LoadTabsAsync");
        await LoadTabsAsync();
    }

    private async Task LoadTabsAsync()
    {
        Debug.WriteLine("LoadTabsAsync: ENTERED");

        try
        {
            Debug.WriteLine("LoadTabsAsync: Querying database for companies...");
            var companies = await Task.Run(() => _db.Query("SELECT * FROM dbo.Companies", null));

            Debug.WriteLine($"LoadTabsAsync: Query returned {companies?.Count ?? 0} companies");

            await MainThread.InvokeOnMainThreadAsync(async () =>
            {
                Debug.WriteLine("LoadTabsAsync: On main thread - delay");
                await Task.Delay(200);

                Debug.WriteLine(
                    $"LoadTabsAsync: Current children count before clear: {_rootTabbedPage.Children.Count}"
                );
                _rootTabbedPage.Children.Clear();
                Debug.WriteLine("LoadTabsAsync: Children cleared");

                if (companies == null || !companies.Any())
                {
                    Debug.WriteLine("LoadTabsAsync: No companies - adding setup page");

                    var setupPage = new Microsoft.Maui.Controls.ContentPage
                    {
                        Title = "Setup",
                        BackgroundColor = Colors.Purple,
                        Content = new StackLayout
                        {
                            VerticalOptions = LayoutOptions.Center,
                            HorizontalOptions = LayoutOptions.Center,
                            Children =
                            {
                                new Microsoft.Maui.Controls.Label
                                {
                                    Text = "No companies found - click to manage",
                                    TextColor = Colors.White,
                                    FontSize = 24,
                                },
                                new Microsoft.Maui.Controls.Button
                                {
                                    Text = "Manage Companies",
                                    Command = new Command(async () =>
                                        await Microsoft.Maui.Controls.Application.Current.MainPage.Navigation.PushAsync(
                                            new CompanyPage(_db)
                                        )
                                    ),
                                },
                            },
                        },
                    };

                    _rootTabbedPage.Children.Add(setupPage);
                    Debug.WriteLine("LoadTabsAsync: Setup page added");
                    return;
                }

                Debug.WriteLine($"LoadTabsAsync: Adding {companies.Count} real tabs");

                int added = 0;
                foreach (var company in companies)
                {
                    string companyName = company.GetValueOrDefault("Name")?.ToString() ?? "Unknown";
                    Debug.WriteLine($"LoadTabsAsync: Processing company '{companyName}'");

                    var employeePage = new EmployeePage(_db, _printerService, company);
                    employeePage.Title = companyName;
                    employeePage.BackgroundColor = Colors.LightBlue; // Temporary for visibility

                    employeePage.ToolbarItems.Add(
                        new ToolbarItem
                        {
                            Text = "Manage",
                            Command = new Command(async () =>
                                await employeePage.Navigation.PushAsync(new CompanyPage(_db))
                            ),
                        }
                    );

                    _rootTabbedPage.Children.Add(employeePage);
                    added++;
                    Debug.WriteLine(
                        $"LoadTabsAsync: Added tab '{companyName}' ({added}/{companies.Count})"
                    );
                }

                Debug.WriteLine($"LoadTabsAsync: Finished - {added} tabs added");
            });
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"LoadTabsAsync: EXCEPTION - {ex.Message}");
            Debug.WriteLine(ex.StackTrace);
        }
    }

    protected override Window CreateWindow(IActivationState? activationState)
    {
        Debug.WriteLine("CreateWindow called");
        return new Window(MainPage!);
    }
}
