using moduleExamen.Data;
using moduleExamen.Helpers;
using moduleExamen.Models;

namespace moduleExamen.Forms
{
    public partial class ProductEditForm : Form
    {
        private readonly Product? editingProduct;
        private readonly bool isEditing;
        private byte[]? photoBytes;

        public ProductEditForm(Product? product)
        {
            InitializeComponent();
            AppStyles.ApplyIcon(this);

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

            editingProduct = product;
            isEditing = product != null;

            Text = isEditing ? "Sport Farm - Редактирование товара" : "Sport Farm - Добавление товара";
            idLabel.Text = isEditing ? $"ID товара: {product!.Idproduct}" : "ID: (новый)";

            LoadComboBoxData();

            if (isEditing)
                FillFields();
        }

        private void LoadComboBoxData()
        {
            try
            {
                using var context = new SportShopContext();

                var categories = context.TipeProducts.ToList();
                categoryComboBox.DataSource = categories;
                categoryComboBox.DisplayMember = "Name";
                categoryComboBox.ValueMember = "IdtipeProduct";

                var mans = context.Manufacts.ToList();
                manufacturerComboBox.DataSource = mans;
                manufacturerComboBox.DisplayMember = "Name";
                manufacturerComboBox.ValueMember = "Idmanufact";

                var sups = context.Supliers.ToList();
                supplierComboBox.DataSource = sups;
                supplierComboBox.DisplayMember = "Name";
                supplierComboBox.ValueMember = "Idsuplier";

                var eds = context.Eds.ToList();
                edComboBox.DataSource = eds;
                edComboBox.DisplayMember = "Name";
                edComboBox.ValueMember = "Ided";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки справочников:\n{ex.Message}", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FillFields()
        {
            if (editingProduct == null) return;

            articlTextBox.Text = editingProduct.Articl;
            articlTextBox.ReadOnly = true;
            nameTextBox.Text = editingProduct.Name;
            categoryComboBox.SelectedValue = editingProduct.IdTipeProduct;
            descriptionTextBox.Text = editingProduct.ProductContent;
            manufacturerComboBox.SelectedValue = editingProduct.IdManufactur;
            supplierComboBox.SelectedValue = editingProduct.IdSuplier;
            priceTextBox.Text = editingProduct.PriceProduct.ToString("F2");
            edComboBox.SelectedValue = editingProduct.IdEd;
            kolvoTextBox.Text = editingProduct.KolVo?.ToString() ?? "0";
            saleTextBox.Text = editingProduct.Sale?.ToString() ?? "0";

            photoBytes = editingProduct.IdPhoto;
            if (photoBytes != null && photoBytes.Length > 0)
            {
                try
                {
                    using var ms = new MemoryStream(photoBytes);
                    photoPictureBox.Image = Image.FromStream(ms);
                }
                catch { }
            }
        }

        private void ChangePhoto_Click(object? sender, EventArgs e)
        {
            using var dialog = new OpenFileDialog
            {
                Title = "Выберите изображение",
                Filter = "Изображения (*.jpg;*.png)|*.jpg;*.png"
            };

            if (dialog.ShowDialog() != DialogResult.OK) return;

            try
            {
                using var original = Image.FromFile(dialog.FileName);
                var resized = new Bitmap(original, new Size(
                    Math.Min(original.Width, 350),
                    Math.Min(original.Height, 350)));

                using var ms = new MemoryStream();
                resized.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                photoBytes = ms.ToArray();

                photoPictureBox.Image = resized;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки изображения:\n{ex.Message}", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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

        private void SaveButton_Click(object? sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(nameTextBox.Text))
            {
                MessageBox.Show("Введите наименование товара.");
                return;
            }

            if (!decimal.TryParse(priceTextBox.Text, out var price))
            {
                MessageBox.Show("Введите корректную цену.");
                return;
            }

            if (!int.TryParse(kolvoTextBox.Text, out var kolvo))
            {
                MessageBox.Show("Введите корректное количество.");
                return;
            }

            if (!int.TryParse(saleTextBox.Text, out var sale))
            {
                MessageBox.Show("Введите корректную скидку.");
                return;
            }

            try
            {
                using var context = new SportShopContext();

                Product product;
                if (isEditing)
                {
                    product = context.Products.Find(editingProduct!.Idproduct)!;
                }
                else
                {
                    product = new Product();
                    product.Articl = articlTextBox.Text.Trim();
                    context.Products.Add(product);
                }

                product.Name = nameTextBox.Text.Trim();
                product.IdTipeProduct = (int)categoryComboBox.SelectedValue;
                product.ProductContent = descriptionTextBox.Text.Trim();
                product.IdManufactur = (int)manufacturerComboBox.SelectedValue;
                product.IdSuplier = (int)supplierComboBox.SelectedValue;
                product.PriceProduct = price;
                product.IdEd = (int)edComboBox.SelectedValue;
                product.KolVo = kolvo;
                product.Sale = sale;
                product.IdPhoto = photoBytes;

                context.SaveChanges();

                MessageBox.Show("Данные сохранены.", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка сохранения:\n{ex.Message}", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ProductEditForm_Load(object sender, EventArgs e)
        {

        }
    }
}
