using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace TradeApp.WinForms.V08;

public sealed partial class ProductListForm : Form
{
    private readonly DatabaseClient _db;
    private readonly AppUser _user;
    private readonly BindingList<ProductView> _products = [];
    private ProductEditForm? _productEditForm;

    public ProductListForm(DatabaseClient db, AppUser user)
    {
        _db = db;
        _user = user;
        InitializeComponent();
        Text = $"{AppearanceSettings.ProductListTitle} - {_user.FullName} ({_user.RoleName})";
        userInfoLabel.Text = $"Пользователь: {_user.FullName}\r\nРоль: {_user.RoleName}";
        searchTextBox.Enabled = _user.CanSearch;
        searchFieldComboBox.Enabled = _user.CanSearch;
        addButton.Enabled = _user.CanEditProducts;
        editButton.Enabled = _user.CanEditProducts;
        deleteButton.Enabled = _user.CanEditProducts;
        ordersButton.Enabled = _user.CanViewOrders;
    }

    private void ProductListForm_Load(object? sender, EventArgs e)
    {
        AsyncTaskDataGrid.DataSource = _products;
        LoadFilters();
        Reload();
    }

    private void SearchTextBox_TextChanged(object? sender, EventArgs e) => Reload();

    private void SearchFieldComboBox_SelectedIndexChanged(object? sender, EventArgs e) => Reload();

    private void SupplierComboBox_SelectedIndexChanged(object? sender, EventArgs e) => Reload();

    private void SortComboBox_SelectedIndexChanged(object? sender, EventArgs e) => Reload();

    private void AddButton_Click(object? sender, EventArgs e) => EditProduct(null);

    private void EditButton_Click(object? sender, EventArgs e) => EditProduct(SelectedProduct());

    private void DeleteButton_Click(object? sender, EventArgs e) => DeleteSelected();

    private void OrdersButton_Click(object? sender, EventArgs e)
    {
        using var form = new OrderListForm(_db, _user);
        form.ShowDialog(this);
    }

    private void ExitButton_Click(object? sender, EventArgs e) => Close();

    private void ProductsGrid_RowPrePaint(object? sender, DataGridViewRowPrePaintEventArgs e) => PaintRow(e.RowIndex);

    private void ProductsGrid_CellDoubleClick(object? sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex < 0 || SelectedProduct() is not ProductView product)
        {
            return;
        }

        using var form = new ProductDetailsForm(product);
        form.ShowDialog(this);
    }

    private void LoadFilters()
    {
        supplierComboBox.Items.Clear();
        supplierComboBox.Items.Add("Все поставщики");
        foreach (var supplier in _db.LoadSuppliers())
        {
            supplierComboBox.Items.Add(supplier);
        }

        supplierComboBox.SelectedIndex = 0;
    }

    private void Reload()
    {
        if (searchFieldComboBox.SelectedItem is null || supplierComboBox.SelectedItem is null || sortComboBox.SelectedItem is null)
        {
            return;
        }

        _products.Clear();
        foreach (var product in _db.LoadProducts(searchTextBox.Text.Trim(), searchFieldComboBox.Text, supplierComboBox.Text, sortComboBox.Text))
        {
            _products.Add(product);
        }

        countStatusLabel.Text = $"Товаров: {_products.Count}";
    }

    private ProductView? SelectedProduct()
    {
        return AsyncTaskDataGrid.CurrentRow?.DataBoundItem as ProductView;
    }

    private void EditProduct(ProductView? product)
    {
        if (_productEditForm is not null && !_productEditForm.IsDisposed)
        {
            _productEditForm.Activate();
            return;
        }

        using var form = new ProductEditForm(_db, product);
        _productEditForm = form;
        try
        {
            if (form.ShowDialog(this) == DialogResult.OK)
            {
                LoadFilters();
                Reload();
            }
        }
        finally
        {
            _productEditForm = null;
        }
    }

    private void DeleteSelected()
    {
        var product = SelectedProduct();
        if (product is null)
        {
            return;
        }

        if (_db.ProductIsUsedInOrders(product.ProductId))
        {
            MessageBox.Show("Товар присутствует в заказе, удалить его нельзя.", "Удаление запрещено", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        if (MessageBox.Show("Удалить выбранный товар?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
        {
            return;
        }

        _db.DeleteProduct(product.ProductId);
        Reload();
    }

    private void PaintRow(int rowIndex)
    {
        if (rowIndex < 0 || rowIndex >= AsyncTaskDataGrid.Rows.Count)
        {
            return;
        }

        if (AsyncTaskDataGrid.Rows[rowIndex].DataBoundItem is not ProductView product)
        {
            return;
        }

        AsyncTaskDataGrid.Rows[rowIndex].DefaultCellStyle.BackColor =
            product.StockQuantity == 0 ? Color.LightBlue :
            product.DiscountPercent > AppearanceSettings.DiscountHighlightThresholdPercent ? ColorTranslator.FromHtml(AppearanceSettings.DiscountHighlightColor) :
            Color.White;
    }

}