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

namespace TradeApp.WinForms.V08;

public sealed partial class OrderListForm : Form
{
    private readonly DatabaseClient _db;
    private readonly AppUser _user;
    private readonly BindingList<OrderView> _orders = [];

    public OrderListForm(DatabaseClient db, AppUser user)
    {
        _db = db;
        _user = user;
        InitializeComponent();
        addButton.Enabled = _user.CanEditOrders;
        editButton.Enabled = _user.CanEditOrders;
        deleteButton.Enabled = _user.CanEditOrders;
    }

    private void OrderListForm_Load(object? sender, EventArgs e)
    {
        ordersGrid.DataSource = _orders;
        Reload();
    }

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

    private void EditButton_Click(object? sender, EventArgs e) => EditOrder(SelectedOrder());

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

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

    private void OrdersGrid_CellDoubleClick(object? sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex < 0 || SelectedOrder() is not OrderView order)
        {
            return;
        }

        using var form = new OrderDetailsForm(order);
        form.ShowDialog(this);
    }

    private void Reload()
    {
        _orders.Clear();
        foreach (var order in _db.LoadOrders())
        {
            _orders.Add(order);
        }
    }

    private void DeleteSelected()
    {
        var order = SelectedOrder();
        if (order is null)
        {
            return;
        }

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

        _db.DeleteOrder(order.OrderId);
        Reload();
    }

    private OrderView? SelectedOrder()
    {
        return ordersGrid.CurrentRow?.DataBoundItem as OrderView;
    }

    private void EditOrder(OrderView? order)
    {
        using var form = new OrderEditForm(_db, order);
        if (form.ShowDialog(this) == DialogResult.OK)
        {
            Reload();
        }
    }
}