using System;
using System.Drawing;
using System.Windows.Forms;
using АвтотранспортноеПредприятие.Database;
using АвтотранспортноеПредприятие.Models;
using АвтотранспортноеПредприятие.Models.АвтотранспортноеПредприятие.Models;

namespace АвтотранспортноеПредприятие
{
    public partial class FormMain : Form
    {
        private DatabaseManager db;
        private Customer currentUser;
        private int currentCustomerId;

        private MenuStrip mainMenu;
        private ToolStripMenuItem driversMenu;
        private ToolStripMenuItem ordersMenu;
        private ToolStripMenuItem createOrderMenu;
        private ToolStripMenuItem myOrdersMenu;
        private ToolStripMenuItem employeesMenu;
        private ToolStripMenuItem logoutMenu;

        private GroupBox searchBox;
        private Label lblGarage;
        private ComboBox cmbGarage;
        private Button btnSearch;

        private DataGridView dgvData;
        private StatusStrip statusStrip;
        private ToolStripStatusLabel lblStatus;
        private ToolStripStatusLabel lblUser;

        private Panel buttonPanel;
        private Button btnAdd;
        private Button btnEdit;
        private Button btnDelete;
        private Button btnRefresh;

        public FormMain(Customer user)
        {
            db = new DatabaseManager();
            currentUser = user;
            currentCustomerId = db.GetCustomerIdByPhone(currentUser.phone);
            InitializeComponent();
            CreateCustomControls();
            LoadGarages();
            LoadDrivers();
            SetupPermissions();
        }

        private void CreateCustomControls()
        {
            this.Text = $"Автотранспортное предприятие - {currentUser.last_name} {currentUser.first_name}";
            this.Size = new Size(1100, 650);
            this.StartPosition = FormStartPosition.CenterScreen;

            mainMenu = new MenuStrip();
            driversMenu = new ToolStripMenuItem("Водители");
            ordersMenu = new ToolStripMenuItem("Все заказы");
            createOrderMenu = new ToolStripMenuItem("Создать заказ");
            myOrdersMenu = new ToolStripMenuItem("Мои заказы");
            employeesMenu = new ToolStripMenuItem("Сотрудники");
            logoutMenu = new ToolStripMenuItem("Выход");

            mainMenu.Items.Add(driversMenu);
            mainMenu.Items.Add(employeesMenu);
            mainMenu.Items.Add(ordersMenu);
            mainMenu.Items.Add(createOrderMenu);
            mainMenu.Items.Add(myOrdersMenu);
            mainMenu.Items.Add(logoutMenu);

            driversMenu.Click += (s, e) => LoadDrivers();
            employeesMenu.Click += (s, e) => LoadEmployees();
            ordersMenu.Click += (s, e) => LoadAllOrders();
            createOrderMenu.Click += (s, e) => OpenCreateOrderForm();
            myOrdersMenu.Click += (s, e) => LoadMyOrders();
            logoutMenu.Click += (s, e) => { this.Close(); Application.Exit(); };

            searchBox = new GroupBox();
            searchBox.Text = "Поиск водителей по гаражу";
            searchBox.Size = new Size(450, 80);
            searchBox.Location = new Point(12, 35);

            lblGarage = new Label();
            lblGarage.Text = "Номер гаража:";
            lblGarage.Location = new Point(10, 30);
            lblGarage.Size = new Size(100, 25);

            cmbGarage = new ComboBox();
            cmbGarage.Location = new Point(120, 28);
            cmbGarage.Size = new Size(150, 25);
            cmbGarage.DropDownStyle = ComboBoxStyle.DropDownList;

            btnSearch = new Button();
            btnSearch.Text = "Найти";
            btnSearch.Location = new Point(290, 26);
            btnSearch.Size = new Size(130, 30);
            btnSearch.BackColor = Color.LightBlue;
            btnSearch.Click += BtnSearch_Click;

            searchBox.Controls.Add(lblGarage);
            searchBox.Controls.Add(cmbGarage);
            searchBox.Controls.Add(btnSearch);

            dgvData = new DataGridView();
            dgvData.Location = new Point(12, 130);
            dgvData.Size = new Size(1060, 420);
            dgvData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dgvData.ReadOnly = true;
            dgvData.AllowUserToAddRows = false;
            dgvData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            buttonPanel = new Panel();
            buttonPanel.Location = new Point(12, 560);
            buttonPanel.Size = new Size(1060, 45);

            btnAdd = new Button();
            btnAdd.Text = "Добавить";
            btnAdd.Size = new Size(120, 35);
            btnAdd.Location = new Point(0, 5);
            btnAdd.BackColor = Color.LightGreen;
            btnAdd.Click += (s, e) => OpenCreateOrderForm();

            btnEdit = new Button();
            btnEdit.Text = "Редактировать";
            btnEdit.Size = new Size(130, 35);
            btnEdit.Location = new Point(130, 5);
            btnEdit.BackColor = Color.LightYellow;
            btnEdit.Click += (s, e) => EditSelectedItem();

            btnDelete = new Button();
            btnDelete.Text = "Удалить";
            btnDelete.Size = new Size(120, 35);
            btnDelete.Location = new Point(270, 5);
            btnDelete.BackColor = Color.LightCoral;
            btnDelete.Click += (s, e) => DeleteSelectedItem();

            btnRefresh = new Button();
            btnRefresh.Text = "Обновить";
            btnRefresh.Size = new Size(120, 35);
            btnRefresh.Location = new Point(400, 5);
            btnRefresh.BackColor = Color.LightGray;
            btnRefresh.Click += (s, e) => RefreshCurrentView();

            buttonPanel.Controls.Add(btnAdd);
            buttonPanel.Controls.Add(btnEdit);
            buttonPanel.Controls.Add(btnDelete);
            buttonPanel.Controls.Add(btnRefresh);

            statusStrip = new StatusStrip();
            lblStatus = new ToolStripStatusLabel("Готово");
            lblUser = new ToolStripStatusLabel($" | {currentUser.last_name} {currentUser.first_name} | Роль: {(currentUser.role == "admin" ? "Администратор" : "Заказчик")}");
            statusStrip.Items.Add(lblStatus);
            statusStrip.Items.Add(lblUser);

            this.Controls.Add(mainMenu);
            this.Controls.Add(searchBox);
            this.Controls.Add(dgvData);
            this.Controls.Add(buttonPanel);
            this.Controls.Add(statusStrip);
            this.MainMenuStrip = mainMenu;
        }

