using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using ComputerShopWpf.Services;
using Npgsql;

namespace ComputerShopWpf.Views
{
    public partial class ProductsPage : Page
    {
        private readonly DatabaseService _database = new DatabaseService();

        public ProductsPage()
        {
            InitializeComponent();
            ApplyRole();
            LoadSuppliers();
            LoadProducts();
        }

        private void ApplyRole()
        {
            bool canEdit = UserSession.CanEditProducts();
            ProductNameTextBox.IsEnabled = canEdit;
            CategoryTextBox.IsEnabled = canEdit;
            PriceTextBox.IsEnabled = canEdit;
            StockTextBox.IsEnabled = canEdit;
            SuppliersComboBox.IsEnabled = canEdit;
            AddProductButton.IsEnabled = canEdit;
        }

        private void LoadProducts()
        {
            try
            {
                DataTable table = _database.ExecuteSelect(
                    "SELECT * FROM v_products_dictionary ORDER BY product_name;");
                ProductsDataGrid.ItemsSource = table.DefaultView;
            }
            catch (Exception ex)
            {
                ShowDatabaseError(ex);
            }
        }

        private void LoadSuppliers()
        {
            try
            {
                DataTable table = _database.ExecuteSelect(
                    "SELECT supplier_id, company_name FROM suppliers ORDER BY company_name;");
                SuppliersComboBox.ItemsSource = table.DefaultView;

                if (SuppliersComboBox.Items.Count > 0)
                {
                    SuppliersComboBox.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                ShowDatabaseError(ex);
            }
        }

        private void AddProductButton_Click(object sender, RoutedEventArgs e)
        {
            if (!UserSession.CanEditProducts())
            {
                MessageBox.Show("У вас нет прав для добавления товаров.", "Товары", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            string productName = ProductNameTextBox.Text.Trim();
            string category = CategoryTextBox.Text.Trim();

            if (string.IsNullOrWhiteSpace(productName) || string.IsNullOrWhiteSpace(category))
            {
                MessageBox.Show("Заполните название товара и категорию.", "Товары", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            decimal price;
            if (!TryParseDecimal(PriceTextBox.Text, out price) || price < 0)
            {
                MessageBox.Show("Цена должна быть числом не меньше нуля.", "Товары", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            int stockQuantity;
            if (!int.TryParse(StockTextBox.Text.Trim(), out stockQuantity) || stockQuantity < 0)
            {
                MessageBox.Show("Остаток должен быть целым числом не меньше нуля.", "Товары", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (SuppliersComboBox.SelectedValue == null)
            {
                MessageBox.Show("Выберите поставщика.", "Товары", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                _database.ExecuteNonQuery(
                    "INSERT INTO products(product_name, price, stock_quantity, category, supplier_id) VALUES (@product_name, @price, @stock_quantity, @category, @supplier_id);",
                    new Dictionary<string, object>
                    {
                        { "@product_name", productName },
                        { "@price", price },
                        { "@stock_quantity", stockQuantity },
                        { "@category", category },
                        { "@supplier_id", Convert.ToInt32(SuppliersComboBox.SelectedValue) }
                    });

                ClearForm();
                LoadProducts();
            }
            catch (Exception ex)
            {
                ShowDatabaseError(ex);
            }
        }

        private void RefreshButton_Click(object sender, RoutedEventArgs e)
        {
            LoadSuppliers();
            LoadProducts();
        }

        private void ClearForm()
        {
            ProductNameTextBox.Clear();
            CategoryTextBox.Clear();
            PriceTextBox.Clear();
            StockTextBox.Clear();

            if (SuppliersComboBox.Items.Count > 0)
            {
                SuppliersComboBox.SelectedIndex = 0;
            }
        }

        private static bool TryParseDecimal(string value, out decimal result)
        {
            value = (value ?? string.Empty).Trim().Replace(',', '.');
            return decimal.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out result);
        }

        private static void ShowDatabaseError(Exception ex)
        {
            PostgresException postgresException = ex as PostgresException;
            if (postgresException != null)
            {
                MessageBox.Show("Ошибка PostgreSQL: " + postgresException.MessageText, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            NpgsqlException npgsqlException = ex as NpgsqlException;
            if (npgsqlException != null)
            {
                MessageBox.Show("Ошибка подключения к базе данных: " + npgsqlException.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            MessageBox.Show("Ошибка: " + ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }
}
