using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Threading;
using NavisworksTransport.UI.WPF.Converters;


namespace NavisworksTransport.UI.WPF.Views
{
    public partial class EditCoordinatesWindow : Window
    {
        public double X { get; set; }
        public double Y { get; set; }
        public double Z { get; set; }
        public string PointName { get; set; }
        public string PointType { get; set; }

        public EditCoordinatesWindow(double x, double y, double z, string pointName = "", string pointType = "")
        {
            try
            {
                InitializeComponent();
                X = x;
                Y = y;
                Z = z;
                PointName = pointName;
                PointType = pointType;
                DataContext = this;
            }
            catch (Exception ex)
            {
                LogManager.Error($"编辑坐标对话框初始化失败: {ex.Message}", ex);
                MessageBox.Show($"编辑坐标对话框初始化失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void OnSaveClick(object sender, RoutedEventArgs e)
        {
            if (!TryCommitInputValues())
            {
                return;
            }

            DialogResult = true;
            Close();
        }

        private void OnCancelClick(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        /// <summary>
        /// 复制坐标
        /// </summary>
        private void OnCopyClick(object sender, RoutedEventArgs e)
        {
            string coordinate = string.Format("{0:0.000}, {1:0.000}, {2:0.000}", X, Y, Z);
            bool success = ClipboardHelper.TrySetText(coordinate, "编辑路径点坐标");
            ShowButtonFeedback(CopyButton, success);
        }

        /// <summary>
        /// 粘贴坐标
        /// </summary>
        private void OnPasteClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!Clipboard.ContainsText()) 
                {
                    ShowButtonFeedback(PasteButton, false);
                    return;
                }
                
                string text = Clipboard.GetText().Trim();
                string[] parts = text.Split(new[] { ',', ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                
                if (parts.Length >= 3 &&
                    EditableNumberConverter.TryParseNumber(parts[0], System.Globalization.CultureInfo.CurrentCulture, typeof(double), out object xValue) &&
                    EditableNumberConverter.TryParseNumber(parts[1], System.Globalization.CultureInfo.CurrentCulture, typeof(double), out object yValue) &&
                    EditableNumberConverter.TryParseNumber(parts[2], System.Globalization.CultureInfo.CurrentCulture, typeof(double), out object zValue))
                {
                    X = (double)xValue;
                    Y = (double)yValue;
                    Z = (double)zValue;
                    // 刷新绑定
                    DataContext = null;
                    DataContext = this;
                    ShowButtonFeedback(PasteButton, true);
                }
                else
                {
                    ShowButtonFeedback(PasteButton, false);
                }
            }
            catch 
            { 
                ShowButtonFeedback(PasteButton, false);
            }
        }

        /// <summary>
        /// 显示按钮点击反馈
        /// </summary>
        private void ShowButtonFeedback(Button button, bool success)
        {
            if (button == null) return;
            
            var originalBackground = button.Background;
            var originalBorderBrush = button.BorderBrush;
            
            // 成功绿色，失败红色
            if (success)
            {
                button.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(76, 175, 80));
                button.BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(56, 142, 60));
            }
            else
            {
                button.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(244, 67, 54));
                button.BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(211, 47, 47));
            }
            
            // 800毫秒后恢复
            var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(800) };
            timer.Tick += (s, e) =>
            {
                timer.Stop();
                button.Background = originalBackground;
                button.BorderBrush = originalBorderBrush;
            };
            timer.Start();
        }

        private bool TryCommitInputValues()
        {
            return TryUpdateNumberTextBox(XTextBox, "请输入有效的 X 坐标。") &&
                   TryUpdateNumberTextBox(YTextBox, "请输入有效的 Y 坐标。") &&
                   TryUpdateNumberTextBox(ZTextBox, "请输入有效的 Z 坐标。");
        }

        private static bool TryUpdateNumberTextBox(TextBox textBox, string message)
        {
            BindingExpression binding = textBox.GetBindingExpression(TextBox.TextProperty);

            if (EditableNumberConverter.IsIntermediateText(textBox.Text) ||
                !EditableNumberConverter.TryParseNumber(textBox.Text.Trim(), System.Globalization.CultureInfo.CurrentCulture, typeof(double), out _))
            {
                ShowInputError(message, textBox);
                return false;
            }

            binding?.UpdateSource();

            if (Validation.GetHasError(textBox))
            {
                ShowInputError(message, textBox);
                return false;
            }

            return true;
        }

        private static void ShowInputError(string message, TextBox textBox)
        {
            MessageBox.Show(message, "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
            textBox.Focus();
            textBox.SelectAll();
        }
    }
}
