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

        public UsersPage()
        {
            InitializeComponent();
            RoleComboBox.SelectedIndex = 2;

            if (!UserSession.CanManageUsers())
            {
                IsEnabled = false;
                MessageBox.Show("У вас нет прав для управления пользователями.", "Пользователи", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            LoadUsers();
        }

        private void LoadUsers()
        {
            try
            {
                DataTable table = _database.ExecuteSelect(
                    "SELECT user_id, login, role_name FROM app_users ORDER BY user_id;");
                UsersDataGrid.ItemsSource = table.DefaultView;
            }
            catch (Exception ex)
            {
                ShowDatabaseError(ex);
            }
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            string roleName = GetSelectedRole();
            if (string.IsNullOrWhiteSpace(LoginTextBox.Text) || string.IsNullOrWhiteSpace(NewPasswordBox.Password) || string.IsNullOrWhiteSpace(roleName))
            {
                MessageBox.Show("Введите логин, пароль и роль.", "Пользователи", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                _database.ExecuteNonQuery(
                    "INSERT INTO app_users(login, password_hash, role_name) VALUES (@login, @password_hash, @role_name);",
                    new Dictionary<string, object>
                    {
                        { "@login", LoginTextBox.Text.Trim() },
                        { "@password_hash", PasswordHasher.ComputeSha256Hash(NewPasswordBox.Password) },
                        { "@role_name", roleName }
                    });
                ClearForm();
                LoadUsers();
            }
            catch (Exception ex)
            {
                ShowDatabaseError(ex);
            }
        }

        private void UpdateRoleButton_Click(object sender, RoutedEventArgs e)
        {
            if (_selectedUserId == 0)
            {
                MessageBox.Show("Выберите пользователя.", "Пользователи", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            string roleName = GetSelectedRole();
            if (string.IsNullOrWhiteSpace(roleName))
            {
                MessageBox.Show("Выберите роль.", "Пользователи", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                _database.ExecuteNonQuery(
                    "UPDATE app_users SET role_name = @role_name WHERE user_id = @user_id;",
                    new Dictionary<string, object>
                    {
                        { "@role_name", roleName },
                        { "@user_id", _selectedUserId }
                    });
                LoadUsers();
            }
            catch (Exception ex)
            {
                ShowDatabaseError(ex);
            }
        }

        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            if (_selectedUserId == 0)
            {
                MessageBox.Show("Выберите пользователя.", "Пользователи", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            if (_selectedUserId == UserSession.UserId)
            {
                MessageBox.Show("Нельзя удалить текущего пользователя.", "Пользователи", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

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

            try
            {
                _database.ExecuteNonQuery(
                    "DELETE FROM app_users WHERE user_id = @user_id;",
                    new Dictionary<string, object> { { "@user_id", _selectedUserId } });
                ClearForm();
                LoadUsers();
            }
            catch (Exception ex)
            {
                ShowDatabaseError(ex);
            }
        }

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

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

            _selectedUserId = Convert.ToInt32(row["user_id"]);
            LoginTextBox.Text = Convert.ToString(row["login"]);
            SelectRole(Convert.ToString(row["role_name"]));
        }

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

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

        private void ClearForm()
        {
            _selectedUserId = 0;
            LoginTextBox.Clear();
            NewPasswordBox.Clear();
            RoleComboBox.SelectedIndex = 2;
        }

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