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

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

        public OrdersPage()
        {
            InitializeComponent();
            ApplyRole();
            LoadOrders();
        }

        private void ApplyRole()
        {
            StatusComboBox.IsEnabled = UserSession.CanEditOrders();
            UpdateStatusButton.IsEnabled = UserSession.CanEditOrders();
        }

        private void LoadOrders()
        {
            try
            {
                DataTable table = _database.ExecuteSelect(
                    "SELECT * FROM v_orders_full_info ORDER BY order_date DESC;");
                OrdersDataGrid.ItemsSource = table.DefaultView;
                SelectedOrderTextBlock.Text = UserSession.CanEditOrders()
                    ? "Выберите заказ для изменения статуса"
                    : "Просмотр заказов";
            }
            catch (Exception ex)
            {
                ShowDatabaseError(ex);
            }
        }

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

        private void UpdateStatusButton_Click(object sender, RoutedEventArgs e)
        {
            if (!UserSession.CanEditOrders())
            {
                MessageBox.Show("У вас нет прав для изменения заказов.", "Заказы", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (_selectedOrderId == 0)
            {
                MessageBox.Show("Выберите заказ.", "Заказы", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            string status = GetSelectedStatus();
            if (string.IsNullOrWhiteSpace(status))
            {
                MessageBox.Show("Выберите статус.", "Заказы", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                _database.ExecuteNonQuery(
                    "UPDATE orders SET status = @status WHERE order_id = @order_id;",
                    new Dictionary<string, object>
                    {
                        { "@status", status },
                        { "@order_id", _selectedOrderId }
                    });
                LoadOrders();
            }
            catch (Exception ex)
            {
                ShowDatabaseError(ex);
            }
        }

        private void ShowItemsButton_Click(object sender, RoutedEventArgs e)
        {
            DataRowView row = OrdersDataGrid.SelectedItem as DataRowView;
            if (row == null)
            {
                MessageBox.Show("Выберите заказ.", "Заказы", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            int orderId = Convert.ToInt32(row["order_id"]);
            string orderInfo = "Заказ №" + orderId + ", клиент: " + Convert.ToString(row["client_name"]);
            NavigationService.Navigate(new OrderItemsPage(orderId, orderInfo));
        }

        private void OrdersDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView row = OrdersDataGrid.SelectedItem as DataRowView;
            if (row == null)
            {
                return;
            }

            _selectedOrderId = Convert.ToInt32(row["order_id"]);
            SelectedOrderTextBlock.Text = "Выбран заказ №" + _selectedOrderId + ", клиент: " + Convert.ToString(row["client_name"]);
            SelectStatus(Convert.ToString(row["status"]));
        }

        private string GetSelectedStatus()
        {
            ComboBoxItem item = StatusComboBox.SelectedItem as ComboBoxItem;
            return item == null ? null : Convert.ToString(item.Content);
        }

        private void SelectStatus(string status)
        {
            for (int i = 0; i < StatusComboBox.Items.Count; i++)
            {
                ComboBoxItem item = StatusComboBox.Items[i] as ComboBoxItem;
                if (item != null && Convert.ToString(item.Content) == status)
                {
                    StatusComboBox.SelectedIndex = i;
                    return;
                }
            }
        }

        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);
        }
    }
}
