using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

using FasdDesktopUi.Basics.Converter;
using FasdDesktopUi.Basics.Models;
using FasdDesktopUi.Basics.UiActions;

using C4IT.FASD.Base;
using static C4IT.Logging.cLogManager;
using MaterialIcons;

namespace FasdDesktopUi.Basics.UserControls
{
    public partial class CustomMenuItem : UserControl
    {
        #region Properties

        #region MenuData

        private cMenuDataBase _menuData = new cMenuDataBase();

        private readonly bool _isLean;

        public cMenuDataBase MenuData
        {
            get { return _menuData; }
            set
            {
                if (_menuData != value)
                {
                    _menuData = value;
                    MenuDataChanged();
                }
            }
        }

        private void MenuDataChanged()
        {
            if (MenuData.MenuIcon.Intern != null)
                MenuItemIcon.SelectedInternIcon = MenuData.MenuIcon.Intern;
            else if (MenuData.MenuIcon.Material != null)
                MenuItemIcon.SelectedMaterialIcon = MenuData.MenuIcon.Material;

            MenuItemIcon.IconHeight = MenuData.MenuIconSize * MenuItemIcon.IconHeight;
            MenuItemIcon.IconWidth = MenuData.MenuIconSize * MenuItemIcon.IconWidth;

            switch (MenuData.UiAction?.DisplayType)
            {
                case Enums.enumActionDisplayType.hidden:
                    //todo: add hidden state
                    break;
                case Enums.enumActionDisplayType.disabled:
                    MenuItemContent.SetValue(OpacityProperty, 0.5);
                    MenuItemBorder.SetResourceReference(StyleProperty, "Menu.MainCategory.NoHover");
                    MenuItemBorder.SetValue(ToolTipProperty, string.IsNullOrWhiteSpace(MenuData.UiAction.AlternativeDescription) ? MenuData.UiAction.Description : MenuData.UiAction.AlternativeDescription);
                    try
                    {
                        MenuItemBorder.MouseLeftButtonUp -= MenuItemBorder_Click;
                        MenuItemBorder.TouchDown -= MenuItemBorder_Click;
                    }
                    catch { }
                    break;
                case Enums.enumActionDisplayType.enabled:
                    MenuItemContent.ClearValue(OpacityProperty);
                    MenuItemBorder.ClearValue(IsHitTestVisibleProperty);
                    break;
            }

            MenuItemBorder.ToolTip = !string.IsNullOrEmpty(MenuData.UiAction?.Description) ? MenuData.UiAction?.Description : null;
            ToolTip = !string.IsNullOrEmpty(MenuData.UiAction?.Description) ? MenuData.UiAction?.Description : null;
            CustomTextBlock.Text = MenuData.MenuText;
            CustomTextBlockBottom.Text = MenuData.MenuText;

            if (string.IsNullOrWhiteSpace(MenuData.TrailingText))
            {
                CustomTrailingTextBlock.Text = string.Empty;
                CustomTrailingTextBlock.Visibility = Visibility.Collapsed;
            }
            else
            {
                CustomTrailingTextBlock.Text = MenuData.TrailingText;
                CustomTrailingTextBlock.Visibility = Visibility.Visible;
            }

            DrawEnhancedMenuInformation();
        }