        private void SetupPermissions()
        {
            if (currentUser.role == "admin")
            {
                searchBox.Visible = true;
                employeesMenu.Visible = true;
                ordersMenu.Visible = true;
                createOrderMenu.Visible = true;
                myOrdersMenu.Visible = false;
                btnAdd.Visible = true;
                btnEdit.Visible = true;
                btnDelete.Visible = true;
            }
            else
            {
                searchBox.Visible = false;
                employeesMenu.Visible = false;
                ordersMenu.Visible = false;
                createOrderMenu.Visible = true;
                myOrdersMenu.Visible = true;
                btnAdd.Visible = true;
                btnEdit.Visible = false;
                btnDelete.Visible = false;
                LoadMyOrders();
            }
        }

        private void LoadGarages()
        {
            try
            {
                var garages = db.GetAllGarages();
                cmbGarage.DataSource = garages;
                cmbGarage.DisplayMember = "garage_number";
                cmbGarage.ValueMember = "garage_number";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки гаражей: {ex.Message}");
            }
        }

        private void LoadDrivers()
        {
            try
            {
                var data = db.GetAllDriversInfo();
                dgvData.DataSource = data;
                lblStatus.Text = $"Водителей: {data.Count}";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки: {ex.Message}");
            }
        }

        private void LoadEmployees()
        {
            try
            {
                var data = db.GetAllEmployees();
                dgvData.DataSource = data;
                lblStatus.Text = $"Сотрудников: {data.Count}";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки: {ex.Message}");
            }
        }

        private void LoadAllOrders()
        {
            try
            {
                var data = db.GetAllOrders();
                dgvData.DataSource = data;
                lblStatus.Text = $"Всех заказов: {data.Count}";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки: {ex.Message}");
            }
        }

        private void LoadMyOrders()
        {
            try
            {
                var data = db.GetOrdersByCustomerId(currentCustomerId);
                dgvData.DataSource = data;
                lblStatus.Text = $"Мои заказы: {data.Count}";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки: {ex.Message}");
            }
        }

        private void BtnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                int garageNum = (int)cmbGarage.SelectedValue;
                var data = db.GetDriversByGarageNumber(garageNum);
                dgvData.DataSource = data;
                lblStatus.Text = $"Водители гаража №{garageNum}: {data.Count}";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка поиска: {ex.Message}");
            }
        }

        private void OpenCreateOrderForm()
        {
            var form = new FormCreateOrder(currentUser.phone);
            if (form.ShowDialog() == DialogResult.OK)
            {
                if (currentUser.role == "admin")
                    LoadAllOrders();
                else
                    LoadMyOrders();
            }
        }

        private void EditSelectedItem()
        {
            if (dgvData.CurrentRow == null)
            {
                MessageBox.Show("Выберите запись для редактирования");
                return;
            }

            if (currentUser.role == "admin" && dgvData.DataSource is List<Order>)
            {
                var selectedOrder = dgvData.CurrentRow.DataBoundItem as Order;
                if (selectedOrder != null)
                {
                    var form = new FormEditOrder(selectedOrder.order_id);
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        LoadAllOrders();
                    }
                }
            }
        }

        private void DeleteSelectedItem()
        {
            if (dgvData.CurrentRow == null)
            {
                MessageBox.Show("Выберите запись для удаления");
                return;
            }

            if (currentUser.role == "admin" && dgvData.DataSource is List<Order>)
            {
                var selectedOrder = dgvData.CurrentRow.DataBoundItem as Order;
                if (selectedOrder != null)
                {
                    if (MessageBox.Show($"Удалить заказ №{selectedOrder.order_id}?", "Подтверждение",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        db.DeleteOrder(selectedOrder.order_id);
                        LoadAllOrders();
                    }
                }
            }
        }

        private void RefreshCurrentView()
        {
            if (currentUser.role == "admin")
            {
                if (dgvData.DataSource is List<DriverInfo>)
                    LoadDrivers();
                else if (dgvData.DataSource is List<Employee>)
                    LoadEmployees();
                else if (dgvData.DataSource is List<Order>)
                    LoadAllOrders();
            }
            else
            {
                LoadMyOrders();
            }
        }

        private void FormMain_Load(object sender, EventArgs e)
        {

        }
    }
}