using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using RestaurantApp.DAL;
using RestaurantApp.Models;

namespace RestaurantApp
{
    public partial class DishForm : Form
    {
        private DishRepository repo = new DishRepository();

        public DishForm()
        {
            InitializeComponent();
            LoadCategories();
            LoadDishes();

            btnSearch.Click += (s, e) => LoadDishes();
            btnRefresh.Click += (s, e) => LoadDishes();
            btnAdd.Click += BtnAdd_Click;
            btnEdit.Click += BtnEdit_Click;
            btnDelete.Click += BtnDelete_Click;
            cmbCategory.SelectedIndexChanged += (s, e) => LoadDishes();
            chkAvailable.CheckedChanged += (s, e) => LoadDishes();
            dgvDishes.DoubleClick += (s, e) => BtnEdit_Click(s, e);
        }

        private void LoadCategories()
        {
            var dtCategories = repo.GetCategories();

            var list = dtCategories.AsEnumerable().Select(r => new
            {
                category_id = r.Field<int>("category_id"),
                name = r.Field<string>("name")
            }).ToList();

            list.Insert(0, new { category_id = 0, name = "Все категории" });

            cmbCategory.DataSource = list;
            cmbCategory.DisplayMember = "name";
            cmbCategory.ValueMember = "category_id";
        }

        private void LoadDishes()
        {
            int categoryId = (int)cmbCategory.SelectedValue;
            if (categoryId == 0) categoryId = 0;

            bool? available = chkAvailable.Checked ? (bool?)true : null;

            var dishes = repo.GetAll(txtSearch.Text, categoryId, available);
            dgvDishes.DataSource = dishes;

            if (dgvDishes.Columns.Count > 0)
            {
                dgvDishes.Columns["DishId"].HeaderText = "ID";
                dgvDishes.Columns["CategoryName"].HeaderText = "Категория";
                dgvDishes.Columns["Name"].HeaderText = "Название";
                dgvDishes.Columns["Description"].HeaderText = "Описание";
                dgvDishes.Columns["Price"].HeaderText = "Цена";
                dgvDishes.Columns["WeightG"].HeaderText = "Вес (г)";
                dgvDishes.Columns["CookTimeMin"].HeaderText = "Время (мин)";
                dgvDishes.Columns["IsAvailable"].HeaderText = "Доступно";
            }
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            var form = new DishEditForm();
            if (form.ShowDialog() == DialogResult.OK)
            {
                LoadDishes();
            }
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            if (dgvDishes.CurrentRow == null)
            {
                MessageBox.Show("Выберите блюдо для редактирования");
                return;
            }

            var dish = (Dish)dgvDishes.CurrentRow.DataBoundItem;
            var form = new DishEditForm(dish);
            if (form.ShowDialog() == DialogResult.OK)
            {
                LoadDishes();
            }
        }

        private void BtnDelete_Click(object sender, EventArgs e)
        {
            if (dgvDishes.CurrentRow == null)
            {
                MessageBox.Show("Выберите блюдо для удаления");
                return;
            }

            var dish = (Dish)dgvDishes.CurrentRow.DataBoundItem;
            if (MessageBox.Show($"Удалить блюдо \"{dish.Name}\"?", "Подтверждение",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    repo.Delete(dish.DishId);
                    LoadDishes();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Ошибка удаления: {ex.Message}");
                }
            }
        }
    }
}