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


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

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

        public async Task<List<EPatient>> GetAllAsync()
        {
            var result = await _http.GetFromJsonAsync<List<EPatient>>("/api/Patient/all");
            return result ?? new List<EPatient>();
        }

        public async Task<EPatient> GetByIdAsync(int id)
        {
            var result = await _http.GetFromJsonAsync<EPatient>($"/api/Patient/{id}");
            return result ?? new EPatient();
        }

        public async Task<HttpResponseMessage> CreateAsync(EPatient patient)
        {
            return await _http.PostAsJsonAsync("/api/Patient/create", patient);
        }

        public async Task<HttpResponseMessage> UpdateAsync(EPatient patient)
        {
            return await _http.PutAsJsonAsync("/api/Patient/update", patient);
        }

        public async Task<PagedResult<EPatient>?> SearchPatientsAsync(PatientSearchParams searchParams)
        {
            var url = $"api/Patient/search?" +
                      $"name={searchParams.Name}&" +
                      $"document={searchParams.Document}&" +
                      $"page={searchParams.Page}&" +
                      $"pageSize={searchParams.PageSize}";
            return await _http.GetFromJsonAsync<PagedResult<EPatient>>(url);
        }

        public async Task ExportFilteredAsync(PatientSearchParams searchParams)
        {
            try
            {
                var content = new StringContent(JsonSerializer.Serialize(searchParams), Encoding.UTF8, "application/json");
                var response = await _http.PostAsync("api/Patient/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}_pacientes.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);
            }
        }
    }
}
