using Microsoft.UI.Xaml.Controls;
using Sonex.Client.Helpers;
using Sonex.Data.Records;
using System;
using System.Collections.ObjectModel;
using System.Globalization;

namespace Sonex.Client.Views
{
    public sealed partial class ProductBasicInformationView : UserControl, IView
    {
        private const string NoImageSource = "ms-appx:///Assets/no-image.png";
        private string? _currentKey;
        private bool _hasChanges;

        public bool HasChanges => _hasChanges;
        public bool CanSave => CanEdit && HasChanges;
        public bool CanEdit => false;

        public ProductBasicInformationView()
        {
            InitializeComponent();
            ClearProductValues();
        }

        public void Clear()
        {
            _currentKey = null;
            if (Gallery.ItemsSource != null)
            {
                Gallery.ItemsSource = null;
            }

            ClearProductValues();
            MarkSaved();
        }

        public void Reload()
        {
            if (string.IsNullOrWhiteSpace(_currentKey))
            {
                Clear();
                return;
            }

            Load(_currentKey);
        }

        public void Load(string key)
        {
            _currentKey = key;
            ObservableCollection<string> pictures = new();
            var productImage = ProductImageRecord.GetByArticleNumber(key).GetAwaiter().GetResult();
            var product = ProductRecord.GetBasicInformation(key).GetAwaiter().GetResult();

            if (productImage != null && productImage.Success && productImage.Items != null)
            {
                foreach (var item in productImage.Items)
                {
                    if (string.IsNullOrWhiteSpace(item.TargetRelativePath))
                    {
                        continue;
                    }

                    var url = $"{GlobalValues.WebApiBaseUrl}/static/img/250/{item.TargetRelativePath}";
                    pictures.Add(url);
                }
            }

            if (pictures.Count == 0)
            {
                pictures.Add(NoImageSource);
            }

            Gallery.ItemsSource = pictures;
            Gallery.UpdateLayout();

            if (product.Success && product.Item is not null)
            {
                LoadProductValues(product.Item);
            }
            else
            {
                ClearProductValues();
                ArticleNumberProperty.Value = key;
            }

            MarkSaved();
        }

        public void Save()
        {
            MarkSaved();
        }

        public void MarkChanged()
        {
            _hasChanges = true;
        }

        public void MarkSaved()
        {
            _hasChanges = false;
        }

        private void LoadProductValues(ProductRecord product)
        {
            ArticleNameProperty.Value = product.ArticleName ?? string.Empty;
            ArticleNumberProperty.Value = product.Artnr;
            SuEanProperty.Value = product.SuEans ?? string.Empty;
            CategoryProperty.Value = product.Category ?? string.Empty;
            ParametersProperty.Value = product.ArticleParametersText ?? string.Empty;
            StockMessageProperty.Value = product.StockMessage ?? string.Empty;
            NotificationProperty.Value = product.Notification ?? string.Empty;

            ArchivalProperty.Value = product.Archival;
            BestBeforeDateUsedProperty.Value = ToBool(product.BestBeforeDateUsed);
            BestBeforeDateMixProperty.Value = ToBool(product.BestBeforeDateMix);
            PacksizeProperty.Value = product.Packsize;
            ShipUnitProperty.Value = product.ShipUnit;
            BkProperty.Value = product.Bk;
            DpdProperty.Value = product.Dpd;

            SalesClassProperty.Value = product.SalesClass ?? string.Empty;
            DcGroupProperty.Value = product.DcGroup ?? string.Empty;
            WebClusterProperty.Value = product.WebCluster ?? string.Empty;
            WebSalesClassProperty.Value = product.WebSalesClass ?? string.Empty;
            WebSalesShareProperty.Value = product.WebSalesShare?.ToString() ?? string.Empty;

            PriceNlProperty.Value = Text(product.PriceNl);
            PriceDeProperty.Value = Text(product.PriceDe);
            PriceHcProperty.Value = Text(product.PriceHc);
        }

        private void ClearProductValues()
        {
            ArticleNameProperty.Value = string.Empty;
            ArticleNumberProperty.Value = string.Empty;
            SuEanProperty.Value = string.Empty;
            CategoryProperty.Value = string.Empty;
            ParametersProperty.Value = string.Empty;
            StockMessageProperty.Value = string.Empty;
            NotificationProperty.Value = string.Empty;

            ArchivalProperty.Value = false;
            BestBeforeDateUsedProperty.Value = false;
            BestBeforeDateMixProperty.Value = false;
            PacksizeProperty.Value = false;
            ShipUnitProperty.Value = false;
            BkProperty.Value = false;
            DpdProperty.Value = false;

            SalesClassProperty.Value = string.Empty;
            DcGroupProperty.Value = string.Empty;
            WebClusterProperty.Value = string.Empty;
            WebSalesClassProperty.Value = string.Empty;
            WebSalesShareProperty.Value = string.Empty;

            PriceNlProperty.Value = string.Empty;
            PriceDeProperty.Value = string.Empty;
            PriceHcProperty.Value = string.Empty;
        }

        private static bool? ToBool(string? value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return false;
            }

            var normalized = value.Trim();
            if (bool.TryParse(normalized, out var result))
            {
                return result;
            }

            if (normalized.Equals("1", StringComparison.OrdinalIgnoreCase)
                || normalized.Equals("y", StringComparison.OrdinalIgnoreCase)
                || normalized.Equals("yes", StringComparison.OrdinalIgnoreCase)
                || normalized.Equals("true", StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            if (normalized.Equals("0", StringComparison.OrdinalIgnoreCase)
                || normalized.Equals("n", StringComparison.OrdinalIgnoreCase)
                || normalized.Equals("no", StringComparison.OrdinalIgnoreCase)
                || normalized.Equals("false", StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            return null;
        }

        private static string Text(object? value)
        {
            return Convert.ToString(value, CultureInfo.CurrentCulture) ?? string.Empty;
        }
    }
}
