using SewingDressesContracts.BusinessLogicsContracts;
using SewingDressesContracts.ViewModels;
using SewingDressesDataModels.Models;
using SewingDressesContracts.SearchModels;
using Microsoft.Extensions.Logging;
using SewingDressesContracts.BindingModels;

namespace SewingDressesView
{
    public partial class DressForm : Form
    {
        private readonly ILogger _logger;
        private readonly IDressLogic _logic;
        private int? _id;
        private Dictionary<int, (IComponentModel, int)> _dressComponents;
        public int Id
        {
            set { _id = value; }
        }
        public DressForm(ILogger<DressForm> logger, IDressLogic logic)
        {
            InitializeComponent();
            _logger = logger;
            _logic = logic;
            _dressComponents = new Dictionary<int, (IComponentModel, int)>();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(DressComponentForm));
            if (service is DressComponentForm form)
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    if (form.ComponentModel == null)
                    {
                        return;
                    }
                    _logger.LogInformation("Add new component: {ComponentName} - {Count} ", form.ComponentModel.ComponentName, form.Count);
                    if (_dressComponents.ContainsKey(form.Id))
                    {
                        _dressComponents[form.Id] = (form.ComponentModel, form.Count);
                    }
                    else
                    {
                        _dressComponents.Add(form.Id, (form.ComponentModel, form.Count));
                    }
                    LoadData();
                }
            }

        }

        private void buttonChange_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count == 1)
            {
                var service =
               Program.ServiceProvider?.GetService(typeof(DressComponentForm));
                if (service is DressComponentForm form)
                {
                    int id =
                   Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
                    form.Id = id;
                    form.Count = _dressComponents[id].Item2;
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        if (form.ComponentModel == null)
                        {
                            return;
                        }
                        _logger.LogInformation("Update component: {ComponentName} - {Count}", form.ComponentModel.ComponentName, form.Count);
                        _dressComponents[form.Id] = (form.ComponentModel, form.Count);
                        LoadData();
                    }
                }
            }
        }

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

        private void buttonUpdate_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(textBoxCost.Text))
            {
                MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (_dressComponents == null || _dressComponents.Count == 0)
            {
                MessageBox.Show("Заполните компоненты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            _logger.LogInformation("Save dress");
            try
            {
                var model = new DressBindingModel
                {
                    Id = _id ?? 0,
                    DressName = textBoxName.Text,
                    Price = Convert.ToDouble(textBoxCost.Text),
                    DressComponents = _dressComponents
                };
                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, "Save dress error");
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        private void DressForm_Load(object sender, EventArgs e)
        {
            if (_id.HasValue)
            {
                _logger.LogInformation("Loading dress");
                try
                {
                    var view = _logic.ReadElement(new DressSearchModel
                    {
                        Id = _id.Value
                    });
                    if (view != null)
                    {
                        textBoxName.Text = view.DressName;
                        textBoxCost.Text = view.Price.ToString();
                        _dressComponents = view.DressComponents ?? new
                        Dictionary<int, (IComponentModel, int)>();
                        LoadData();
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Load dress error");
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                }
            }
        }
        private void LoadData()
        {
            _logger.LogInformation("Load dress component");
            try
            {
                if (_dressComponents != null)
                {
                    dataGridView.Rows.Clear();
                    foreach (var pc in _dressComponents)
                    {
                        dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.Item1.ComponentName, pc.Value.Item2 });
                    }
                    textBoxCost.Text = CalcPrice().ToString();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Load dress component Error");
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private double CalcPrice()
        {
            double price = 0;
            foreach (var elem in _dressComponents)
            {
                price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2);
            }
            return Math.Round(price * 1.1, 2);
        }
    }
}
