using Microsoft.AspNetCore.Mvc;
using StockFin.Models;
using StockFin.ViewModels;
using System.Diagnostics;

namespace StockFin.Controllers
{
    public class HomeController : Controller
    {
        FinancesContext db = new FinancesContext();
        private readonly AlphaVantageService _alpha;
        private readonly IFinnhubClient _finnhub;
        private readonly ITwelveDataClient _twelveData;
        private readonly StocksCache _cache;

        public HomeController(AlphaVantageService alpha, IFinnhubClient finnhub, ITwelveDataClient twelveData, StocksCache cache)
        {
            _alpha = alpha;
            _finnhub = finnhub;
            _twelveData = twelveData;
            _cache = cache;
        }
        public async Task<IActionResult> Index()
        {
            var accountTypes = db.AccountTypes.ToList();

            try
            {
                //await _alpha.GetQuoteAsync("IE00B4K48X80", "IMAE.AMS");
                //var results =
    //await _twelveData.SearchAsync("IE00B44Z5B48");

                //var quote =
                //    await _twelveData.GetQuoteAsync("SPYY");

                //var price =
                    //await _twelveData.GetPriceAsync("AAPL");
            }
            catch (Exception ex)
            {
                // AlphaVantage unavailable — continue loading the page
                _ = ex;
            }

            await _finnhub.GetQuoteAsync("SPY");
            var accounts = db.Accounts.ToList();
            List<AccountState> accountStates = new List<AccountState>();
            foreach (var account in accounts)
            {
                switch(account.TypeId)
                {
                    case 1:
                    case 2:
                    case 4:
                        accountStates.Add(AccountState.FromAccount(account.Id));
                        break;
                    case 5:
                    case 3:
                        accountStates.Add(await AccountState.FromStocks(account.Id, _cache));
                        break;
                    case 6:
                        accountStates.Add(AccountState.FromPatrimony(account.Id));
                        break;
                    default:
                        break;
                };
               
            }

            var colorPalette = new[]
            {
                "#2563eb",
                "#0f766e",
                "#7c3aed",
                "#ea580c",
                "#db2777",
                "#ca8a04",
                "#1d4ed8",
                "#0891b2"
            };

            var totalActualValue = accountStates.Sum(a => a.ActualValue);
            var totalStartValue = accountStates.Sum(a => a.StartValue);

            var typeSummaries = accountTypes
                .Select((type, index) =>
                {
                    var typeAccounts = accountStates
                        .Where(a => a.TypeId == type.Id)
                        .OrderByDescending(a => a.ActualValue)
                        .ToList();

                    var actualValue = typeAccounts.Sum(a => a.ActualValue);
                    var startValue = typeAccounts.Sum(a => a.StartValue);

                    return new HomeAccountTypeSummaryViewModel
                    {
                        TypeId = type.Id,
                        TypeTitle = type.Title ?? "Sans type",
                        Color = colorPalette[index % colorPalette.Length],
                        ActualValue = actualValue,
                        StartValue = startValue,
                        Percentage = totalActualValue > 0 ? (actualValue / totalActualValue) * 100 : 0,
                        StartPercentage = totalStartValue > 0 ? (startValue / totalStartValue) * 100 : 0,
                        Accounts = typeAccounts
                    };
                })
                .Where(summary => summary.Accounts.Count > 0)
                .OrderByDescending(summary => summary.ActualValue)
                .ToList();

            var model = new HomeDashboardViewModel
            {
                TypeSummaries = typeSummaries,
                TotalActualValue = totalActualValue,
                TotalStartValue = totalStartValue,
                AccountCount = accountStates.Count
            };

            return View(model);
        
        }  

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View();//new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
