using FilterCair.Shared.Models;
using FilterCair.Client.Services.Local;
using System.Net.Http.Json;
using Microsoft.JSInterop;

namespace FilterCair.Client.Services.API
{
    public class CustomerService
    {
        private readonly HttpClient _http;
        private readonly IConfiguration _config;
        private readonly CustomerLocalService _local;
        private readonly IJSRuntime _js;
        private string BaseUrl => _config["Api:BaseUrl"] + "/api/Customer";

        public CustomerService(
            HttpClient http,
            IConfiguration config,
            CustomerLocalService local,
            IJSRuntime js)
        {
            _http = http;
            _config = config;
            _local = local;
            _js = js;
        }

        // Online-Status prüfen
        private async Task<bool> IsOnlineAsync()
        {
            try
            {
                return await _js.InvokeAsync<bool>("navigator.onLine");
            }
            catch
            {
                return true; // Fallback: versuchen online
            }
        }

        public async Task<List<CustomerModel>> GetCustomersAsync()
        {
            bool isOnline = await IsOnlineAsync();

            Console.WriteLine($"[CustomerService] Online: {isOnline}");

            if (!isOnline)
            {
                Console.WriteLine("Offline → lade aus IndexedDB");
                var local = await _local.GetAllAsync();
                Console.WriteLine($"IndexedDB liefert: {local?.Count ?? 0} Kunden");
                return local ?? new();
            }

            try
            {
                var result = await _http.GetFromJsonAsync<List<CustomerModel>>(BaseUrl);
                Console.WriteLine($"API liefert: {result?.Count ?? 0} Kunden");

                if (result != null && result.Count > 0)
                {
                    await _local.SaveAllAsync(result);
                }
                return result ?? new();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"API-Fehler: {ex.Message}");
                Console.WriteLine("Fallback auf IndexedDB");
                var fallback = await _local.GetAllAsync();
                Console.WriteLine($"Fallback liefert: {fallback?.Count ?? 0} Kunden");
                return fallback ?? new();
            }
        }

        public async Task<bool> AddCustomerAsync(CustomerModel customer)
        {
            bool isOnline = await IsOnlineAsync();

            if (isOnline)
            {
                try
                {
                    var response = await _http.PostAsJsonAsync(BaseUrl, customer);
                    if (response.IsSuccessStatusCode)
                    {
                        await _local.AddOrUpdateAsync(customer);
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Add online fehlgeschlagen: {ex.Message}");
                }
            }

            // Offline: nur lokal speichern
            Console.WriteLine("Offline – Kunde nur lokal gespeichert");
            await _local.AddOrUpdateAsync(customer);
            return true; // "Erfolg" im Offline-Modus
        }

        public async Task<bool> UpdateCustomerAsync(CustomerModel customer)
        {
            bool isOnline = await IsOnlineAsync();

            if (isOnline)
            {
                try
                {
                    var response = await _http.PutAsJsonAsync($"{BaseUrl}/{customer.Id}", customer);
                    if (response.IsSuccessStatusCode)
                    {
                        await _local.AddOrUpdateAsync(customer);
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Update online fehlgeschlagen: {ex.Message}");
                }
            }

            Console.WriteLine("Offline – Update nur lokal");
            await _local.AddOrUpdateAsync(customer);
            return true;
        }

        public async Task<bool> DeleteCustomerAsync(int id)
        {
            bool isOnline = await IsOnlineAsync();

            if (isOnline)
            {
                try
                {
                    var response = await _http.DeleteAsync($"{BaseUrl}/{id}");
                    if (response.IsSuccessStatusCode)
                    {
                        await _local.DeleteAsync(id);
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Delete online fehlgeschlagen: {ex.Message}");
                }
            }

            Console.WriteLine("Offline – Delete nur lokal");
            await _local.DeleteAsync(id);
            return true;
        }
    }
}