using Core.Dtos;
using Domain.Entities;
using Domain.Generics;
using System.Net.Http.Json;

namespace phronCare.UIBlazor.Services.Sales.Quotes
{
    public class QuoteService
    {
        private readonly HttpClient _http;
        public QuoteService(HttpClient http)
        {
            _http = http;
        }

        /// <summary>
        /// Envía el EQuoteHeader junto con el formSeriesId al backend
        /// y recibe el número de presupuesto generado o un error.
        /// </summary>
        public async Task<CreateQuoteResult> CreateFullQuoteAsync(EQuoteHeader quote, int formSeriesId)
        {
            var request = new CreateFullQuoteRequest
            {
                Quote = quote,
                FormSeriesId = formSeriesId
            };

            var response = await _http.PostAsJsonAsync("/api/quote/createfull", request);

            if (!response.IsSuccessStatusCode)
            {
                var serverMessage = await response.Content.ReadAsStringAsync();
                return new CreateQuoteResult
                {
                    Success = false,
                    ErrorMessage = serverMessage
                };
            }

            var result = await response.Content.ReadFromJsonAsync<CreateQuoteResult>();
            return result!;
        }

        /// <summary>
        /// Busca presupuestos con filtros y paginación.
        /// </summary>
        public async Task<PagedResult<QuoteDto>> SearchAsync(
            int? customerId = null,
            string? customerText = null,
            string? quoteNumber = null,
            int? professionalId = null,
            string? professionalText = null,
            int? institutionId = null,
            string? institutionText = null,
            int? patientId = null,
            string? patientText = null,
            string? status = null,
            DateTime? issueDateFrom = null,
            DateTime? issueDateTo = null,
            int page = 1,
            int pageSize = 10)
        {
            // Construir manualmente la query string
            var queryParams = new List<string>();

            void AddParam(string key, string? value)
            {
                if (!string.IsNullOrWhiteSpace(value))
                    queryParams.Add($"{key}={Uri.EscapeDataString(value!)}");
            }

            AddParam("customerId", customerId?.ToString());
            AddParam("customerText", customerText);
            AddParam("quoteNumber", quoteNumber);
            AddParam("professionalId", professionalId?.ToString());
            AddParam("professionalText", professionalText);
            AddParam("institutionId", institutionId?.ToString());
            AddParam("institutionText", institutionText);
            AddParam("patientId", patientId?.ToString());
            AddParam("patientText", patientText);
            AddParam("status", status);
            AddParam("issueDateFrom", issueDateFrom?.ToString("o"));
            AddParam("issueDateTo", issueDateTo?.ToString("o"));
            AddParam("page", page.ToString());
            AddParam("pageSize", pageSize.ToString());

            var url = "/api/quote/search";
            if (queryParams.Any())
                url += "?" + string.Join("&", queryParams);

            // Llamada al endpoint
            var result = await _http.GetFromJsonAsync<PagedResult<QuoteDto>>(url);
            return result!;
        }
    }

    public class CreateQuoteResult
    {
        public bool Success { get; set; }
        public string QuoteNumber { get; set; } = string.Empty;
        public string ErrorMessage { get; set; } = string.Empty;
    }

    public class CreateFullQuoteRequest
    {
        public EQuoteHeader Quote { get; set; } = default!;
        public int FormSeriesId { get; set; }
    }
}
