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();
        private List<Manufact> manufacturers = new();
        // Ссылка на открытую форму редактирования — не даём открыть две одновременно
        private ProductEditForm? openEditForm;

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

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

            userLabel.Text = SessionManager.IsGuest
                ? "Гость"
                : $"{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);
            }

            if (!SessionManager.IsManagerOrAdmin)
            {
                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();

                manufacturers = context.Manufacts.OrderBy(m => m.Name).ToList();

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

                ApplyFilters();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки данных:\n{ex.Message}", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        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 selectedManufacturer = manufacturerComboBox.SelectedItem?.ToString();
                    filtered = filtered.Where(p => p.IdManufacturNavigation.Name == selectedManufacturer);
                }

                filtered = sortComboBox.SelectedIndex switch
                {
                    1 => filtered.OrderBy(p => p.FinalPrice),
                    2 => filtered.OrderByDescending(p => p.FinalPrice),
                    _ => filtered
                };
            }

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

            productGrid.Rows.Clear();
            foreach (var p in list)
            {
                var photoImage = GetProductImage(p);
                var priceText = FormatPrice(p);

                var rowIndex = productGrid.Rows.Add(
                    photoImage,
                    p.Articl,
                    p.Name,
                    p.IdTipeProductNavigation?.Name ?? "",
                    p.IdManufacturNavigation?.Name ?? "",
                    priceText,
                    p.Sale.HasValue && p.Sale > 0 ? $"{p.Sale}%" : "—",
                    p.KolVo?.ToString() ?? "0",
                    p.ProductContent
                );
                // доступ при дабл клике
                productGrid.Rows[rowIndex].Tag = p;
            }
        }

        private static string FormatPrice(Product p)
        {
            if (p.Sale.HasValue && p.Sale > 0)
                return $"{p.PriceProduct:N2} → {p.FinalPrice:N2} руб.";
            return $"{p.PriceProduct:N2} руб.";
        }

        private static Image GetProductImage(Product p)
        {
            if (p.IdPhoto != null && p.IdPhoto.Length > 0)
            {
                try
                {
                    using var ms = new MemoryStream(p.IdPhoto);
                    return Image.FromStream(ms);
                }
                catch { }
            }

            if (File.Exists(AppStyles.PicturePath))
                return Image.FromFile(AppStyles.PicturePath);

            var bmp = new Bitmap(60, 60);
            using var g = Graphics.FromImage(bmp);
            g.Clear(Color.LightGray);
            g.DrawString("Нет фото", new Font("Segoe UI", 8f), Brushes.Gray, 5, 15);
            return bmp;
        }

        private void ProductGrid_CellFormatting(object? sender, DataGridViewCellFormattingEventArgs e)
        {
        }

        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;
            OpenEditForm(product);
        }

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

        private void OpenEditForm(Product? product)
        {
            if (openEditForm != null && !openEditForm.IsDisposed)
            {
                MessageBox.Show("Уже открыто окно редактирования. Закройте его перед открытием нового.",
                    "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                openEditForm.BringToFront();
                return;
            }

            openEditForm = new ProductEditForm(product);
            openEditForm.FormClosed += (_, _) =>
            {
                openEditForm = null;
                LoadData();
            };
            openEditForm.Show();
        }

        private void DeleteButton_Click(object? sender, EventArgs e)
        {
            if (productGrid.CurrentRow?.Tag is not Product product) return;

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

            var result = MessageBox.Show(
                $"Вы уверены, что хотите удалить товар \"{product.Name}\"?",
                "Подтверждение удаления", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            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($"Ошибка удаления:\n{ex.Message}", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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

        private void ProductListForm_Load(object sender, EventArgs e)
        {

        }
    }
}
