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 LateOrdersPage : Page
    {
        private readonly DatabaseService _database = new DatabaseService();

        public LateOrdersPage()
        {
            InitializeComponent();
            LoadClients();
        }

        private void LoadClients()
        {
            try
            {
                DataTable table = _database.ExecuteSelect(
                    "SELECT client_id, last_name || ' ' || first_name AS client_name FROM clients ORDER BY last_name, first_name;");
                ClientsComboBox.ItemsSource = table.DefaultView;

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

        private void ShowLateOrdersButton_Click(object sender, RoutedEventArgs e)
        {
            if (ClientsComboBox.SelectedValue == null)
            {
                MessageBox.Show("Выберите клиента.", "Просроченные заказы", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            try
            {
                int clientId = Convert.ToInt32(ClientsComboBox.SelectedValue);
                DataTable table = _database.ExecuteSelect(
                    "SELECT * FROM fn_get_late_orders_by_client(@client_id);",
                    new Dictionary<string, object> { { "@client_id", clientId } });
                LateOrdersDataGrid.ItemsSource = table.DefaultView;
                CountTextBlock.Text = "Найдено записей: " + table.Rows.Count;

                if (table.Rows.Count == 0)
                {
                    MessageBox.Show("У выбранного клиента нет просроченных заказов.", "Просроченные заказы", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                ShowDatabaseError(ex);
            }
        }

        private void ShowOrderItemsButton_Click(object sender, RoutedEventArgs e)
        {
            DataRowView row = LateOrdersDataGrid.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 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);
        }
    }
}
