using Microsoft.Win32;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using WinForms = System.Windows.Forms;

namespace dealer
{
    public partial class AddVehicleWindow : Window
    {
        public string? SelectedPhotoPath { get; private set; }
        public System.Windows.Media.Color SelectedColor { get; private set; } = Colors.White;

        private DataManager dataManager;
        private Owner? selectedOwner;
        private bool isUpdatingOwnerComboBox = false;

        public AddVehicleWindow(DataManager dataManager)
        {
            InitializeComponent();

            this.dataManager = dataManager;
            LoadOwners();
        }

        private void LoadOwners()
        {
            OwnerComboBox.ItemsSource = dataManager.GetAllOwners().ToList();
        }

        private void OwnerComboBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (isUpdatingOwnerComboBox) return;

            var comboBox = sender as System.Windows.Controls.ComboBox;
            if (comboBox == null) return;

            string searchText = comboBox.Text;
            var filteredOwners = dataManager.SearchOwners(searchText).ToList();
            
            isUpdatingOwnerComboBox = true;
            comboBox.ItemsSource = filteredOwners;
            comboBox.IsDropDownOpen = true;
            isUpdatingOwnerComboBox = false;
        }

        private void OwnerComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            selectedOwner = OwnerComboBox.SelectedItem as Owner;
            UpdateSelectedOwnerInfo();
        }

        private void UpdateSelectedOwnerInfo()
        {
            if (selectedOwner != null)
            {
                var info = selectedOwner.CeleJmeno;
                if (!string.IsNullOrEmpty(selectedOwner.Telefon))
                    info += $"\nTel: {selectedOwner.Telefon}";
                if (!string.IsNullOrEmpty(selectedOwner.Email))
                    info += $"\nEmail: {selectedOwner.Email}";
                if (!string.IsNullOrEmpty(selectedOwner.Adresa))
                    info += $"\nAdresa: {selectedOwner.Adresa}";
                SelectedOwnerInfo.Text = info;
            }
            else
            {
                SelectedOwnerInfo.Text = "";
            }
        }

        private void AddNewOwnerButton_Click(object sender, RoutedEventArgs e)
        {
            var addOwnerWindow = new AddOwnerWindow(dataManager);
            addOwnerWindow.Owner = this;
            if (addOwnerWindow.ShowDialog() == true && addOwnerWindow.CreatedOwner != null)
            {
                LoadOwners();
                OwnerComboBox.SelectedItem = dataManager.GetAllOwners().FirstOrDefault(o => o.Id == addOwnerWindow.CreatedOwner.Id);
            }
            else
            {
                LoadOwners();
            }
        }

        private void SelectPhotoButton_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog
            {
                Title = "Vyberte fotografii vozidla",
                Filter = "Obrazky|*.jpg;*.jpeg;*.png;*.bmp;*.gif|Vsechny soubory|*.*",
                FilterIndex = 1
            };

            if (openFileDialog.ShowDialog() == true)
            {
                SelectedPhotoPath = openFileDialog.FileName;
                PhotoPathTextBlock.Text = SelectedPhotoPath;
            }
        }

        private void SelectColorButton_Click(object sender, RoutedEventArgs e)
        {
            WinForms.ColorDialog colorDialog = new WinForms.ColorDialog
            {
                AllowFullOpen = true,
                FullOpen = true
            };

            if (colorDialog.ShowDialog() == WinForms.DialogResult.OK)
            {
                SelectedColor = System.Windows.Media.Color.FromArgb(
                    colorDialog.Color.A,
                    colorDialog.Color.R,
                    colorDialog.Color.G,
                    colorDialog.Color.B);
                
                ColorPreviewBorder.Background = new SolidColorBrush(SelectedColor);
                ColorNameTextBlock.Text = $"#{SelectedColor.R:X2}{SelectedColor.G:X2}{SelectedColor.B:X2}";
                ColorNameTextBlock.FontStyle = FontStyles.Normal;
                ColorNameTextBlock.Foreground = System.Windows.Media.Brushes.Black;
            }
        }

        private void NumericOnly_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            e.Handled = !int.TryParse(e.Text, out _);
        }

        private void DecimalOnly_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            var textBox = sender as System.Windows.Controls.TextBox;
            string newText = textBox?.Text.Insert(textBox.SelectionStart, e.Text) ?? e.Text;
            e.Handled = !decimal.TryParse(newText, out _);
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(SpzTextBox.Text))
            {
                System.Windows.MessageBox.Show("Vyplnte SPZ.", "Upozorneni", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(ZnackaTextBox.Text))
            {
                System.Windows.MessageBox.Show("Vyplnte znacku.", "Upozorneni", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(ModelTextBox.Text))
            {
                System.Windows.MessageBox.Show("Vyplnte model.", "Upozorneni", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (string.IsNullOrWhiteSpace(YearTextBox.Text))
            {
                System.Windows.MessageBox.Show("Vyplnte rok vyroby.", "Upozorneni", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (PalivoComboBox.SelectedItem == null)
            {
                System.Windows.MessageBox.Show("Vyberte palivo.", "Upozorneni", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (!string.IsNullOrWhiteSpace(MileageTextBox.Text) && (!int.TryParse(MileageTextBox.Text, out int mileageVal) || mileageVal < 0))
            {
                System.Windows.MessageBox.Show("Najete km musi byt nezaporne cele cislo.", "Upozorneni", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (!string.IsNullOrWhiteSpace(PriceTextBox.Text) && (!decimal.TryParse(PriceTextBox.Text, out decimal priceVal) || priceVal < 0))
            {
                System.Windows.MessageBox.Show("Cena musi byt nezaporne cislo.", "Upozorneni", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            Image? image = null;
            if (!string.IsNullOrEmpty(SelectedPhotoPath) && File.Exists(SelectedPhotoPath))
            {
                byte[] imageBytes = File.ReadAllBytes(SelectedPhotoPath);
                image = new Image
                {
                    Data = Convert.ToBase64String(imageBytes),
                    FileName = System.IO.Path.GetFileName(SelectedPhotoPath),
                    ContentType = GetContentType(SelectedPhotoPath)
                };
                this.dataManager.AddImage(image);
            }

            var vehicle = new Vehicle
            {
                Spz = SpzTextBox.Text,
                Znacka = ZnackaTextBox.Text,
                Model = ModelTextBox.Text,
                Barva = $"#{SelectedColor.R:X2}{SelectedColor.G:X2}{SelectedColor.B:X2}",
                RokVyroby = int.TryParse(YearTextBox.Text, out int rok) ? rok : (int?)null,
                Palivo = (PalivoComboBox.SelectedItem as System.Windows.Controls.ComboBoxItem)?.Content?.ToString(),
                NajeteKm = int.TryParse(MileageTextBox.Text, out int km) ? km : (int?)null,
                Cena = decimal.TryParse(PriceTextBox.Text, out decimal cena) ? cena : (decimal?)null,
                FotografieId = image?.Id,
                Fotografie = image,
                VlastnikId = selectedOwner?.Id,
                Vlastnik = selectedOwner
            };

            this.dataManager.AddVehicle(vehicle);
            this.dataManager.Save();

            this.Close();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private static string GetContentType(string filePath)
        {
            var extension = System.IO.Path.GetExtension(filePath)?.ToLowerInvariant();
            return extension switch
            {
                ".jpg" or ".jpeg" => "image/jpeg",
                ".png" => "image/png",
                ".gif" => "image/gif",
                ".bmp" => "image/bmp",
                ".webp" => "image/webp",
                _ => "application/octet-stream"
            };
        }
    }
}