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

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

        public ClientsPage()
        {
            InitializeComponent();
            ApplyRole();
            LoadClients();
        }

        private void ApplyRole()
        {
            AddButton.IsEnabled = UserSession.CanEditClients();
            UpdateButton.IsEnabled = UserSession.CanEditClients();
            DeleteButton.IsEnabled = UserSession.CanDeleteClients();
        }

        private void LoadClients()
        {
            try
            {
                DataTable table = _database.ExecuteSelect(
                    "SELECT client_id, first_name, last_name, address, phone, email FROM clients ORDER BY client_id;");
                ClientsDataGrid.ItemsSource = table.DefaultView;
            }
            catch (Exception ex)
            {
                ShowDatabaseError(ex);
            }
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            string errorMessage;
            if (!ValidationHelper.ValidateClient(FirstNameTextBox.Text, LastNameTextBox.Text, AddressTextBox.Text, PhoneTextBox.Text, EmailTextBox.Text, out errorMessage))
            {
                MessageBox.Show(errorMessage, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                _database.ExecuteNonQuery(
                    "INSERT INTO clients(first_name, last_name, address, phone, email) VALUES (@first_name, @last_name, @address, @phone, @email);",
                    GetClientParameters());
                ClearForm();
                LoadClients();
            }
            catch (Exception ex)
            {
                ShowDatabaseError(ex);
            }
        }

        private void UpdateButton_Click(object sender, RoutedEventArgs e)
        {
            if (_selectedClientId == 0)
            {
                MessageBox.Show("Выберите клиента для изменения.", "Клиенты", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            string errorMessage;
            if (!ValidationHelper.ValidateClient(FirstNameTextBox.Text, LastNameTextBox.Text, AddressTextBox.Text, PhoneTextBox.Text, EmailTextBox.Text, out errorMessage))
            {
                MessageBox.Show(errorMessage, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                Dictionary<string, object> parameters = GetClientParameters();
                parameters.Add("@client_id", _selectedClientId);

                _database.ExecuteNonQuery(
                    "UPDATE clients SET first_name = @first_name, last_name = @last_name, address = @address, phone = @phone, email = @email WHERE client_id = @client_id;",
                    parameters);
                ClearForm();
                LoadClients();
            }
            catch (Exception ex)
            {
                ShowDatabaseError(ex);
            }
        }

        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            if (_selectedClientId == 0)
            {
                MessageBox.Show("Выберите клиента для удаления.", "Клиенты", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            if (MessageBox.Show("Удалить выбранного клиента?", "Подтверждение", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
            {
                return;
            }

            try
            {
                _database.ExecuteNonQuery(
                    "DELETE FROM clients WHERE client_id = @client_id;",
                    new Dictionary<string, object> { { "@client_id", _selectedClientId } });
                ClearForm();
                LoadClients();
            }
            catch (PostgresException ex)
            {
                if (ex.SqlState == "23503")
                {
                    MessageBox.Show("Невозможно удалить клиента, так как у него есть заказы.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

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

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

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

            _selectedClientId = Convert.ToInt32(row["client_id"]);
            FirstNameTextBox.Text = Convert.ToString(row["first_name"]);
            LastNameTextBox.Text = Convert.ToString(row["last_name"]);
            AddressTextBox.Text = Convert.ToString(row["address"]);
            PhoneTextBox.Text = Convert.ToString(row["phone"]);
            EmailTextBox.Text = Convert.ToString(row["email"]);
        }

        private Dictionary<string, object> GetClientParameters()
        {
            return new Dictionary<string, object>
            {
                { "@first_name", FirstNameTextBox.Text.Trim() },
                { "@last_name", LastNameTextBox.Text.Trim() },
                { "@address", AddressTextBox.Text.Trim() },
                { "@phone", string.IsNullOrWhiteSpace(PhoneTextBox.Text) ? null : PhoneTextBox.Text.Trim() },
                { "@email", string.IsNullOrWhiteSpace(EmailTextBox.Text) ? null : EmailTextBox.Text.Trim() }
            };
        }

        private void ClearForm()
        {
            _selectedClientId = 0;
            FirstNameTextBox.Clear();
            LastNameTextBox.Clear();
            AddressTextBox.Clear();
            PhoneTextBox.Clear();
            EmailTextBox.Clear();
        }

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