using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media.Imaging;
using Microsoft.EntityFrameworkCore;
using demko_v.Models;

namespace demko_v;

public partial class MainWindow : Window
{
    
    ObservableCollection<AgentPresenter> agents = new ObservableCollection<AgentPresenter>();
    List<AgentPresenter> dataSourceAgents;
    
    private const int ItemsPerPage = 10;
    private int currentPage = 1;
    
    public MainWindow()
    {
        InitializeComponent();
        LoadData();
        
        TitleAgentSortComboBox.SelectedIndex = 0;
        SaleSortComboBox.SelectedIndex = 0;
        PrioritySortCombobox.SelectedIndex = 0;
        TypeAgentSortCombobox.SelectedIndex = 0;

        DisplayAgents();
    }
    
    private void LoadData()
    {
        using var ctx = new DemoAgentsContext();
        
        dataSourceAgents = ctx.Agents
            .Include(a => a.ProductSales)
            .ThenInclude(ps => ps.Product)
            .Select(agent => new AgentPresenter
            {
                Id = agent.Id,
                Title = agent.Title,
                Phone = "+" + agent.Phone,
                AgentType = agent.AgentType.Title,
                Priority = agent.Priority,
                SalesYear = agent.ProductSales.Any() ? agent.ProductSales.Max(ps => ps.SaleDate.Year) : 0,
                SalesQuantity = agent.ProductSales.Sum(ps => ps.ProductCount * (int)ps.Product.MinCostForAgent),
                CountSales = agent.ProductSales.Sum(ps => ps.ProductCount),
                Sale = agent.ProductSales.Any() ? CalculateSale(agent.ProductSales.Sum(ps => ps.Product.MinCostForAgent * ps.ProductCount)) + "%" : "0%",
                Logo = agent.Logo
            }).ToList();
    }

    public void DisplayAgents()
    {
        LoadData();
        var temp = dataSourceAgents;
        
        agents.Clear();

        switch (TitleAgentSortComboBox.SelectedIndex)
        {
            case 0: break;
            case 1: temp = temp.OrderBy(a => a.Title).ToList(); break;
            case 2: temp = temp.OrderByDescending(a => a.Title).ToList(); break;
        }

        switch (SaleSortComboBox.SelectedIndex)
        {
            case 0: break;
            case 1: temp = temp.OrderByDescending(a => int.Parse(a.Sale.Replace("%", ""))).ToList(); break;
            case 2: temp = temp.OrderBy(a => int.Parse(a.Sale.Replace("%", ""))).ToList(); break;
        }

        switch (PrioritySortCombobox.SelectedIndex)
        {
            case 0: break;
            case 1: temp = temp.OrderByDescending(a => a.Priority).ToList(); break;
            case 2: temp = temp.OrderBy(a => a.Priority).ToList(); break;
        }

        switch (TypeAgentSortCombobox.SelectedIndex)
        {
            case 0: break;
            case 1: temp = temp.Where(a => a.AgentType == "ООО").ToList(); break;
            case 2: temp = temp.Where(a => a.AgentType == "МФО").ToList(); break;
            case 3: temp = temp.Where(a => a.AgentType == "ЗАО").ToList(); break;
            case 4: temp = temp.Where(a => a.AgentType == "МКК").ToList(); break;
            case 5: temp = temp.Where(a => a.AgentType == "ПАО").ToList(); break;
            case 6: temp = temp.Where(a => a.AgentType == "ОАО").ToList(); break;
        }
        
        if (!string.IsNullOrEmpty(SearchTextBox.Text))
        {
            var search = SearchTextBox.Text;
            temp = temp.Where(a => IsContains(a.Title, a.Phone, search)).ToList();
        }

        foreach (var item in temp)
        {
            agents.Add(item);
        }

        currentPage = 0; 
        UpdateListBox();
    }

    public class AgentPresenter : Agent
    {
        Bitmap? Image
        {
            get
            {
                try
                {
                    string absolutePath = Path.Combine(AppContext.BaseDirectory, Logo);
                    return new Bitmap(absolutePath);
                }
                catch
                {
                    return null;
                }
            }
        }
        
        public int SalesYear { get; set; }
        public int? SalesQuantity { get; set; }
        public string? Sale { get; set; }
        public string? AgentType { get; set; }
        public int CountSales { get; set; }
    }
    
    
    public void UpdateListBox()
    {
        var pagedAgents = agents.Skip(currentPage * ItemsPerPage).Take(ItemsPerPage).ToList();
        AgentListBox.ItemsSource = pagedAgents;
        
        CountAgentsTextBlock.Text = $"{currentPage + 1} / {Math.Ceiling((double)agents.Count / ItemsPerPage)}";
        
        BackButton.IsEnabled = currentPage > 0;
        NextButton.IsEnabled = (currentPage + 1) * ItemsPerPage < agents.Count;
        
    }
    
    public void Back_OnClick(object? sender, RoutedEventArgs e)
    {
        if (currentPage > 0)
        {
            currentPage--;
            UpdateListBox();
        }
    }

    public void Next_OnClick(object? sender, RoutedEventArgs e)
    {
        if ((currentPage + 1) * ItemsPerPage < agents.Count)
        {
            currentPage++;
            UpdateListBox();
        }
    }
    
    public bool IsContains(string title, string phone, string search)
    {
        string message = (title + phone).ToLower();
        search = search.ToLower();
        return message.Contains(search);
    }
    
    private static int CalculateSale(decimal totalSales)
    {
        if (totalSales < 10000) return 0;
        if (totalSales < 50000) return 5;
        if (totalSales < 150000) return 10;
        if (totalSales < 500000) return 20;
        return 25;
    }
    
    public void SearchTextBox_OnTextChanging(object? sender, RoutedEventArgs e)
    {
        DisplayAgents();
    }
    
    
    public void TitleAgentSortComboBox_OnSelectionChanged(object? sender, RoutedEventArgs e)
    {
        DisplayAgents();
    }
    
    
    public void SaleSortComboBox_OnSelectionChanged(object? sender, RoutedEventArgs e)
    {
        DisplayAgents();
    }
    
    
    public void PrioritySortCombobox_OnSelectionChanged(object? sender, RoutedEventArgs e)
    {
        DisplayAgents();
    }
    
    
    public void TypeAgentSortCombobox_OnSelectionChanged(object? sender, RoutedEventArgs e)
    {
        DisplayAgents();
    }
    
    public void AddAgent_OnClick(object? sender, RoutedEventArgs e)
    {
        AddAgentWindow attendanceButton = new AddAgentWindow();
        attendanceButton.ShowDialog(this); ;
    }
    
    private async void EditMenuItem_OnClick(object? sender, RoutedEventArgs e)
    {
        using var ctx = new DemoAgentsContext();
        if (AgentListBox.SelectedItem is AgentPresenter selectedAgentPresenter)
        {
            var agent = ctx.Agents.FirstOrDefault(a => a.Id == selectedAgentPresenter.Id);
            EditAgentWindow editAgentWindow = new EditAgentWindow(agent);
            var updatedAgent = await editAgentWindow.ShowDialog<Agent>(this);
        }
    
        DisplayAgents();
    }

    private async void PriorityMenuItem_OnClick(object? sender, RoutedEventArgs e)
    {
        if (AgentListBox.SelectedItem is AgentPresenter selectedAgentPresenter)
        {
            PriorityWindow priorityWindow = new PriorityWindow(selectedAgentPresenter.Id);
            await priorityWindow.ShowDialog(this);
        }
        
        DisplayAgents();
    }
}