using Elwig.Helpers;
using Elwig.Models.Entities;
using Elwig.ViewModels;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Elwig.Documents;
using Elwig.Helpers.Export;
using Elwig.Models.Dtos;
using Microsoft.Win32;
using System.Windows.Input;
using System.Windows;
using System;
using LinqKit;
using System.Windows.Controls;

namespace Elwig.Services {
    public static class DeliveryAncmtService {

        public enum ExportSubject {
            FromSelectedSchedule,
        };

        public static void InitInputs(this DeliveryAncmtAdminViewModel vm) {
            if (vm.SelectedDeliverySchedule is DeliverySchedule s)
                vm.DeliverySchedule = (DeliverySchedule?)ControlUtils.GetItemFromSourceWithPk(vm.DeliveryScheduleSource, s.Year, s.DsNr);
        }

        public static void ClearInputs(this DeliveryAncmtAdminViewModel vm) {
            vm.StatusAncmtCreated = "-";
            vm.StatusAncmtModified = "-";
        }

        public static void FillInputs(this DeliveryAncmtAdminViewModel vm, DeliveryAncmt a) {
            vm.MgNr = a.MgNr;
            vm.DeliverySchedule = (DeliverySchedule?)ControlUtils.GetItemFromSourceWithPk(vm.DeliveryScheduleSource, a.Year, a.DsNr);
            vm.SortId = a.SortId;
            vm.Weight = a.Weight;
            vm.StatusAncmtCreated = $"{a.CreatedAt:dd.MM.yyyy, HH:mm} ({a.Type})";
            vm.StatusAncmtModified = a.ModifiedAt != a.CreatedAt ? $"{a.ModifiedAt:dd.MM.yyyy, HH:mm}" : "-";
        }

