using System.Collections.Generic;
using System.Linq;
using System.Windows;
using CtrEditor.FuncionesBase;

namespace CtrEditor.PopUps
{
    public partial class ColumnSelectionDialog : Window
    {
        private readonly List<string> _columnNames;
        public string SelectedSourceColumn { get; private set; }
        public string SelectedTargetColumn { get; private set; }
        public string SelectedSourceLanguage { get; private set; }
        public string SelectedTargetLanguage { get; private set; }

        private static readonly List<string> SupportedLanguages = Idiomas.GetLanguageList();

        private string _sourceColumnLabel = "Idioma 1";
        private string _targetColumnLabel = "Idioma 2";

        public string SourceColumnLabel
        {
            get => _sourceColumnLabel;
            set
            {
                _sourceColumnLabel = value;
                if (SourceColumnHeaderLabel != null)
                    SourceColumnHeaderLabel.Content = value;
            }
        }

        public string TargetColumnLabel
        {
            get => _targetColumnLabel;
            set
            {
                _targetColumnLabel = value;
                if (TargetColumnHeaderLabel != null)
                    TargetColumnHeaderLabel.Content = value;
            }
        }

        public ColumnSelectionDialog(List<string> columnNames)
        {
            InitializeComponent();
            _columnNames = columnNames;

            SourceColumnComboBox.ItemsSource = columnNames;
            TargetColumnComboBox.ItemsSource = columnNames;
            SourceLanguageComboBox.ItemsSource = SupportedLanguages;
            TargetLanguageComboBox.ItemsSource = SupportedLanguages;

            // Pre-select languages from saved settings
            PreSelectLanguages();

            // Set default labels
            SourceColumnHeaderLabel.Content = SourceColumnLabel;
            TargetColumnHeaderLabel.Content = TargetColumnLabel;
        }

        private void PreSelectLanguages()
        {
            // First try to load last used column pair
            var lastPair = EstadoPersistente.Instance.ColumnPairs.LastOrDefault();
            if (lastPair != null &&
                _columnNames.Contains(lastPair.SourceColumn) &&
                _columnNames.Contains(lastPair.TargetColumn))
            {
                SourceColumnComboBox.SelectedItem = lastPair.SourceColumn;
                TargetColumnComboBox.SelectedItem = lastPair.TargetColumn;
            }
            // If no previous pair exists or columns not found, try Descrip columns
            else
            {
                var descColumns = _columnNames.Where(c => c.Contains("Descrip")).ToList();
                if (descColumns.Any())
                {
                    SourceColumnComboBox.SelectedItem = descColumns.FirstOrDefault();
                    if (descColumns.Count > 1)
                    {
                        TargetColumnComboBox.SelectedItem = descColumns[1];
                    }
                }
            }

            // Load language mappings
            if (SourceColumnComboBox.SelectedItem != null)
            {
                var sourceMapping = EstadoPersistente.Instance.ColumnLanguages
                    .FirstOrDefault(m => m.ColumnName == SourceColumnComboBox.SelectedItem.ToString());
                if (sourceMapping != null)
                {
                    SourceLanguageComboBox.SelectedItem = sourceMapping.Language;
                }
            }

            if (TargetColumnComboBox.SelectedItem != null)
            {
                var targetMapping = EstadoPersistente.Instance.ColumnLanguages
                    .FirstOrDefault(m => m.ColumnName == TargetColumnComboBox.SelectedItem.ToString());
                if (targetMapping != null)
                {
                    TargetLanguageComboBox.SelectedItem = targetMapping.Language;
                }
            }
        }

        private void ColumnComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            var comboBox = sender as System.Windows.Controls.ComboBox;
            if (comboBox?.SelectedItem == null) return;

            var mapping = EstadoPersistente.Instance.ColumnLanguages
                .FirstOrDefault(m => m.ColumnName == comboBox.SelectedItem.ToString());

            if (mapping != null)
            {
                if (comboBox == SourceColumnComboBox)
                    SourceLanguageComboBox.SelectedItem = mapping.Language;
                else if (comboBox == TargetColumnComboBox)
                    TargetLanguageComboBox.SelectedItem = mapping.Language;
            }
        }

        private void OkButton_Click(object sender, RoutedEventArgs e)
        {
            if (SourceColumnComboBox.SelectedItem == null || 
                TargetColumnComboBox.SelectedItem == null ||
                SourceLanguageComboBox.SelectedItem == null ||
                TargetLanguageComboBox.SelectedItem == null)
            {
                MessageBox.Show("Please select both columns and their languages", 
                    "Selection Required", 
                    MessageBoxButton.OK, 
                    MessageBoxImage.Warning);
                return;
            }

            SelectedSourceColumn = SourceColumnComboBox.SelectedItem.ToString();
            SelectedTargetColumn = TargetColumnComboBox.SelectedItem.ToString();
            SelectedSourceLanguage = SourceLanguageComboBox.SelectedItem.ToString();
            SelectedTargetLanguage = TargetLanguageComboBox.SelectedItem.ToString();

            // Save language mappings
            SaveLanguageMappings();

            DialogResult = true;
            Close();
        }

        private void SaveLanguageMappings()
        {
            // Save language mappings
            var mappings = EstadoPersistente.Instance.ColumnLanguages;
            UpdateMapping(mappings, SelectedSourceColumn, SelectedSourceLanguage);
            UpdateMapping(mappings, SelectedTargetColumn, SelectedTargetLanguage);

            // Save column pair
            var columnPairs = EstadoPersistente.Instance.ColumnPairs;
            var lastPair = columnPairs.LastOrDefault();
            if (lastPair == null || 
                lastPair.SourceColumn != SelectedSourceColumn || 
                lastPair.TargetColumn != SelectedTargetColumn)
            {
                columnPairs.Add(new ColumnPairMapping 
                { 
                    SourceColumn = SelectedSourceColumn, 
                    TargetColumn = SelectedTargetColumn 
                });
            }

            EstadoPersistente.Instance.GuardarEstado();
        }

        private void UpdateMapping(List<ColumnLanguageMapping> mappings, string columnName, string language)
        {
            var existing = mappings.FirstOrDefault(m => m.ColumnName == columnName);
            if (existing != null)
                existing.Language = language;
            else
                mappings.Add(new ColumnLanguageMapping { ColumnName = columnName, Language = language });
        }

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