using Domain.Entities;
using Domain.Generics;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text;
using Microsoft.JSInterop;
using System.Reflection;

namespace phronCare.UIBlazor.Services.Sales
{
    public class InstitutionService
    {
        private readonly HttpClient _http;
        private readonly IJSRuntime _js;

        public InstitutionService(HttpClient http, IJSRuntime js)
        {
            _http = http;
            _js = js;
        }

        // Obtener todas las instituciones
        public async Task<List<EInstitution>> GetAllAsync()
        {
            var result = await _http.GetFromJsonAsync<List<EInstitution>>("/api/Institution/all");
            return result ?? new List<EInstitution>();
        }

        // Obtener institución por ID
        public async Task<EInstitution> GetByIdAsync(int id)
        {
            var result = await _http.GetFromJsonAsync<EInstitution>($"/api/Institution/{id}");
            return result ?? new EInstitution();
        }

        // Crear una nueva institución
        public async Task<HttpResponseMessage> CreateAsync(EInstitution institution)
        {
            return await _http.PostAsJsonAsync("/api/Institution/create", institution);
        }

        // Actualizar una institución existente
        public async Task<HttpResponseMessage> UpdateAsync(EInstitution institution)
        {
            return await _http.PutAsJsonAsync("/api/Institution/update", institution);
        }

        // Buscar instituciones con parámetros de búsqueda (paginación)
        public async Task<PagedResult<EInstitution>?> SearchInstitutionsAsync(InstitutionSearchParams searchParams)
        {
            var url = $"api/Institution/search?" +
                      $"name={searchParams.Name}&" +
                      $"type={searchParams.Type}&" +
                      $"province={searchParams.Province}&" +
                      $"page={searchParams.Page}&" +
                      $"pageSize={searchParams.PageSize}";
            return await _http.GetFromJsonAsync<PagedResult<EInstitution>>(url);
        }

        // Exportar instituciones filtradas
        public async Task ExportFilteredAsync(InstitutionSearchParams searchParams)
        {
            try
            {
                var content = new StringContent(JsonSerializer.Serialize(searchParams), Encoding.UTF8, "application/json");
                var response = await _http.PostAsync("api/Institution/exportfiltered", content);

                if (!response.IsSuccessStatusCode)
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    throw new Exception(errorContent);
                }

                var bytes = await response.Content.ReadAsByteArrayAsync();
                var base64 = Convert.ToBase64String(bytes);
                var timestamp = DateTime.Now.ToString("yyyyMMddHHmm");
                var fileName = $"{timestamp}_instituciones.xlsx";
                await _js.InvokeVoidAsync("saveAsFile", fileName, base64);
            }
            catch (Exception ex)
            {
                var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
                var message = ex.Message ?? "No message provided";
                throw new Exception($"{message}", ex);
            }
        }
    }
}