        public static async Task<(List<string>, IQueryable<DeliveryAncmt>, List<string>)> GetFilters(this DeliveryAncmtAdminViewModel vm, AppDbContext ctx) {
            List<string> filterNames = [];
            IQueryable<DeliveryAncmt> deliveryAncmtQuery = ctx.DeliveryAnnouncements;
            if (vm.SelectedDeliverySchedule is DeliverySchedule s) {
                deliveryAncmtQuery = deliveryAncmtQuery.Where(a => a.Year == s.Year && a.DsNr == s.DsNr);
                filterNames.Add($"{s.Date:dd.MM.yyyy} – {s.Branch.Name} – {s.Description}");
            } else {
                deliveryAncmtQuery = deliveryAncmtQuery.Where(a => a.Year == vm.FilterSeason && (!vm.FilterOnlyUpcoming || a.Schedule.DateString.CompareTo(Utils.Today.ToString("yyyy-MM-dd")) >= 0));
                filterNames.Add($"{vm.FilterSeason}");
            }

            var filterVar = new List<string>();
            var filterNotVar = new List<string>();
            var filterMgNr = new List<int>();
            var filterZwst = new List<string>();
            var filterAttr = new List<string>();
            var filterNotAttr = new List<string>();
            var filterCult = new List<string>();
            var filterNotCult = new List<string>();
            var filterDate = new List<(string?, string?)>();
            int filterWeightGt = 0, filterWeightLt = 0;

            var filter = vm.TextFilter;
            if (filter.Count > 0) {
                var var = await ctx.WineVarieties.ToDictionaryAsync(v => v.SortId, v => v);
                var mgnr = await ctx.Members.ToDictionaryAsync(m => m.MgNr.ToString(), m => m);
                var zwst = await ctx.Branches.ToDictionaryAsync(b => b.Name.ToLower().Split(' ')[0], b => b);
                var attr = await ctx.WineAttributes.ToDictionaryAsync(a => a.Name.ToLower().Split(' ')[0], a => a);
                var cult = await ctx.WineCultivations.ToDictionaryAsync(c => c.Name.ToLower().Split(' ')[0], c => c);

                for (int i = 0; i < filter.Count; i++) {
                    var e = filter[i];
                    if (e.ToLower() is "r" or "rot") {
                        filterVar.AddRange(var.Values.Where(v => v.IsRed).Select(v => v.SortId));
                        filter.RemoveAt(i--);
                        filterNames.Add("Rotweinsorten");
                    } else if (e.ToLower() is "w" or "weiß" or "weiss") {
                        filterVar.AddRange(var.Values.Where(v => v.IsWhite).Select(v => v.SortId));
                        filter.RemoveAt(i--);
                        filterNames.Add("Weißweinsorten");
                    } else if (e.Length == 2 && var.ContainsKey(e.ToUpper())) {
                        filterVar.Add(e.ToUpper());
                        filter.RemoveAt(i--);
                        filterNames.Add(var[e.ToUpper()].Name);
                    } else if (e.Length == 3 && e[0] == '!' && var.ContainsKey(e[1..].ToUpper())) {
                        filterNotVar.Add(e[1..].ToUpper());
                        filter.RemoveAt(i--);
                        filterNames.Add("außer " + var[e[1..].ToUpper()].Name);
                    } else if (e.All(char.IsAsciiDigit) && mgnr.TryGetValue(e, out var member)) {
                        filterMgNr.Add(int.Parse(e));
                        filter.RemoveAt(i--);
                        filterNames.Add(member.AdministrativeName);
                    } else if (attr.ContainsKey(e.ToLower())) {
                        var a = attr[e.ToLower()];
                        filterAttr.Add(a.AttrId);
                        filter.RemoveAt(i--);
                        filterNames.Add($"Attribut {a.Name}");
                    } else if (e[0] == '!' && attr.ContainsKey(e[1..].ToLower())) {
                        var a = attr[e[1..].ToLower()];
                        filterNotAttr.Add(a.AttrId);
                        filter.RemoveAt(i--);
                        filterNames.Add($"ohne Attribut {a.Name}");
                    } else if (cult.ContainsKey(e.ToLower())) {
                        var c = cult[e.ToLower()];
                        filterCult.Add(c.CultId);
                        filter.RemoveAt(i--);
                        filterNames.Add($"Bewirtschaftung {c.Name}");
                    } else if (e[0] == '!' && cult.ContainsKey(e[1..].ToLower())) {
                        var c = cult[e[1..].ToLower()];
                        filterNotCult.Add(c.CultId);
                        filter.RemoveAt(i--);
                        filterNames.Add($"ohne Bewirtschaftung {c.Name}");
                    } else if (zwst.ContainsKey(e.ToLower())) {
                        var b = zwst[e.ToLower()];
                        filterZwst.Add(b.ZwstId);
                        filter.RemoveAt(i--);
                        filterNames.Add($"Zweigstelle {b.Name}");
                    } else if ((e.StartsWith('>') || e.StartsWith('<')) && e.EndsWith("kg")) {
                        if (int.TryParse(e[1..^2], out var num)) {
                            switch (e[0]) {
                                case '>': filterWeightGt = num; break;
                                case '<': filterWeightLt = num; break;
                            }
                            filter.RemoveAt(i--);
                        }
                        if (e.Length == 3) filter.RemoveAt(i--);
                    } else if (DateOnly.TryParse(e, out var date)) {
                        var str = date.ToString("yyyy-MM-dd");
                        filterDate.Add((str, str));
                        filter.RemoveAt(i--);
                        if (filterNames.Contains($"{vm.FilterSeason}") && vm.FilterSeason == date.Year)
                            filterNames.Remove($"{vm.FilterSeason}");
                        filterNames.Add(date.ToString("dd.MM.yyyy"));
                    } else if (Utils.DateFromToRegex.IsMatch(e)) {
                        var parts = e.Split("-");
                        if (parts.Length == 1) {
                            // single date
                            var dParts = parts[0].Split('.');
                            var str = $"{dParts[2]}-{dParts[1].PadLeft(2, '0')}-{dParts[0].PadLeft(2, '0')}";
                            filterDate.Add((str, str));
                            filter.RemoveAt(i--);
                            var n = string.Join('.', str.Split('-').Reverse());
                            if (dParts[2] == "") {
                                filterNames.Remove($"{vm.FilterSeason}");
                                filterNames.Add(n + $"{vm.FilterSeason}");
                            } else {
                                if ($"{vm.FilterSeason}" == dParts[2])
                                    filterNames.Remove($"{vm.FilterSeason}");
                                filterNames.Add(n);
                            }
                        } else if (parts.Length == 2) {
                            // from/to date
                            var d1Parts = parts[0].Split('.');
                            var d2Parts = parts[1].Split('.');
                            var s1 = d1Parts.Length < 2 ? null : $"{d1Parts.ElementAtOrDefault(2)}-{d1Parts[1].PadLeft(2, '0')}-{d1Parts[0].PadLeft(2, '0')}";
                            var s2 = d2Parts.Length < 2 ? null : $"{d2Parts.ElementAtOrDefault(2)}-{d2Parts[1].PadLeft(2, '0')}-{d2Parts[0].PadLeft(2, '0')}";
                            filterDate.Add((s1, s2));
                            filter.RemoveAt(i--);
                            var n1 = s1 == null ? null : string.Join('.', s1.Split('-').Reverse());
                            var n2 = s2 == null ? null : string.Join('.', s2.Split('-').Reverse());
                            if (n1 != null && n2 != null) {
                                filterNames.Add($"{n1}–{n2}");
                            } else if (n1 != null) {
                                filterNames.Add($"ab dem {n1}");
                            } else if (n2 != null) {
                                filterNames.Add($"bis zum {n2}");
                            }
                        }
                    } else if (e.Length > 2 && e.StartsWith('"') && e.EndsWith('"')) {
                        filter[i] = e[1..^1];
                    } else if (e.Length <= 2) {
                        filter.RemoveAt(i--);
                    }
                }

                if (filterWeightGt > 0) deliveryAncmtQuery = deliveryAncmtQuery.Where(a => a.Weight >= filterWeightGt);
                if (filterWeightLt > 0) deliveryAncmtQuery = deliveryAncmtQuery.Where(a => a.Weight <= filterWeightLt);
                if (filterMgNr.Count > 0) deliveryAncmtQuery = deliveryAncmtQuery.Where(a => filterMgNr.Contains(a.MgNr));
                if (filterDate.Count > 0) {
                    var pr = PredicateBuilder.New<DeliveryAncmt>(false);
                    foreach (var (d1, d2) in filterDate)
                        pr.Or(a => (d1 == null || d1.CompareTo(a.Schedule.DateString.Substring(10 - d1.Length)) <= 0) && (d2 == null || d2.CompareTo(a.Schedule.DateString.Substring(10 - d2.Length)) >= 0));
                    deliveryAncmtQuery = deliveryAncmtQuery.Where(pr);
                }
                if (filterVar.Count > 0) deliveryAncmtQuery = deliveryAncmtQuery.Where(a => filterVar.Contains(a.SortId));
                if (filterNotVar.Count > 0) deliveryAncmtQuery = deliveryAncmtQuery.Where(a => !filterNotVar.Contains(a.SortId));
                if (filterZwst.Count > 0) deliveryAncmtQuery = deliveryAncmtQuery.Where(a => filterZwst.Contains(a.Schedule.ZwstId));
                if (filterAttr.Count > 0) deliveryAncmtQuery = deliveryAncmtQuery.Where(a => a.Schedule.AttrId != null && filterAttr.Contains(a.Schedule.AttrId));
                if (filterNotAttr.Count > 0) deliveryAncmtQuery = deliveryAncmtQuery.Where(a => a.Schedule.AttrId == null || !filterNotAttr.Contains(a.Schedule.AttrId));
                if (filterCult.Count > 0) deliveryAncmtQuery = deliveryAncmtQuery.Where(a => a.Schedule.CultId != null && filterCult.Contains(a.Schedule.CultId));
                if (filterNotCult.Count > 0) deliveryAncmtQuery = deliveryAncmtQuery.Where(a => a.Schedule.CultId == null || !filterNotCult.Contains(a.Schedule.CultId));

                if (filterWeightGt > 0 && filterWeightLt > 0) {
                    filterNames.Add($"{filterWeightGt:N0}–{filterWeightLt:N0} kg");
                } else if (filterWeightGt > 0) {
                    filterNames.Add($"ab {filterWeightGt:N0} kg");
                } else if (filterWeightLt > 0) {
                    filterNames.Add($"bis {filterWeightLt:N0} kg");
                }
            }

            return (filterNames, deliveryAncmtQuery, filter);
        }

