using FrymasterBadgeApp.Services;
using Microsoft.Maui.Controls;

namespace FrymasterBadgeApp;

public partial class AppShell : Shell
{
    private readonly SqlService _db;
    private readonly PrinterService _printerService;

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

        _ = LoadCompaniesAsync();
    }

    private async Task LoadCompaniesAsync()
    {
        try
        {
            var companies = await Task.Run(() => _db.Query("SELECT * FROM dbo.Companies", null));

            await MainThread.InvokeOnMainThreadAsync(() =>
            {
                Items.Clear();

                if (companies == null || !companies.Any())
                {
                    CurrentItem = SetupTab;
                    return;
                }

                foreach (var company in companies)
                {
                    string companyName = company.GetValueOrDefault("Name")?.ToString() ?? "Unknown";

                    var employeePage = new EmployeePage(_db, _printerService, company)
                    {
                        Title = companyName,
                    };

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

                    var tab = new Tab { Title = companyName };
                    tab.Items.Add(new ShellContent { Content = employeePage });

                    MainTabBar.Items.Add(tab);
                }

                if (MainTabBar.Items.Count > 0)
                    CurrentItem = MainTabBar.Items[0];
            });
        }
        catch (Exception ex)
        {
            await MainThread.InvokeOnMainThreadAsync(async () =>
                await DisplayAlert("Error", $"Failed to load: {ex.Message}", "OK")
            );
        }
    }
}
