using SecureShopContracts.BindingModels;
using SecureShopContracts.BusinessLogicsContracts;
using SecureShopContracts.SearchModels;
using SecureShopDataModels.Models;
using Microsoft.Extensions.Logging;


namespace SecureShopView
{
    public partial class FormSecure : Form
    {
        private readonly ILogger _logger;
        private readonly ISecureLogic _logic;
        private int? _id;
        private Dictionary<int, (IFacilitiesModel, int)> _SecureFacilitiess;
        public int Id { set { _id = value; } }

        public FormSecure(ILogger<FormSecure> logger, ISecureLogic logic)
        {
            InitializeComponent();
            _logger = logger;
            _logic = logic;
            _SecureFacilitiess = new Dictionary<int, (IFacilitiesModel, int)>();
        }

        private void FormSecure_Load(object sender, EventArgs e)
        {
            if (_id.HasValue)
            {
                _logger.LogInformation("Загрузка мороженого");
                try
                {
                    var view = _logic.ReadElement(new SecureSearchModel
                    {
                        Id = _id.Value
                    });
                    if (view != null)
                    {
                        textBoxName.Text = view.SecureName;
                        textBoxPrice.Text = view.Price.ToString();
                        _SecureFacilitiess = view.SecureFacilitiess ?? new Dictionary<int, (IFacilitiesModel, int)>();
                        LoadData();
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Ошибка загрузки мороженого");
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

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

        private void ButtonAdd_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormSecureFacilities));
            if (service is FormSecureFacilities form)
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    if (form.FacilitiesModel == null)
                    {
                        return;
                    }
                    _logger.LogInformation("Добавление новой добавки: {FacilitiesName} - {Count}", form.FacilitiesModel.FacilitiesName, form.Count);
                    if (_SecureFacilitiess.ContainsKey(form.Id))
                    {
                        _SecureFacilitiess[form.Id] = (form.FacilitiesModel, form.Count);
                    }
                    else
                    {
                        _SecureFacilitiess.Add(form.Id, (form.FacilitiesModel, form.Count));
                    }
                    LoadData();
                }
            }
        }

        private void ButtonUpd_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count == 1)
            {
                var service = Program.ServiceProvider?.GetService(typeof(FormSecureFacilities));
                if (service is FormSecureFacilities form)
                {
                    int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
                    form.Id = id;
                    form.Count = _SecureFacilitiess[id].Item2;
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        if (form.FacilitiesModel == null)
                        {
                            return;
                        }
                        _logger.LogInformation("Изменение добавки: {FacilitiesName} - {Count}", form.FacilitiesModel.FacilitiesName, form.Count);
                        _SecureFacilitiess[form.Id] = (form.FacilitiesModel, form.Count);
                        LoadData();
                    }
                }
            }
        }

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

        private void ButtonRef_Click(object sender, EventArgs e)
        {
            LoadData();
        }

        private void ButtonSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxName.Text))
            {
                MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(textBoxPrice.Text))
            {
                MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (_SecureFacilitiess == null || _SecureFacilitiess.Count == 0)
            {
                MessageBox.Show("Заполните добавки", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            _logger.LogInformation("Сохранение мороженого");
            try
            {
                var model = new SecureBindingModel
                {
                    Id = _id ?? 0,
                    SecureName = textBoxName.Text,
                    Price = Convert.ToDouble(textBoxPrice.Text),
                    SecureFacilitiess = _SecureFacilitiess
                };
                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 void ButtonCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

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

        private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}