        public static async Task<(int, int, int, string)> UpdateDeliveryAncmt(this DeliveryAncmtAdminViewModel vm, int? oldYear, int? oldDsNr, int? oldMgNr, string? oldSortId, string? oldType) {
            int year = vm.DeliverySchedule!.Year;
            int dsnr = vm.DeliverySchedule!.DsNr;
            int newMgNr = vm.MgNr!.Value;
            string newSortId = vm.SortId!;

            return await Task.Run(async () => {
                using var ctx = new AppDbContext();
                var a = new DeliveryAncmt {
                    Year = oldYear ?? year,
                    DsNr = oldDsNr ?? dsnr,
                    MgNr = oldMgNr ?? newMgNr,
                    SortId = oldSortId ?? newSortId,
                    Weight = vm.Weight!.Value,
                    Type = oldType ?? "manual",
                };

                if (oldDsNr != null) {
                    ctx.Update(a);
                } else {
                    ctx.Add(a);
                }

                await ctx.SaveChangesAsync();

                if (oldDsNr != null && (oldYear != year || oldDsNr != dsnr || oldMgNr != newMgNr || oldSortId != newSortId)) {
                    await ctx.Database.ExecuteSqlAsync($"UPDATE delivery_announcement SET year = {year}, dsnr = {dsnr}, mgnr = {newMgNr}, sortid = {newSortId} WHERE (year, dsnr, mgnr, sortid) = ({a.Year}, {a.DsNr}, {a.MgNr}, {a.SortId})");
                }

                return (year, dsnr, newMgNr, newSortId);
            });
        }

