using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using RestaurantApp.DAL;
using RestaurantApp.Models;

namespace RestaurantApp
{
    public partial class OrderForm : Form
    {
        private OrderRepository repo = new OrderRepository();
        private OrderRepository dishRepo = new OrderRepository();
        private ClientRepository clientRepo = new ClientRepository();
        private EmployeeRepository empRepo = new EmployeeRepository();

        private Order currentOrder = null;

        public OrderForm()
        {
            InitializeComponent();
            LoadOrders();
            LoadDishes();

            cmbStatusFilter.SelectedIndex = 0;

            btnNewOrder.Click += BtnNewOrder_Click;
            btnRefreshOrders.Click += (s, e) => LoadOrders();
            btnOrderSearch.Click += (s, e) => LoadOrders();
            btnAddDish.Click += BtnAddDish_Click;
            btnAddItem.Click += (s, e) => groupAddItem.Visible = !groupAddItem.Visible;
            btnEditItem.Click += BtnEditItem_Click;
            btnRemoveItem.Click += BtnRemoveItem_Click;
            btnPay.Click += BtnPay_Click;
            btnCloseOrder.Click += BtnCloseOrder_Click;

            dgvOrders.SelectionChanged += DgvOrders_SelectionChanged;

            groupAddItem.Visible = false;
        }

        private void LoadOrders()
        {
            string status = cmbStatusFilter.SelectedIndex > 0 ? cmbStatusFilter.Text : "";

            // Если выбран "Все" - передаём пустую строку
            string statusParam = (status == "Все" || string.IsNullOrEmpty(status)) ? "" : status;

            dgvOrders.DataSource = repo.GetAll(statusParam, txtOrderSearch.Text);

            if (dgvOrders.Columns.Count > 0)
            {
                dgvOrders.Columns["OrderId"].HeaderText = "ID";
                dgvOrders.Columns["TableInfo"].HeaderText = "Стол";
                dgvOrders.Columns["EmployeeName"].HeaderText = "Официант";
                dgvOrders.Columns["ClientName"].HeaderText = "Клиент";
                dgvOrders.Columns["OpenedAt"].HeaderText = "Открыт";
                dgvOrders.Columns["ClosedAt"].HeaderText = "Закрыт";
                dgvOrders.Columns["Status"].HeaderText = "Статус";
                dgvOrders.Columns["TotalAmount"].HeaderText = "Сумма";

                if (dgvOrders.Columns["TableId"] != null)
                    dgvOrders.Columns["TableId"].Visible = false;
                if (dgvOrders.Columns["EmployeeId"] != null)
                    dgvOrders.Columns["EmployeeId"].Visible = false;
                if (dgvOrders.Columns["ClientId"] != null)
                    dgvOrders.Columns["ClientId"].Visible = false;
                if (dgvOrders.Columns["DiscountPct"] != null)
                    dgvOrders.Columns["DiscountPct"].Visible = false;
            }
        }

        private void LoadDishes()
        {
            var dishRepo = new DishRepository();
            var dishes = dishRepo.GetAll("", 0, true);
            cmbDish.DisplayMember = "Name";
            cmbDish.ValueMember = "DishId";
            cmbDish.DataSource = dishes;
        }

        private void LoadOrderItems(int orderId)
        {
            dgvOrderItems.DataSource = repo.GetItems(orderId);
            if (dgvOrderItems.Columns.Count > 0)
            {
                dgvOrderItems.Columns["DishName"].HeaderText = "Блюдо";
                dgvOrderItems.Columns["Quantity"].HeaderText = "Кол-во";
                dgvOrderItems.Columns["UnitPrice"].HeaderText = "Цена";
                dgvOrderItems.Columns["Total"].HeaderText = "Сумма";
                dgvOrderItems.Columns["Status"].HeaderText = "Статус";
                dgvOrderItems.Columns["Notes"].HeaderText = "Примечание";
            }

            // Обновляем общую сумму
            var order = repo.GetAll("", "").FirstOrDefault(o => o.OrderId == orderId);
            if (order != null)
                lblTotal.Text = $"Сумма: {order.TotalAmount} ₽";
        }

