using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.DI;
using BarContracts.SearchModels;
using BarDataModels.Models;
using Microsoft.Extensions.Logging;

namespace BarView.Forms
{
    public partial class FormCocktail : Form
    {
        private readonly ILogger _logger;

        private readonly ICocktailLogic _logic;

        private int? _id;

        private Dictionary<int, (IComponentModel, int)> _cocktailComponents;

        public int Id { set { _id = value; } }

        public FormCocktail(ILogger<FormCocktail> Logger, ICocktailLogic Logic)
        {
            InitializeComponent();
            _logger = Logger;
            _logic = Logic;
            _cocktailComponents = new Dictionary<int, (IComponentModel, int)>();
        }

        private void FormCocktail_Load(object sender, EventArgs e)
        {
            if (_id.HasValue)
            {
                _logger.LogInformation("Загрузка коктейльа");

                try
                {
                    var View = _logic.ReadElement(new CocktailSearchModel
                    {
                        Id = _id.Value
                    });

                    if (View != null)
                    {
                        NameTextBox.Text = View.CocktailName;
                        PriceTextBox.Text = View.Price.ToString();

                        _cocktailComponents = View.CocktailComponents ?? new Dictionary<int, (IComponentModel, int)>();
                        LoadData();
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Ошибка загрузки коктейльа");
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void LoadData()
        {
            _logger.LogInformation("Загрузка компонентов коктейльа");

            try
            {
                if (_cocktailComponents != null)
                {
                    DataGridView.Rows.Clear();
                    foreach (var Comp in _cocktailComponents)
                    {
                        DataGridView.Rows.Add(new object[] { Comp.Key, Comp.Value.Item1.ComponentName, Comp.Value.Item2 });
                    }

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

        private void AddButton_Click(object sender, EventArgs e)
        {
            var Service = DependencyManager.Instance.Resolve<FormCocktailComponent>();

            if (Service is FormCocktailComponent Form)
            {
                if (Form.ShowDialog() == DialogResult.OK)
                {
                    if (Form.ComponentModel == null)
                    {
                        return;
                    }

                    _logger.LogInformation("Добавление нового компонента: {ComponentName} - {Count}", Form.ComponentModel.ComponentName, Form.Count);

                    if (_cocktailComponents.ContainsKey(Form.Id))
                    {
                        _cocktailComponents[Form.Id] = (Form.ComponentModel, Form.Count);
                    }
                    else
                    {
                        _cocktailComponents.Add(Form.Id, (Form.ComponentModel, Form.Count));
                    }

                    LoadData();
                }
            }
        }

        private void UpdateButton_Click(object sender, EventArgs e)
        {
            if (DataGridView.SelectedRows.Count == 1)
            {
                var service = DependencyManager.Instance.Resolve<FormCocktailComponent>();
                if (service is FormCocktailComponent Form)
                {
                    int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells[0].Value);
                    Form.Id = id;
                    Form.Count = _cocktailComponents[id].Item2;

                    if (Form.ShowDialog() == DialogResult.OK)
                    {
                        if (Form.ComponentModel == null)
                        {
                            return;
                        }

                        _logger.LogInformation("Изменение компонента: {ComponentName} - {Count}", Form.ComponentModel.ComponentName, Form.Count);
                        _cocktailComponents[Form.Id] = (Form.ComponentModel, Form.Count);

                        LoadData();
                    }
                }
            }
        }

        private void DeleteButton_Click(object sender, EventArgs e)
        {
            if (DataGridView.SelectedRows.Count == 1)
            {
                if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    try
                    {
                        _logger.LogInformation("Удаление компонента: {ComponentName} - {Count}", DataGridView.SelectedRows[0].Cells[1].Value,
                            DataGridView.SelectedRows[0].Cells[2].Value);

                        _cocktailComponents?.Remove(Convert.ToInt32(DataGridView.SelectedRows[0].Cells[0].Value));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    LoadData();
                }
            }
        }

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

        private void SaveButton_Click(object sender, EventArgs e)
        {

            if (string.IsNullOrEmpty(NameTextBox.Text))
            {
                MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(PriceTextBox.Text))
            {
                MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (_cocktailComponents == null || _cocktailComponents.Count == 0)
            {
                MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            _logger.LogInformation("Сохранение коктейльа");

            try
            {
                var Мodel = new CocktailBindingModel
                {
                    Id = _id ?? 0,
                    CocktailName = NameTextBox.Text,
                    Price = Convert.ToDouble(PriceTextBox.Text),
                    CocktailComponents = _cocktailComponents
                };

                var OperationResult = _id.HasValue ? _logic.Update(Мodel) : _logic.Create(Мodel);

                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 _cocktailComponents)
            {
                Price += ((Elem.Value.Item1?.Cost ?? 0) * Elem.Value.Item2);
            }

            return Math.Round(Price * 1.1, 2);
        }
    }
}
