using Contracts.BindingModels;
using Contracts.BusinessLogicContracts;
using Contracts.SearchModels;
using DataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp
{
    public partial class FormSupply : Form
    {
        private readonly ILogger _logger;
        private readonly ISupplyLogic _logic;
        private readonly ISupplierLogic _supplierLogic;
        private Guid? _id;
        private Dictionary<Guid, (IProduct, int)> _supplyProducts;
        public Guid Id { set { _id = value; } }
        public FormSupply(ILogger<FormSupply> logger, ISupplyLogic logic, ISupplierLogic supplierLogic)
        {
            InitializeComponent();
            _logger = logger;
            _logic = logic;
            _supplyProducts = new Dictionary<Guid, (IProduct, int)>();
            _supplierLogic = supplierLogic;
        }
        private void FormSupply_Load(object sender, EventArgs e)
        {
            if (_id.HasValue)
            {
                _logger.LogInformation("Загрузка изделия");
                try
                {
                    var view = _logic.ReadElement(new SupplySearchModel
                    {
                        Id = _id.Value
                    });
                    if (view != null)
                    {
                        textBoxName.Text = view.Name;
                        _supplyProducts = view.Products ?? new Dictionary<Guid, (IProduct, int)>();
                        LoadData();
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Ошибка загрузки изделия");
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            try
            {
                var list = _supplierLogic.ReadList(null);
                if (list != null)
                {
                    comboBoxSupplier.DisplayMember = "Name";
                    comboBoxSupplier.ValueMember = "Id";
                    comboBoxSupplier.DataSource = list;
                    comboBoxSupplier.SelectedItem = null;
                }

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Ошибка загрузки списка клиентов");
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadData()
        {
            _logger.LogInformation("Загрузка компонент изделия");
            try
            {
                if (_supplyProducts != null)
                {
                    dataGridView.Rows.Clear();
                    foreach (var pc in _supplyProducts)
                    {
                        dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.Item1.Name, pc.Value.Item2 });
                    }
                    textBoxPrice.Text = CalcPrice().ToString();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Ошибка загрузки компонент изделия");
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
               MessageBoxIcon.Error);
            }
        }

        private void buttonAddProduct_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormSupplyProduct));
            if (service is FormSupplyProduct form)
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    if (form.ProductModel == null)
                    {
                        return;
                    }
                    _logger.LogInformation("Добавление нового компонента");
                    if (_supplyProducts.ContainsKey(form.Id))
                    {
                        _supplyProducts[form.Id] = (form.ProductModel, form.Count);
                    }
                    else
                    {
                        _supplyProducts.Add(form.Id, (form.ProductModel, form.Count));
                    }
                    LoadData();
                }
            }
        }

        private void buttonUpdateProduct_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count == 1)
            {
                var service =
               Program.ServiceProvider?.GetService(typeof(FormSupplyProduct));
                if (service is FormSupplyProduct form)
                {
                    Guid id = (Guid)dataGridView.SelectedRows[0].Cells[0].Value;
                    form.Id = id;
                    form.Count = _supplyProducts[id].Item2;
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        if (form.ProductModel == null)
                        {
                            return;
                        }
                        _logger.LogInformation("Изменение компонента");
                        _supplyProducts[form.Id] = (form.ProductModel, form.Count);
                        LoadData();
                    }
                }
            }
        }

        private void buttonDeleteProduct_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count == 1)
            {
                if (MessageBox.Show("Удалить запись?", "Вопрос",
               MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    try
                    {
                        _logger.LogInformation("Удаление компонента");
                        _supplyProducts?.Remove((Guid)dataGridView.SelectedRows[0].Cells[0].Value);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    LoadData();
                }
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxName.Text))
            {
                MessageBox.Show("Заполните информацию", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (_supplyProducts == null || _supplyProducts.Count == 0)
            {
                MessageBox.Show("Заполните товары", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            _logger.LogInformation("Сохранение изделия");
            try
            {
                var model = new SupplyBindingModel
                {
                    Id = _id ?? Guid.NewGuid(),
                    Name = textBoxName.Text,
                    Date = DateTime.UtcNow,
                    Price = Convert.ToDouble(textBoxPrice.Text),
                    SupplierId = (Guid)comboBoxSupplier.SelectedValue,
                    SupplyProducts = _supplyProducts,
                    
                };
                var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
                if (!operationResult)
                {
                    throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
                }
                MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Ошибка сохранения изделия"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private double CalcPrice()
        {
            double price = 0;
            foreach (var elem in _supplyProducts)
            {
                price += ((elem.Value.Item1?.Price ?? 0) * elem.Value.Item2);
            }
            return Math.Round(price * 1.1, 2);
        }
    }
}
