using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.WebUtilities;
using System.Globalization;
using economy.Helpers;
using economy.Models;
using economy.Models.Price.Domestic;
using economy.Models.Price.Domestic.Oil;

namespace economy.Controllers.Price.Domestic
{
    public class OilController : Controller
    {
        private readonly DataGoKR _dataGoKR;
        private Dictionary<string, string> _queryString;

        public OilController(DataGoKR dataGoKR)
        {
            _dataGoKR = dataGoKR;
            _queryString = [];
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            _queryString = QueryHelpers.ParseQuery(HttpContext.Request.QueryString.Value).ToDictionary(k => k.Key, v => string.Join(",", v.Value));

            ViewBag.QueryString = _queryString;

            base.OnActionExecuting(context);
        }

        [HttpGet("Price/Domestic/Oil")]
        public async Task<IActionResult> Index(Request request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            DomesticModel domesticModel = new DomesticModel(_dataGoKR, null);
            Response itemList = await domesticModel.GetOilPriceInfo(request);

            if (itemList.Body is not null)
            {
                int listNum = Common.CalcListNumber(itemList.Body.TotalCount, request.PageNo, request.NumOfRows);
                itemList.Body.Items.ItemList = itemList.Body.Items.ItemList.Select((row, index) =>
                {
                    row.Num = listNum - index;
                    row.OilCtg = Common.NumberFormat(row.OilCtg);
                    row.WtAvgPrcCptn = Common.NumberFormat(row.WtAvgPrcCptn, "0.##");
                    row.WtAvgPrcDisc = Common.NumberFormat(row.WtAvgPrcDisc);
                    row.Trqu = Common.NumberFormat(row.Trqu);
                    row.TrPrc = Common.NumberFormat(row.TrPrc);
                    return row;
                }).ToList();
            }
            else
            {
                ViewBag.isError = true;
                ViewBag.errorMessage = "시세 정보를 가져오지 못했습니다. (외부 API 오류)";
            }

            // 차트용 데이터 조회 (같은 검색조건, 최대 300행)
            ChartData? chart = null;

            var chartRequest = new Request
            {
                PageNo = 1,
                NumOfRows = 300,
                StartDate = request.StartDate,
                EndDate = request.EndDate
            };
            Response chartList = await domesticModel.GetOilPriceInfo(chartRequest);

            if (chartList.Body?.Items?.ItemList is not null)
            {
                var rows = chartList.Body.Items.ItemList;
                var labels = rows.Select(r => r.BasDt).Distinct().OrderBy(d => d).ToList();

                chart = new ChartData
                {
                    Labels = labels.Select(d => Common.StringToDateFormat(d)).ToList(),
                    Series = rows.GroupBy(r => r.OilCtg).Select(g => new ChartSeries
                    {
                        Name = g.Key,
                        Values = labels.Select(d =>
                        {
                            var row = g.FirstOrDefault(r => r.BasDt == d);
                            return (row is not null && decimal.TryParse(row.WtAvgPrcCptn, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal value)) ? value : (decimal?)null;
                        }).ToList()
                    }).ToList()
                };
            }

            var viewModel = new View<Request, Response>();
            viewModel.SelectedListPerPage = request.NumOfRows;
            viewModel.Request = request;
            viewModel.Response = itemList;
            viewModel.Chart = chart;

            var queryString = new
            {
                sDate = request.StartDate.ToString("yyyy-MM-dd"),
                eDate = request.EndDate.ToString("yyyy-MM-dd")
            };

            var pagination = new Pagination(itemList.Body?.TotalCount, request.PageNo, request.NumOfRows, queryString);
            viewModel.Pagination = pagination;

            return View("/Views/Price/Domestic/Oil.cshtml", viewModel);
        }
    }
}
