using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
using PrecastConcretePlantContracts.SearchModels;
using Microsoft.Extensions.Logging;
using PrecastConcretePlantBusinessLogic.BusinessLogic;

namespace PrecastConcretePlantView
{
    public partial class FormCreateOrder : Form
    {
        private readonly ILogger _logger;
        private readonly IReinforcedLogic _logicP;
        private readonly IOrderLogic _logicO;
        private readonly IClientLogic _clientLogic;

        public FormCreateOrder(ILogger<FormCreateOrder> logger, IReinforcedLogic logicP, IOrderLogic logicO, IClientLogic clientLogic)
        {
            InitializeComponent();
            _logger = logger;
            _logicP = logicP;
            _logicO = logicO;
            _clientLogic = clientLogic;
            LoadData();
        }

        private void LoadData()
        {
            _logger.LogInformation("Загрузка изделий для заказа");

            try
            {
                var list = _logicP.ReadList(null);
                if (list != null)
                {
                    ReinforcedComboBox.DisplayMember = "ReinforcedName";
                    ReinforcedComboBox.ValueMember = "Id";
                    ReinforcedComboBox.DataSource = list;
                    ReinforcedComboBox.SelectedItem = null;
                }
                var clients = _clientLogic.ReadList(null);
                if (clients != null)
                {
                    ClientСomboBox.DisplayMember = "clientFIO";
                    ClientСomboBox.ValueMember = "Id";
                    ClientСomboBox.DataSource = clients;
                    ClientСomboBox.SelectedItem = null;
                }

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

        private void CalcSum()
        {
            if (ReinforcedComboBox.SelectedValue != null && !string.IsNullOrEmpty(CountTextBox.Text))
            {
                try
                {
                    int id = Convert.ToInt32(ReinforcedComboBox.SelectedValue);

                    var reinforced = _logicP.ReadElement(new ReinforcedSearchModel
                    {
                        Id = id
                    });

                    int count = Convert.ToInt32(CountTextBox.Text);
                    SumTextBox.Text = Math.Round(count * (reinforced?.Price ?? 0), 2).ToString();
                    _logger.LogInformation("Расчет суммы заказа");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Ошибка расчета суммы заказа");
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void CountTextBox_TextChanged(object sender, EventArgs e)
        {
            CalcSum();
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(CountTextBox.Text))
            {
                MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ReinforcedComboBox.SelectedValue == null)
            {
                MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (ClientСomboBox.SelectedValue == null)
            {
                MessageBox.Show("Выберите клиента", "Ошибка",MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            _logger.LogInformation("Создание заказа");

            try
            {
                var operationResult = _logicO.CreateOrder(new OrderBindingModel
                {
                    ClientId = Convert.ToInt32(ClientСomboBox.SelectedValue),
                    ReinforcedId = Convert.ToInt32(ReinforcedComboBox.SelectedValue),
                    Count = Convert.ToInt32(CountTextBox.Text),
                    Sum = Convert.ToDouble(SumTextBox.Text)
                });

                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 void ReinforcedComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            CalcSum();
        }

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