using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using StockFin.Models;
using System.Linq;
using System.Threading.Tasks;
using YahooFinanceApi;

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

        public StocksController(AlphaVantageService alpha, IFinnhubClient finnhub, ITwelveDataClient twelveData, StocksCache cache)
        {
            _alpha = alpha;
            _finnhub = finnhub;
            _twelveData = twelveData;
            _cache = cache;
        }
        //public StocksController(FinancesContext context)
        //{
        //    _context = context;
        //}

        // GET: Stocks
        public async Task<IActionResult> Index()
        {
            var stocks = await _context.Stocks
                .OrderBy(s => s.Title)
                .ToListAsync();


            ViewData["actuals"] = _cache.actuals;
            return View(stocks);
        }

        // GET: Stocks/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Stocks/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Title,Isin,Ticker,Cost,TypeId")] Stock stock)
        {
            if (ModelState.IsValid)
            {
                _context.Add(stock);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }

            return View(stock);
        }

        // GET: Stocks/Edit/5
        public async Task<IActionResult> Edit(long? id)
        {
            if (id == null) return NotFound();

            var stock = await _context.Stocks.FindAsync(id.Value);
            if (stock == null) return NotFound();

            return View(stock);
        }

        // POST: Stocks/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(long id, [Bind("Id,Title,Isin,Ticker,Cost,TypeId")] Stock stock)
        {
            if (id != stock.Id) return NotFound();

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(stock);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!StockExists(stock.Id)) return NotFound();
                    else throw;
                }

                return RedirectToAction(nameof(Index));
            }

            return View(stock);
        }

        // GET: Stocks/Delete/5
        public async Task<IActionResult> Delete(long? id)
        {
            if (id == null) return NotFound();

            var stock = await _context.Stocks
                .FirstOrDefaultAsync(s => s.Id == id.Value);

            if (stock == null) return NotFound();

            return View(stock);
        }

        // POST: Stocks/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(long id)
        {
            var stock = await _context.Stocks.FindAsync(id);
            if (stock != null)
            {
                _context.Stocks.Remove(stock);
                await _context.SaveChangesAsync();
            }

            return RedirectToAction(nameof(Index));
        }
        // GET
        public IActionResult UpdateFromTradeRepublic()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UpdateFromTradeRepublic(IFormFile csvFile)
        {
            if (csvFile == null || csvFile.Length == 0)
            {
                ModelState.AddModelError("csvFile", "Veuillez sélectionner un fichier CSV.");
                return View();
            }

            if (!Path.GetExtension(csvFile.FileName).Equals(".csv", StringComparison.OrdinalIgnoreCase))
            {
                ModelState.AddModelError("csvFile", "Le fichier doit avoir l'extension .csv.");
                return View();
            }

            var tempPath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.csv");
            try
            {
                await using (var stream = System.IO.File.Create(tempPath))
                    await csvFile.CopyToAsync(stream);

                var importer = new TransactionCsvImporter();
                var rows = importer.Read(tempPath);

                // TODO : traiter les lignes
                // var transactions = importer.ToTransactions(rows);
                // _context.Transactions.AddRange(transactions);
                // await _context.SaveChangesAsync();

                ViewBag.ImportResult = rows.Count;
                return View();
            }
            finally
            {
                if (System.IO.File.Exists(tempPath))
                    System.IO.File.Delete(tempPath);
            }
        }
        // POST
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> UpdateFromTradeRepublic2(IFormFile csvFile)
        {
            var traderepaccountid = 18;
            List<string> notfound = new List<string>();
            var stocks = await _context.Stocks
                .OrderBy(s => s.Title)
                .ToListAsync();
            var importer = new TransactionCsvImporter();
            var rows = importer.Read("Exportation de transactions.csv");

            // Filtrer par type
            var Trade = rows.Where(r => r.Category == "TRADING");
            var total = 0;
            var found = 0;
            foreach (var row in Trade)
            {
                total = total + 1;
                var stock = stocks.FirstOrDefault(s => s.Isin == row.Symbol);
                if (stock != null)
                {

                    found = found + 1;
                    Transaction T = _context.Transactions.Where(t => t.StocksId == stock.Id && t.AccountId == traderepaccountid && t.Date == row.Date).SingleOrDefault();
                    if (T == null)
                    {
                        T = new Transaction();
                        T.Date = row.Date;
                        T.StocksId = stock.Id;
                        T.Value = row.Price;
                        T.Quantity = row.Shares;
                        T.AccountId = traderepaccountid;
                        T.TypeId = 1;
                        _context.Transactions.Add(T);
                    }


                }
                else
                {
                    if (!notfound.Contains(row.Symbol + " - " + row.Name))
                    {
                        notfound.Add(row.Symbol + " - " + row.Name);
                    }
                }
            }
            _context.SaveChanges();
            Console.WriteLine($"Total: {total}, Found: {found}");
            return View(notfound);
        }
        private bool StockExists(long id)
        {
            return _context.Stocks.Any(e => e.Id == id);
        }
    }
}
