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

namespace АвтотранспортноеПредприятие
{
    public partial class FormCreateOrder : Form
    {
        private DatabaseManager db;
        private string customerPhone;
        private int customerId;

        private Label lblPickupAddress;
        private Label lblDestinationAddress;
        private Label lblVehicle;
        private Label lblDriver;
        private Label lblPickupDate;
        private Label lblDescription;

        private ComboBox cmbPickupAddress;
        private ComboBox cmbDestinationAddress;
        private ComboBox cmbVehicle;
        private ComboBox cmbDriver;
        private DateTimePicker dtpPickupDate;
        private TextBox txtDescription;

        private Button btnSave;
        private Button btnCancel;

        public FormCreateOrder(string phone)
        {
            db = new DatabaseManager();
            customerPhone = phone;
            customerId = db.GetCustomerIdByPhone(customerPhone);
            InitializeComponent();
            CreateCustomControls();
            LoadData();
        }

        private void CreateCustomControls()
        {
            this.Text = "Создание нового заказа";
            this.Size = new Size(600, 520);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.BackColor = Color.White;

            lblPickupAddress = new Label();
            lblPickupAddress.Text = "Адрес подачи:";
            lblPickupAddress.Location = new Point(20, 20);
            lblPickupAddress.Size = new Size(120, 25);

            cmbPickupAddress = new ComboBox();
            cmbPickupAddress.Location = new Point(150, 20);
            cmbPickupAddress.Size = new Size(400, 25);
            cmbPickupAddress.DropDownStyle = ComboBoxStyle.DropDownList;

            lblDestinationAddress = new Label();
            lblDestinationAddress.Text = "Адрес назначения:";
            lblDestinationAddress.Location = new Point(20, 60);
            lblDestinationAddress.Size = new Size(120, 25);

            cmbDestinationAddress = new ComboBox();
            cmbDestinationAddress.Location = new Point(150, 60);
            cmbDestinationAddress.Size = new Size(400, 25);
            cmbDestinationAddress.DropDownStyle = ComboBoxStyle.DropDownList;

            lblVehicle = new Label();
            lblVehicle.Text = "Транспортное средство:";
            lblVehicle.Location = new Point(20, 100);
            lblVehicle.Size = new Size(150, 25);

            cmbVehicle = new ComboBox();
            cmbVehicle.Location = new Point(170, 100);
            cmbVehicle.Size = new Size(380, 25);
            cmbVehicle.DropDownStyle = ComboBoxStyle.DropDownList;

            lblDriver = new Label();
            lblDriver.Text = "Водитель:";
            lblDriver.Location = new Point(20, 140);
            lblDriver.Size = new Size(120, 25);

            cmbDriver = new ComboBox();
            cmbDriver.Location = new Point(150, 140);
            cmbDriver.Size = new Size(400, 25);
            cmbDriver.DropDownStyle = ComboBoxStyle.DropDownList;

            lblPickupDate = new Label();
            lblPickupDate.Text = "Дата и время подачи:";
            lblPickupDate.Location = new Point(20, 180);
            lblPickupDate.Size = new Size(140, 25);

            dtpPickupDate = new DateTimePicker();
            dtpPickupDate.Location = new Point(170, 180);
            dtpPickupDate.Size = new Size(380, 25);
            dtpPickupDate.Format = DateTimePickerFormat.Custom;
            dtpPickupDate.CustomFormat = "dd.MM.yyyy HH:mm";
            dtpPickupDate.Value = DateTime.Now.AddDays(1);

            lblDescription = new Label();
            lblDescription.Text = "Описание:";
            lblDescription.Location = new Point(20, 220);
            lblDescription.Size = new Size(120, 25);

            txtDescription = new TextBox();
            txtDescription.Location = new Point(150, 220);
            txtDescription.Size = new Size(400, 100);
            txtDescription.Multiline = true;

            btnSave = new Button();
            btnSave.Text = "Сохранить";
            btnSave.Location = new Point(150, 360);
            btnSave.Size = new Size(120, 40);
            btnSave.BackColor = Color.LightGreen;
            btnSave.Click += BtnSave_Click;

            btnCancel = new Button();
            btnCancel.Text = "Отмена";
            btnCancel.Location = new Point(290, 360);
            btnCancel.Size = new Size(120, 40);
            btnCancel.BackColor = Color.LightCoral;
            btnCancel.Click += (s, e) => this.Close();

            this.Controls.Add(lblPickupAddress);
            this.Controls.Add(cmbPickupAddress);
            this.Controls.Add(lblDestinationAddress);
            this.Controls.Add(cmbDestinationAddress);
            this.Controls.Add(lblVehicle);
            this.Controls.Add(cmbVehicle);
            this.Controls.Add(lblDriver);
            this.Controls.Add(cmbDriver);
            this.Controls.Add(lblPickupDate);
            this.Controls.Add(dtpPickupDate);
            this.Controls.Add(lblDescription);
            this.Controls.Add(txtDescription);
            this.Controls.Add(btnSave);
            this.Controls.Add(btnCancel);
        }

        private void LoadData()
        {
            var addresses = db.GetAllAddressesForOrder();

            var addressesPickup = addresses.Select(a => new { a.address_id, a.FullAddress }).ToList();
            var addressesDestination = addresses.Select(a => new { a.address_id, a.FullAddress }).ToList();

            cmbPickupAddress.DataSource = null;
            cmbPickupAddress.DataSource = addressesPickup;
            cmbPickupAddress.DisplayMember = "FullAddress";
            cmbPickupAddress.ValueMember = "address_id";

            cmbDestinationAddress.DataSource = null;
            cmbDestinationAddress.DataSource = addressesDestination;
            cmbDestinationAddress.DisplayMember = "FullAddress";
            cmbDestinationAddress.ValueMember = "address_id";

            var vehicles = db.GetAllVehiclesForOrder();
            cmbVehicle.DataSource = vehicles;
            cmbVehicle.DisplayMember = "license_plate";
            cmbVehicle.ValueMember = "license_plate";

            var drivers = db.GetAllDrivers();
            cmbDriver.DataSource = drivers;
            cmbDriver.DisplayMember = "driver_id";
            cmbDriver.ValueMember = "driver_id";
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbPickupAddress.SelectedItem == null)
                {
                    MessageBox.Show("Выберите адрес подачи");
                    return;
                }
                if (cmbDestinationAddress.SelectedItem == null)
                {
                    MessageBox.Show("Выберите адрес назначения");
                    return;
                }
                if (cmbVehicle.SelectedItem == null)
                {
                    MessageBox.Show("Выберите транспортное средство");
                    return;
                }
                if (cmbDriver.SelectedItem == null)
                {
                    MessageBox.Show("Выберите водителя");
                    return;
                }

                Order order = new Order();
                order.status = "новый";
                order.pickup_datetime = dtpPickupDate.Value;
                order.customer_id = customerId;
                order.pickup_address_id = (int)cmbPickupAddress.SelectedValue;
                order.destination_address_id = (int)cmbDestinationAddress.SelectedValue;
                order.license_plate = cmbVehicle.SelectedValue.ToString();
                order.driver_id = (int)cmbDriver.SelectedValue;
                order.description = txtDescription.Text;

                db.AddOrder(order);
                MessageBox.Show("Заказ успешно создан", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка при создании заказа: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FormCreateOrder_Load(object sender, EventArgs e)
        {

        }
    }
}