        private void UpdateOrderInfo()
        {
            if (currentOrder != null)
            {
                lblTable.Text = $"Стол: {currentOrder.TableInfo}";
                lblWaiter.Text = $"Официант: {currentOrder.EmployeeName}";
                lblOpenedAt.Text = $"Открыт: {currentOrder.OpenedAt:dd.MM.yyyy HH:mm}";
                lblClient.Text = $"Клиент: {(string.IsNullOrEmpty(currentOrder.ClientName) ? "Без клиента" : currentOrder.ClientName)}";
                lblStatus.Text = $"Статус: {currentOrder.Status}";
                lblTotal.Text = $"Сумма: {currentOrder.TotalAmount} ₽";

                bool isActive = currentOrder.Status != "closed" && currentOrder.Status != "cancelled";
                btnAddItem.Enabled = isActive;
                btnAddDish.Enabled = isActive;
                btnEditItem.Enabled = isActive;
                btnRemoveItem.Enabled = isActive;
                btnPay.Enabled = isActive && currentOrder.TotalAmount > 0;
                btnCloseOrder.Enabled = isActive;
            }
        }

        private void DgvOrders_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvOrders.CurrentRow != null)
            {
                currentOrder = (Order)dgvOrders.CurrentRow.DataBoundItem;
                UpdateOrderInfo();
                LoadOrderItems(currentOrder.OrderId);
            }
        }

        private void BtnNewOrder_Click(object sender, EventArgs e)
        {
            var form = new OrderEditForm();
            if (form.ShowDialog() == DialogResult.OK)
            {
                LoadOrders();
                // Выбираем созданный заказ (последний)
                if (dgvOrders.Rows.Count > 0)
                {
                    dgvOrders.ClearSelection();
                    dgvOrders.Rows[dgvOrders.Rows.Count - 1].Selected = true;
                }
            }
        }

        private void BtnAddDish_Click(object sender, EventArgs e)
        {
            if (currentOrder == null)
            {
                MessageBox.Show("Выберите заказ");
                return;
            }

            if (cmbDish.SelectedItem == null)
            {
                MessageBox.Show("Выберите блюдо");
                return;
            }

            var dish = (Dish)cmbDish.SelectedItem;

            var item = new OrderItem
            {
                OrderId = currentOrder.OrderId,
                DishId = dish.DishId,
                Quantity = (int)numQuantity.Value,
                UnitPrice = dish.Price,
                Notes = txtItemNotes.Text
            };

            try
            {
                repo.AddItem(item);
                LoadOrderItems(currentOrder.OrderId);
                LoadOrders(); // обновляем сумму в списке заказов
                txtItemNotes.Text = "";
                numQuantity.Value = 1;
                MessageBox.Show("Блюдо добавлено");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка: {ex.Message}");
            }
        }

        private void BtnEditItem_Click(object sender, EventArgs e)
        {
            if (dgvOrderItems.CurrentRow == null)
            {
                MessageBox.Show("Выберите позицию");
                return;
            }

            var item = (OrderItem)dgvOrderItems.CurrentRow.DataBoundItem;
            var form = new OrderItemEditForm(item);
            if (form.ShowDialog() == DialogResult.OK)
            {
                LoadOrderItems(currentOrder.OrderId);
                LoadOrders();
            }
        }

        private void BtnRemoveItem_Click(object sender, EventArgs e)
        {
            if (dgvOrderItems.CurrentRow == null)
            {
                MessageBox.Show("Выберите позицию");
                return;
            }

            var item = (OrderItem)dgvOrderItems.CurrentRow.DataBoundItem;
            if (MessageBox.Show($"Удалить {item.DishName}?", "Подтверждение",
                MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                repo.DeleteItem(item.OrderItemId);
                LoadOrderItems(currentOrder.OrderId);
                LoadOrders();
            }
        }

        private void BtnPay_Click(object sender, EventArgs e)
        {
            if (currentOrder == null) return;

            var form = new PaymentForm(currentOrder.OrderId, currentOrder.TotalAmount);
            if (form.ShowDialog() == DialogResult.OK)
            {
                LoadOrders();
                LoadOrderItems(currentOrder.OrderId);
                UpdateOrderInfo();
                MessageBox.Show("Оплата произведена");
            }
        }

        private void BtnCloseOrder_Click(object sender, EventArgs e)
        {
            if (currentOrder == null) return;

            if (MessageBox.Show($"Закрыть заказ #{currentOrder.OrderId}?", "Подтверждение",
                MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                repo.UpdateOrderStatus(currentOrder.OrderId, "closed");
                LoadOrders();
                LoadOrderItems(currentOrder.OrderId);
                UpdateOrderInfo();
            }
        }
    }
}