using System;
using System.Windows;
using System.Windows.Media;
using NavisworksTransport.Utils;

namespace NavisworksTransport.UI.WPF.Views
{
    public partial class CornerTurnCheckDialog : Window
    {
        public CornerTurnCheckDialog()
        {
            InitializeComponent();
        }

        private void OnCalculateClick(object sender, RoutedEventArgs e)
        {
            if (!TryParseInputs(out var c1, out var c2, out var length, out var width))
                return;

            var pass = CornerTurnCheckHelper.CanPass(length, width, c1, c2,
                out var margin, out var maxLength);

            ResultBorder.Visibility = Visibility.Visible;

            if (pass)
            {
                ResultBorder.Background = new SolidColorBrush(Color.FromRgb(240, 255, 240));
                ResultBorder.BorderBrush = new SolidColorBrush(Color.FromRgb(76, 175, 80));
                ResultTitle.Text = "✅ 可通过";
                ResultTitle.Foreground = new SolidColorBrush(Color.FromRgb(46, 125, 50));
                ResultDetail.Text = $"余量: {margin:F2} 米\n临界长度: {maxLength:F2} 米";
            }
            else
            {
                ResultBorder.Background = new SolidColorBrush(Color.FromRgb(255, 240, 240));
                ResultBorder.BorderBrush = new SolidColorBrush(Color.FromRgb(244, 67, 54));
                ResultTitle.Text = "❌ 不可通过";
                ResultTitle.Foreground = new SolidColorBrush(Color.FromRgb(183, 28, 28));
                ResultDetail.Text = $"不足: {-margin:F2} 米\n临界长度: {maxLength:F2} 米";
            }
        }

        private void OnCloseClick(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private bool TryParseInputs(out double c1, out double c2, out double length, out double width)
        {
            c1 = c2 = length = width = 0;

            if (!TryParseTextBox(EntryWidthBox, out c1, "入口通道宽度")) return false;
            if (!TryParseTextBox(ExitWidthBox, out c2, "出口通道宽度")) return false;
            if (!TryParseTextBox(LengthBox, out length, "模块长度")) return false;
            if (!TryParseTextBox(WidthBox, out width, "模块宽度")) return false;

            return true;
        }

        private static bool TryParseTextBox(System.Windows.Controls.TextBox box, out double value, string name)
        {
            value = 0;
            var text = box.Text.Trim();
            if (string.IsNullOrEmpty(text))
            {
                MessageBox.Show($"请输入{name}。", "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                box.Focus();
                return false;
            }
            if (!double.TryParse(text, out value) || value <= 0)
            {
                MessageBox.Show($"请输入有效的{name}（正数）。", "输入错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                box.Focus();
                box.SelectAll();
                return false;
            }
            return true;
        }
    }
}
