using Microsoft.EntityFrameworkCore;
using moduleExamen.Data;
using moduleExamen.Helpers;
using moduleExamen.Models;

namespace moduleExamen.Forms
{
    public partial class OrderListForm : Form
    {
        private List<Order> orders = new();

        public OrderListForm()
        {
            InitializeComponent();
            AppStyles.ApplyIcon(this);

            if (File.Exists(AppStyles.LogoPath))
                logoPictureBox.Image = Image.FromFile(AppStyles.LogoPath);

            addButton.Visible = SessionManager.IsAdmin;
            deleteButton.Visible = SessionManager.IsAdmin;

            LoadData();
        }

        private void HeaderPanel_Resize(object? sender, EventArgs e)
        {
            backButton.Location = new Point(headerPanel.ClientSize.Width - backButton.Width - 10, 10);
        }

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

        private void LoadData()
        {
            try
            {
                using var context = new SportShopContext();
                orders = context.Orders
                    .Include(o => o.FioNavigation)
                    .Include(o => o.IdStatusNavigation)
                    .Include(o => o.OrderItems)
                    .OrderByDescending(o => o.DataStart)
                    .ToList();

                orderGrid.Rows.Clear();
                foreach (var o in orders)
                {
                    var rowIndex = orderGrid.Rows.Add(
                        o.Idzakaz,
                        o.Article,
                        o.FioNavigation?.Fio ?? "—",
                        o.IdStatusNavigation?.Name ?? "—",
                        o.Adrec,
                        o.DataStart.ToString("dd.MM.yyyy"),
                        o.DateEnd?.ToString("dd.MM.yyyy") ?? "—",
                        o.OrderItems.Count
                    );
                    orderGrid.Rows[rowIndex].Tag = o;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки заказов:\n{ex.Message}", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void OrderGrid_CellDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || !SessionManager.IsAdmin) return;
            var order = orderGrid.Rows[e.RowIndex].Tag as Order;
            if (order == null) return;

            var editForm = new OrderEditForm(order);
            editForm.FormClosed += (_, _) => LoadData();
            editForm.Show();
        }

        private void AddButton_Click(object? sender, EventArgs e)
        {
            var editForm = new OrderEditForm(null);
            editForm.FormClosed += (_, _) => LoadData();
            editForm.Show();
        }

        private void DeleteButton_Click(object? sender, EventArgs e)
        {
            if (orderGrid.CurrentRow?.Tag is not Order order) return;

            var result = MessageBox.Show(
                $"Вы уверены, что хотите удалить заказ \"{order.Article}\"?\nЗарезервированные товары будут возвращены на склад.",
                "Подтверждение удаления", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result != DialogResult.Yes) return;

            try
            {
                using var context = new SportShopContext();
                var dbOrder = context.Orders
                    .Include(o => o.OrderItems)
                    .FirstOrDefault(o => o.Idzakaz == order.Idzakaz);

                if (dbOrder != null)
                {
                    context.OrderItems.RemoveRange(dbOrder.OrderItems);
                    context.Orders.Remove(dbOrder);
                    context.SaveChanges();
                }

                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка удаления:\n{ex.Message}", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void OrderListForm_Load(object sender, EventArgs e)
        {

        }
    }
}