        public static async Task GenerateDeliveryAncmtList(this DeliveryAncmtAdminViewModel vm, ExportSubject subject, ExportMode mode) {
            using var ctx = new AppDbContext();
            IQueryable<DeliveryAncmt> query;
            List<string> filterNames = [];
            if (subject == ExportSubject.FromSelectedSchedule) {
                var s = vm.SelectedDeliverySchedule;
                if (s == null) return;
                query = ctx.DeliveryAnnouncements
                    .Where(a => a.Year == s.Year && a.DsNr == s.DsNr);
                filterNames.Add($"{s.Date:dd.MM.yyyy} – {s.Branch.Name} – {s.Description}");
            } else {
                throw new ArgumentException("Invalid value for ExportSubject");
            }

            query = query
                .OrderBy(a => a.Schedule.DateString)
                .ThenBy(a => a.Schedule.Branch.Name)
                .ThenBy(a => a.Schedule.Description)
                .ThenBy(a => a.Member.Name)
                .ThenBy(a => a.Member.GivenName)
                .ThenBy(a => a.Member.MgNr);

            if (mode == ExportMode.SaveList) {
                var d = new SaveFileDialog() {
                    FileName = $"{DeliveryAncmtList.Name}.ods",
                    DefaultExt = "ods",
                    Filter = "OpenDocument Format Spreadsheet (*.ods)|*.ods",
                    Title = $"{DeliveryAncmtList.Name} speichern unter - Elwig"
                };
                if (d.ShowDialog() == true) {
                    Mouse.OverrideCursor = Cursors.Wait;
                    await Task.Run(async () => {
                        try {
                            var data = await DeliveryAncmtListData.FromQuery(query, filterNames);
                            using var ods = new OdsFile(d.FileName);
                            await ods.AddTable(data);
                        } catch (Exception exc) {
                            MessageBox.Show(exc.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    });
                    Mouse.OverrideCursor = null;
                }
            } else {
                Mouse.OverrideCursor = Cursors.Wait;
                await Task.Run(async () => {
                    try {
                        var data = await DeliveryAncmtListData.FromQuery(query, filterNames);
                        using var doc = new DeliveryAncmtList(string.Join(" / ", filterNames), data);
                        await Utils.ExportDocument(doc, mode);
                    } catch (Exception exc) {
                        MessageBox.Show(exc.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                });
                Mouse.OverrideCursor = null;
            }
        }

        private static void AddToolTipCell(Grid grid, string text, int row, int col, int colSpan = 1, bool bold = false, bool alignRight = false, bool alignCenter = false) {
            var tb = new TextBlock() {
                Text = text,
                TextAlignment = alignRight ? TextAlignment.Right : alignCenter ? TextAlignment.Center : TextAlignment.Left,
                Margin = new(0, 12 * row, 0, 0),
                FontWeight = bold ? FontWeights.Bold : FontWeights.Normal,
            };
            tb.SetValue(Grid.ColumnProperty, col);
            tb.SetValue(Grid.ColumnSpanProperty, colSpan);
            grid.Children.Add(tb);
        }

        private static void AddToolTipRow(Grid grid, int row, string? h1, string? h2, int weight, int? total1, int total2) {
            var bold = h2 == null;
            if (h1 != null) AddToolTipCell(grid, h1 + ":", row, 0, (h2 == null) ? 2 : 1, bold);
            if (h2 != null) AddToolTipCell(grid, h2 + ":", row, 1, 1, bold);
            AddToolTipCell(grid, $"{weight:N0} kg", row, 2, 1, bold, true);
            if (total1 != null && total1 != 0)
                AddToolTipCell(grid, $"{weight * 100.0 / total1:N1} %", row, 3, 1, bold, true);
            if (total2 != 0)
                AddToolTipCell(grid, $"{weight * 100.0 / total2:N1} %", row, 4, 1, bold, true);
        }

        public static async Task<(string, Grid)> GenerateToolTip(IQueryable<DeliveryAncmt> deliveryAncmts) {
            var grid = new Grid();
            grid.ColumnDefinitions.Add(new() { Width = new(10) });
            grid.ColumnDefinitions.Add(new() { Width = new(60) });
            grid.ColumnDefinitions.Add(new() { Width = new(80) });
            grid.ColumnDefinitions.Add(new() { Width = new(50) });
            grid.ColumnDefinitions.Add(new() { Width = new(50) });
            var text = "-";

            var weight = await deliveryAncmts.SumAsync(p => p.Weight);
            text = $"{weight:N0} kg";
            AddToolTipRow(grid, 0, "Menge", null, weight, null, weight);

            if (await deliveryAncmts.AnyAsync()) {
                var attrGroups = await deliveryAncmts
                    .GroupBy(a => new { Attr = a.Schedule.Attribute!.Name, Cult = a.Schedule.Cultivation!.Name })
                    .Select(g => new {
                        g.Key.Attr,
                        g.Key.Cult,
                        Weight = g.Sum(a => a.Weight)
                    })
                    .OrderByDescending(g => g.Weight)
                    .ThenBy(g => g.Attr)
                    .ThenBy(g => g.Cult)
                    .ToListAsync();
                var sortGroups = await deliveryAncmts
                    .GroupBy(a => a.SortId)
                    .Select(g => new {
                        SortId = g.Key,
                        Weight = g.Sum(a => a.Weight)
                    })
                    .OrderByDescending(g => g.Weight)
                    .ThenBy(g => g.SortId)
                    .ToListAsync();
                var groups = await deliveryAncmts
                    .GroupBy(a => new {
                        Attr = a.Schedule.Attribute!.Name,
                        Cult = a.Schedule.Cultivation!.Name,
                        a.SortId,
                    })
                    .Select(g => new {
                        g.Key.Attr,
                        g.Key.Cult,
                        g.Key.SortId,
                        Weight = g.Sum(p => p.Weight)
                    })
                    .OrderByDescending(g => g.Weight)
                    .ThenBy(g => g.Attr)
                    .ThenBy(g => g.Cult)
                    .ThenBy(g => g.SortId)
                    .ToListAsync();

                int rowNum = 1;
                foreach (var attrG in attrGroups) {
                    rowNum++;
                    var name = attrG.Attr == null && attrG.Cult == null ? null : attrG.Attr + (attrG.Attr != null && attrG.Cult != null ? " / " : "") + attrG.Cult;
                    AddToolTipRow(grid, rowNum++, name, null, attrG.Weight, attrG.Weight, weight);
                    foreach (var g in groups.Where(g => g.Attr == attrG.Attr && g.Cult == attrG.Cult).OrderByDescending(g => g.Weight).ThenBy(g => g.SortId)) {
                        AddToolTipRow(grid, rowNum++, null, g.SortId, g.Weight, attrG.Weight, weight);
                    }
                }

                if (attrGroups.Count == 1) {
                    var g = attrGroups.First();
                    var name = g.Attr == null && g.Cult == null ? null : g.Attr + (g.Attr != null && g.Cult != null ? " / " : "") + g.Cult;
                    if (name != null) {
                        text += $" [{name}]";
                    }
                    if (sortGroups.Count > 1 && sortGroups.Count <= 4) {
                        text += $" = {string.Join(" + ", sortGroups.Select(g => $"{g.Weight:N0} kg ({(double)g.Weight / weight:0%})" + (g.SortId == null ? "" : $" [{g.SortId}]")))}";

                    }
                } else if (attrGroups.Count <= 4) {
                    text += $" = {string.Join(" + ", attrGroups.Select(g => $"{g.Weight:N0} kg ({(double)g.Weight / weight:0%})" + (g.Attr == null && g.Cult == null ? "" : $" [{g.Attr}{(g.Attr != null && g.Cult != null ? " / " : "")}{g.Cult}]")))}";
                }
            }

            return (text, grid);
        }
    }
}
