using moduleExamen.Data;
using moduleExamen.Helpers;
using moduleExamen.Models;

namespace moduleExamen.Forms
{
    public partial class OrderEditForm : Form
    {
        private readonly Order? editingOrder;
        private readonly bool isEditing;

        public OrderEditForm(Order? order)
        {
            InitializeComponent();
            AppStyles.ApplyIcon(this);

            if (File.Exists(AppStyles.LogoPath))
                logoPictureBox.Image = Image.FromFile(AppStyles.LogoPath);

            editingOrder = order;
            isEditing = order != null;

            Text = isEditing ? "Sport Farm - Редактирование заказа" : "Sport Farm - Добавление заказа";
            idLabel.Text = isEditing ? $"Заказ #{order!.Idzakaz}" : "Новый заказ";

            LoadStatuses();
            if (isEditing) FillFields();
        }

        private void DateEndCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            dateEndPicker.Enabled = dateEndCheckBox.Checked;
        }

        private void CancelButton_Click(object? sender, EventArgs e) => Close();

        private void LoadStatuses()
        {
            try
            {
                using var context = new SportShopContext();
                var statuses = context.Statuses.ToList();
                statusComboBox.DataSource = statuses;
                statusComboBox.DisplayMember = "Name";
                statusComboBox.ValueMember = "IdStatus";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки статусов:\n{ex.Message}", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FillFields()
        {
            if (editingOrder == null) return;

            articleTextBox.Text = editingOrder.Article;
            statusComboBox.SelectedValue = editingOrder.IdStatus;
            addressTextBox.Text = editingOrder.Adrec;
            dateStartPicker.Value = editingOrder.DataStart.ToDateTime(TimeOnly.MinValue);

            if (editingOrder.DateEnd.HasValue)
            {
                dateEndCheckBox.Checked = true;
                dateEndPicker.Value = editingOrder.DateEnd.Value.ToDateTime(TimeOnly.MinValue);
            }
        }

        private void SaveButton_Click(object? sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(articleTextBox.Text))
            {
                MessageBox.Show("Введите артикул заказа.", "Ошибка валидации",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                articleTextBox.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(addressTextBox.Text))
            {
                MessageBox.Show("Введите адрес пункта выдачи.", "Ошибка валидации",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                addressTextBox.Focus();
                return;
            }

            if (statusComboBox.SelectedValue == null)
            {
                MessageBox.Show("Выберите статус заказа.", "Ошибка валидации",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                using var context = new SportShopContext();
                var newStatusId = (int)statusComboBox.SelectedValue;

                Order order;
                if (isEditing)
                {
                    order = context.Orders.First(o => o.Idzakaz == editingOrder!.Idzakaz);
                }
                else
                {
                    // Fio = 1 — ID первого пользователя по умолчанию (FK на таблицу User)
                    order = new Order { Fio = 1 };
                    context.Orders.Add(order);
                }

                order.Article = articleTextBox.Text.Trim();
                order.IdStatus = newStatusId;
                order.Adrec = addressTextBox.Text.Trim();
                order.DataStart = DateOnly.FromDateTime(dateStartPicker.Value);
                order.DateEnd = dateEndCheckBox.Checked ? DateOnly.FromDateTime(dateEndPicker.Value) : null;

                context.SaveChanges();

                MessageBox.Show("Заказ сохранён.", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка сохранения:\n{ex.Message}", "Ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void OrderEditForm_Load(object sender, EventArgs e)
        {

        }
    }
}
