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

namespace moduleExamen.Forms
{
    public partial class ProductListForm : Form
    {
        private List<Product> allProducts = new();

        public ProductListForm()
        {
            InitializeComponent();

            var iconPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "icon.ico");
            if (File.Exists(iconPath))
                Icon = new Icon(iconPath);

            var logoPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "logo.png");
            if (File.Exists(logoPath))
                logoPictureBox.Image = Image.FromFile(logoPath);

            if (SessionManager.IsGuest)
                userLabel.Text = "Гость";
            else
                userLabel.Text = SessionManager.CurrentUser!.Fio + " (" + SessionManager.RoleName + ")";

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

            if (!SessionManager.IsManagerOrAdmin)
            {
                ordersButton.Location = new Point(10, 7);
                searchTextBox.Visible = false;
                searchLabel.Visible = false;
                manufacturerComboBox.Visible = false;
                manufacturerLabel.Visible = false;
                sortComboBox.Visible = false;
                sortLabel.Visible = false;
            }

            sortComboBox.SelectedIndex = 0;

            LoadData();
        }

        private void BackButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void SearchTextBox_TextChanged(object sender, EventArgs e)
        {
            ApplyFilters();
        }

        private void ManufacturerComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            ApplyFilters();
        }

        private void SortComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            ApplyFilters();
        }

        private void LoadData()
        {
            try
            {
                using var context = new SportShopContext();
                allProducts = context.Products
                    .Include(p => p.IdManufacturNavigation)
                    .Include(p => p.IdTipeProductNavigation)
                    .Include(p => p.IdEdNavigation)
                    .Include(p => p.IdSuplierNavigation)
                    .Include(p => p.OrderItems)
                    .ToList();

                manufacturerComboBox.Items.Clear();
                manufacturerComboBox.Items.Add("Все производители");
                var mans = context.Manufacts.OrderBy(m => m.Name).ToList();
                foreach (var m in mans)
                    manufacturerComboBox.Items.Add(m.Name);
                manufacturerComboBox.SelectedIndex = 0;

                ApplyFilters();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки данных: " + ex.Message);
            }
        }

        private void ApplyFilters()
        {
            var filtered = allProducts.AsEnumerable();

            if (SessionManager.IsManagerOrAdmin)
            {
                var searchText = searchTextBox.Text.Trim().ToLower();
                if (!string.IsNullOrEmpty(searchText))
                {
                    filtered = filtered.Where(p =>
                        p.Name.ToLower().Contains(searchText) ||
                        p.ProductContent.ToLower().Contains(searchText) ||
                        p.IdManufacturNavigation.Name.ToLower().Contains(searchText));
                }

                if (manufacturerComboBox.SelectedIndex > 0)
                {
                    var selected = manufacturerComboBox.SelectedItem.ToString();
                    filtered = filtered.Where(p => p.IdManufacturNavigation.Name == selected);
                }

                if (sortComboBox.SelectedIndex == 1)
                    filtered = filtered.OrderBy(p => p.PriceProduct);
                else if (sortComboBox.SelectedIndex == 2)
                    filtered = filtered.OrderByDescending(p => p.PriceProduct);
            }

            var list = filtered.ToList();
            countLabel.Text = list.Count + " из " + allProducts.Count;

            productGrid.Rows.Clear();
            foreach (var p in list)
            {
                Image photo = new Bitmap(60, 60);
                if (p.IdPhoto != null && p.IdPhoto.Length > 0)
                {
                    try
                    {
                        using var ms = new MemoryStream(p.IdPhoto);
                        photo = Image.FromStream(ms);
                    }
                    catch { }
                }

                var sale = (p.Sale.HasValue && p.Sale > 0) ? p.Sale + "%" : "—";
                var kolvo = p.KolVo.HasValue ? p.KolVo.ToString() : "0";

                var rowIndex = productGrid.Rows.Add(
                    photo,
                    p.Articl,
                    p.Name,
                    p.IdTipeProductNavigation != null ? p.IdTipeProductNavigation.Name : "",
                    p.IdManufacturNavigation != null ? p.IdManufacturNavigation.Name : "",
                    p.PriceProduct.ToString("N2") + " руб.",
                    sale,
                    kolvo,
                    p.ProductContent
                );
                productGrid.Rows[rowIndex].Tag = p;
            }
        }

        private void ProductGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || !SessionManager.IsAdmin) return;

            var product = productGrid.Rows[e.RowIndex].Tag as Product;
            if (product == null) return;

            var editForm = new ProductEditForm(product);
            editForm.FormClosed += (s, args) => LoadData();
            editForm.Show();
        }

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

        private void DeleteButton_Click(object sender, EventArgs e)
        {
            if (productGrid.CurrentRow == null) return;

            var product = productGrid.CurrentRow.Tag as Product;
            if (product == null) return;

            if (product.OrderItems.Count > 0)
            {
                MessageBox.Show("Невозможно удалить товар, он присутствует в заказе.");
                return;
            }

            var result = MessageBox.Show("Удалить товар \"" + product.Name + "\"?",
                "Подтверждение", MessageBoxButtons.YesNo);

            if (result != DialogResult.Yes) return;

            try
            {
                using var context = new SportShopContext();
                var dbProduct = context.Products.Find(product.Idproduct);
                if (dbProduct != null)
                {
                    context.Products.Remove(dbProduct);
                    context.SaveChanges();
                }
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка удаления: " + ex.Message);
            }
        }

        private void OrdersButton_Click(object sender, EventArgs e)
        {
            var orderForm = new OrderListForm();
            orderForm.Show();
        }
    }
}
