using Core.Dtos;
using Domain.Entities;
using Domain.Generics;
using Microsoft.AspNetCore.Mvc;
using Models.Interfaces;
using System.Reflection;

namespace phronCare.API.Controllers.Sales
{
    [Route("api/[controller]")]
    [ApiController]
    public class QuoteController : ControllerBase
    {
        private readonly IQuoteDom _quoteService;
        public QuoteController(IQuoteDom quoteService)
        {
            _quoteService = quoteService ?? throw new ArgumentNullException(nameof(quoteService));
        }

        #region Obtener Presupuestos
        /// <summary>
        /// Busca presupuestos con filtros de texto libre o por ID, paginados.
        /// </summary>
        [HttpGet("search")]
        public async Task<ActionResult<PagedResult<QuoteDto>>> Search(
            [FromQuery] int? customerId,
            [FromQuery] string? customerText,
            [FromQuery] string? quoteNumber,
            [FromQuery] int? professionalId,
            [FromQuery] string? professionalText,
            [FromQuery] int? institutionId,
            [FromQuery] string? institutionText,
            [FromQuery] int? patientId,
            [FromQuery] string? patientText,
            [FromQuery] DateTime? issueDateFrom,
            [FromQuery] DateTime? issueDateTo,
            [FromQuery] string? status,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 50)
        {
            try
            {
                var result = await _quoteService.SearchAsync(
                    customerId,
                    customerText,
                    quoteNumber,
                    professionalId,
                    professionalText,
                    institutionId,
                    institutionText,
                    patientId,
                    patientText,
                    issueDateFrom,
                    issueDateTo,
                    status,
                    page,
                    pageSize);

                return Ok(result);
            }
            catch (Exception ex)
            {
                var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
                // Log exception as needed...
                return StatusCode(500, $"{methodName} Message: {ex.Message}");
            }
        }
        #endregion

        //[HttpGet("all")]
        //public async Task<IActionResult> GetAll([FromQuery] int page = 1, [FromQuery] int pageSize = 50)
        //{
        //    try
        //    {
        //        var result = await _quoteService.GetAllQuotesAsync(page, pageSize);
        //        return Ok(result);
        //    }
        //    catch (Exception ex)
        //    {
        //        var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
        //        return StatusCode(500, $"{methodName} Message: {ex.Message}");
        //    }
        //}

        //[HttpGet("search")]
        //public async Task<IActionResult> Search(
        //    [FromQuery] int? customerId,
        //    [FromQuery] string? customerText,
        //    [FromQuery] string? quoteNumber,
        //    [FromQuery] int? professionalId,
        //    [FromQuery] string? professionalText,
        //    [FromQuery] int? institutionId,
        //    [FromQuery] string? institutionText,
        //    [FromQuery] int? patientId,
        //    [FromQuery] string? patientText,
        //    [FromQuery] DateTime? issueDateFrom,
        //    [FromQuery] DateTime? issueDateTo,
        //    [FromQuery] string? status,
        //    [FromQuery] int page = 1,
        //    [FromQuery] int pageSize = 50)
        //{
        //    try
        //    {
        //        var result = await _quoteService.SearchAsync(
        //            customerId,
        //            customerText,
        //            quoteNumber,
        //            professionalId,
        //            professionalText,
        //            institutionId,
        //            institutionText,
        //            patientId,
        //            patientText,
        //            issueDateFrom,
        //            issueDateTo,
        //            status,
        //            page,
        //            pageSize);

        //        return Ok(result);
        //    }
        //    catch (Exception ex)
        //    {
        //        var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
        //        return StatusCode(500, $"{methodName} Message: {ex.Message}");
        //    }
        //}

        //[HttpGet("{id:int}")]
        //public async Task<ActionResult<EQuoteHeader>> GetById(int id)
        //{
        //    try
        //    {
        //        var quote = await _quoteService.GetQuoteByIdAsync(id);
        //        if (quote == null)
        //            return NotFound();

        //        return Ok(quote);
        //    }
        //    catch (Exception ex)
        //    {
        //        var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
        //        return StatusCode(500, $"{methodName} Message: {ex.Message}");
        //    }
        //}

        //#endregion

        //#region Crear / Actualizar / Eliminar

        //[HttpPut("update")]
        //public async Task<IActionResult> Update([FromBody] EQuoteHeader quote)
        //{
        //    try
        //    {
        //        if (quote == null || quote.Id <= 0)
        //            return BadRequest("El presupuesto es inválido o no tiene un ID válido.");

        //        await _quoteService.UpdateQuoteAsync(quote);
        //        return Ok("Presupuesto actualizado correctamente.");
        //    }
        //    catch (Exception ex)
        //    {
        //        var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
        //        return StatusCode(500, $"{methodName} Message: {ex.Message}");
        //    }
        //}

        //[HttpDelete("delete/{id:int}")]
        //public async Task<IActionResult> Delete(int id)
        //{
        //    try
        //    {
        //        await _quoteService.DeleteQuoteAsync(id);
        //        return Ok("Presupuesto eliminado correctamente.");
        //    }
        //    catch (Exception ex)
        //    {
        //        var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
        //        return StatusCode(500, $"{methodName} Message: {ex.Message}");
        //    }
        //}


        //#region Exportación

        //[HttpPost("exportfiltered")]
        //public async Task<IActionResult> ExportFiltered([FromBody] QuoteSearchParams searchParams)
        //{
        //    try
        //    {
        //        var file = await _quoteService.ExportFilteredQuotesToExcelAsync(searchParams);
        //        return File(file,
        //            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        //            "Presupuestos.xlsx");
        //    }
        //    catch (Exception ex)
        //    {
        //        return BadRequest(ex.Message);
        //    }
        //}

        //#endregion

        #region Endpoint de emision de presupuesto (encabezado + detalles + roles + ajustes + impuestos)
        [HttpPost("createfull")]
        public async Task<IActionResult> CreateFullQuote([FromBody] CreateFullQuoteRequest request)
        {
            try
            {
                // Validamos que el request y el objeto Quote no sean nulos
                if (request == null || request.Quote == null)
                    return BadRequest("El payload no puede contener elementos nulos.");

                // Desempaquetamos los datos
                var quote = request.Quote;
                var formSeriesId = request.FormSeriesId;

                // Llamada al servicio de negocio
                var quoteNumber = await _quoteService.CreateFullQuoteAsync(quote, formSeriesId);

                // Devolvemos el número generado
                return Ok(new { Success = true, QuoteNumber = quoteNumber });
            }
            catch (ArgumentNullException ex)
            {
                return BadRequest($"Validación fallida: {ex.Message}");
            }
            catch (InvalidOperationException ex)
            {
                return BadRequest($"Error de negocio: {ex.Message}");
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Ocurrió un error interno: {ex.Message}");
            }
        }

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

        #endregion
    }
}