using PlumbingRepairContracts.BindingModels;
using PlumbingRepairContracts.BusinessLogicsContracts;
using PlumbingRepairContracts.SearchModels;
using Microsoft.Extensions.Logging;

namespace PlumbingRepair
{
    public partial class FormCreateOrder : Form
    {
        private readonly ILogger _logger;
        private readonly IWorkLogic _logicW;
        private readonly IOrderLogic _logicO;
        private readonly IClientLogic _logicC;

        public FormCreateOrder(ILogger<FormCreateOrder> logger, IWorkLogic logicW, IOrderLogic logicO, IClientLogic logicC)
        {
            InitializeComponent();
            _logger = logger;
            _logicW = logicW;
            _logicO = logicO;
            _logicC = logicC;
            LoadData();
        }

        private void LoadData()
        {
            _logger.LogInformation("Загрузка Работ для заказа");

            try
            {
                var list = _logicW.ReadList(null);
                var listClients = _logicC.ReadList(null);
                if (list != null)
                {
                    WorkComboBox.DisplayMember = "WorkName";
                    WorkComboBox.ValueMember = "Id";
                    WorkComboBox.DataSource = list;
                    WorkComboBox.SelectedItem = null;
                }
                if(listClients != null)
                {
                    comboBoxClient.DisplayMember = "ClientFIO";
                    comboBoxClient.ValueMember = "Id";
                    comboBoxClient.DataSource = listClients;
                    comboBoxClient.SelectedItem = null;
                }

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

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

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

                    var product = _logicW.ReadElement(new WorkSearchModel
                    {
                        Id = id
                    });

                    int count = Convert.ToInt32(CountTextBox.Text);
                    SumTextBox.Text = Math.Round(count * (product?.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 WorkComboBox_SelectedIndexChanged(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 (WorkComboBox.SelectedValue == null)
            {
                MessageBox.Show("Выберите Работа", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (comboBoxClient.SelectedValue == null)
            {
                MessageBox.Show("Выберите заказчика", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

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

            try
            {
                var operationResult = _logicO.CreateOrder(new OrderBindingModel
                {
                    WorkId = Convert.ToInt32(WorkComboBox.SelectedValue),
                    WorkName = WorkComboBox.Text,
                    Count = Convert.ToInt32(CountTextBox.Text),
                    Sum = Convert.ToDouble(SumTextBox.Text),
                    ClientId = Convert.ToInt32(comboBoxClient.SelectedValue)
                });

                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();
        }
    }
}