        private void DrawEnhancedMenuInformation()
        {
            try
            {
                if (MenuData is cMenuDataContainer containerMenuData)
                    DrawContainer(containerMenuData);
                else if (MenuData is cMenuDataSearchRelation searchRelationMenuData)
                    DrawSearchRelation(searchRelationMenuData);
                else if (MenuData is cMenuDataLoading)
                    LoadingIcon.Visibility = Visibility.Visible;
                else
                    DrawDefault();
            }
            catch (Exception E)
            {
                LogException(E);
            }

            void DrawContainer(cMenuDataContainer containerMenuData)
            {
                SubMenuCounterBorder.Visibility = Visibility.Visible;
                var count = 0;
                foreach (var entry in containerMenuData.SubMenuData)
                {
                    if (entry.UiAction?.DisplayType == null || entry.UiAction?.DisplayType == Enums.enumActionDisplayType.enabled)
                        count++;
                }
                if (count == 0)
                    SubMenuCounterTextBlock.Text = "-";
                else
                    SubMenuCounterTextBlock.Text = count.ToString();
            }

            void DrawSearchRelation(cMenuDataSearchRelation searchRelationMenuData)
            {
                if (!(searchRelationMenuData.Data is cF4sdApiSearchResultRelation relationData))
                    return;

                if (searchRelationMenuData.IsMatchingRelation)
                {
                    LoadingIcon.SelectedMaterialIcon = MaterialIconType.ic_link;
                    LoadingIcon.ClearValue(StyleProperty);
                    LoadingIcon.Visibility = Visibility.Visible;
                }


                if (relationData.Type is enumF4sdSearchResultClass.Ticket)
                {
                    if (relationData.Infos is null)
                        return;

                    if (relationData.Infos.TryGetValue("Summary", out var ticketSummary))
                    {
                        CustomTextBlockBottom.Text = ticketSummary;
                        CustomTextBlockBorderBottom.Visibility = Visibility.Visible;
                    }

                    if (relationData.Infos.TryGetValue("StatusId", out var ticketStatusId))
                    {
                        Enum.TryParse(ticketStatusId, true, out enumTicketStatus ticketStatus);

                        switch (ticketStatus)
                        {
                            case enumTicketStatus.Unknown:
                                break;
                            case enumTicketStatus.New:
                            case enumTicketStatus.InProgress:
                            case enumTicketStatus.OnHold:
                                MenuItemIcon.SelectedMaterialIcon = MaterialIconType.ic_drafts;
                                break;
                            case enumTicketStatus.Closed:
                                MenuItemIcon.SelectedMaterialIcon = MaterialIconType.ic_mail;
                                break;
                            default:
                                break;
                        }
                    }
                }
                else
                {
                    SearchRelationGrid.Visibility = Visibility.Visible;

                    if (searchRelationMenuData.LastUsed == DateTime.MinValue)
                    {
                        LessThanTextBlock.Text= string.Empty;
                        LessThanTextBlock.Visibility = Visibility.Collapsed;
                        LastSeenTextBox.Visibility = Visibility.Collapsed;

                        ActivityIndicator.Width = 0;
                        ActivityIndicator.Visibility = Visibility.Collapsed;
                        ActivityTextBlock.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        var lastUsedTimeSpan = DateTime.UtcNow - searchRelationMenuData.LastUsed;
                        LanguageDefinitionsConverter valueConverter = new LanguageDefinitionsConverter();
                        string lastSeenText = null;

                        if (Math.Floor(lastUsedTimeSpan.TotalHours) > 24)
                            lastSeenText = valueConverter.Convert(Math.Ceiling(lastUsedTimeSpan.TotalDays), null, "Searchbar.LessThan.Days", null) as string;
                        else if (Math.Floor(lastUsedTimeSpan.TotalHours) >= 1)
                            lastSeenText = valueConverter.Convert(Math.Ceiling(lastUsedTimeSpan.TotalHours), null, "Searchbar.LessThan.Hours", null) as string;
                        else
                            lastSeenText = valueConverter.Convert(Math.Ceiling(lastUsedTimeSpan.TotalMinutes), null, "Searchbar.LessThan.Min", null) as string;

                        LessThanTextBlock.Text = lastSeenText;
                        LessThanTextBlock.Visibility = Visibility.Visible;
                        LastSeenTextBox.Visibility = Visibility.Visible;

                        ActivityIndicator.Width = Math.Max(ActivityIndicator.Width * relationData.UsingLevel, ActivityIndicator.Width * 0.1);
                        ActivityIndicator.Visibility = Visibility.Visible;
                        ActivityTextBlock.Visibility = Visibility.Visible;
                    }

                }
            }

            void DrawDefault()
            {
                if (string.IsNullOrWhiteSpace(MenuData.SubMenuText))
                    return;

                CustomTextBlockBottom.Text = MenuData.SubMenuText;
                CustomTextBlockBorderBottom.Visibility = Visibility.Visible;
            }
        }

        #endregion

        #endregion

        public CustomMenuItem(bool isLean)
        {
            _isLean = isLean;
            InitializeComponent();
        }

        #region Events

        private void MenuItemBorder_Click(object sender, InputEventArgs e)
        {
            if (MenuData.UiAction == null)
                return;

            cUiActionBase.RaiseEvent(MenuData.UiAction, this, this);
        }

        #region Hover

        private void MenuItemBorder_MouseEnter(object sender, MouseEventArgs e)
        {
            cUtility.SetTickerTextAnimation(CustomTextBlock, CustomTextBlockBorder);

            if (string.IsNullOrWhiteSpace(CustomTextBlockBottom.Text) is false)
                cUtility.SetTickerTextAnimation(CustomTextBlockBottom, CustomTextBlockBorderBottom);
        }

        private void MenuItemBorder_MouseLeave(object sender, MouseEventArgs e)
        {
            CustomTextBlock.TextTrimming = TextTrimming.CharacterEllipsis;
            CustomTextBlock.BeginAnimation(MarginProperty, null);

            CustomTextBlockBorder.ClearValue(WidthProperty);
            CustomTextBlockBorderBottom.ClearValue(WidthProperty);

            if (string.IsNullOrWhiteSpace(CustomTextBlockBottom.Text) is false)
            {
                CustomTextBlockBottom.TextTrimming = TextTrimming.CharacterEllipsis;
                CustomTextBlockBottom.BeginAnimation(MarginProperty, null);
            }
        }

        #endregion

        #endregion

        public void ShowDetailHeadings(bool showDetails)
        {
            SearchRelationGrid.ColumnDefinitions[0].Width =
                showDetails ? new GridLength(1, GridUnitType.Auto) : new GridLength(0);
        }

        private void CustomMenuItemUc_Initialized(object sender, EventArgs e)
        {
            if (_isLean)
                MenuItemBorder.Height = 30;

        }
    }
}
