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

namespace RestaurantApp
{
    public partial class EmployeeForm : Form
    {
        private EmployeeRepository repo = new EmployeeRepository();

        public EmployeeForm()
        {
            InitializeComponent();
            LoadPositions();
            LoadEmployees();

            btnSearch.Click += (s, e) => LoadEmployees();
            btnRefresh.Click += (s, e) => LoadEmployees();
            btnAdd.Click += BtnAdd_Click;
            btnEdit.Click += BtnEdit_Click;
            btnDelete.Click += BtnDelete_Click;
            cmbPosition.SelectedIndexChanged += (s, e) => LoadEmployees();
            chkActive.CheckedChanged += (s, e) => LoadEmployees();
            dgvEmployees.DoubleClick += (s, e) => BtnEdit_Click(s, e);
        }

        private void LoadPositions()
        {
            var dtPositions = repo.GetPositions();

            var list = dtPositions.AsEnumerable().Select(r => new
            {
                position_id = r.Field<int>("position_id"),
                title = r.Field<string>("title")
            }).ToList();

            list.Insert(0, new { position_id = 0, title = "Все должности" });

            cmbPosition.DataSource = list;
            cmbPosition.DisplayMember = "title";
            cmbPosition.ValueMember = "position_id";
        }

        private void LoadEmployees()
        {
            int positionId = (int)cmbPosition.SelectedValue;
            string positionFilter = positionId > 0 ? cmbPosition.Text : "";

            bool? active = chkActive.Checked ? (bool?)true : null;

            var employees = repo.GetAll(txtSearch.Text, active);

            // Фильтрация по должности на клиенте
            if (positionId > 0)
            {
                employees = employees.FindAll(e => e.PositionId == positionId);
            }

            dgvEmployees.DataSource = employees;

            if (dgvEmployees.Columns.Count > 0)
            {
                dgvEmployees.Columns["EmployeeId"].HeaderText = "ID";
                dgvEmployees.Columns["FullName"].HeaderText = "ФИО";
                dgvEmployees.Columns["PositionTitle"].HeaderText = "Должность";
                dgvEmployees.Columns["Phone"].HeaderText = "Телефон";
                dgvEmployees.Columns["Email"].HeaderText = "Email";
                dgvEmployees.Columns["HireDate"].HeaderText = "Дата приема";
                dgvEmployees.Columns["Salary"].HeaderText = "Оклад";
                dgvEmployees.Columns["IsActive"].HeaderText = "Активен";
                dgvEmployees.Columns["PositionId"].Visible = false;
                dgvEmployees.Columns["FirstName"].Visible = false;
                dgvEmployees.Columns["LastName"].Visible = false;
                dgvEmployees.Columns["MiddleName"].Visible = false;
            }
        }

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

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

            var employee = (Employee)dgvEmployees.CurrentRow.DataBoundItem;
            var form = new EmployeeEditForm(employee);
            if (form.ShowDialog() == DialogResult.OK)
            {
                LoadEmployees();
            }
        }

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

            var employee = (Employee)dgvEmployees.CurrentRow.DataBoundItem;
            if (MessageBox.Show($"Уволить сотрудника {employee.FullName}?", "Подтверждение",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    repo.Delete(employee.EmployeeId);
                    LoadEmployees();
                    MessageBox.Show("Сотрудник уволен");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Ошибка: {ex.Message}");
                }
            }
        }
    }
}