using System;
using System.Drawing;
using System.Windows.Forms;
using Npgsql;
using Guna.UI2.WinForms;

namespace ProviderApp
{
    public class AddEditTariffForm : Form
    {
        private int? tariffId = null;
        private Guna2TextBox txtName;
        private Guna2TextBox txtPrice;
        private Guna2TextBox txtSpeed;
        private Guna2Button btnSave;
        private Guna2Button btnCancel;
        private Label lblTitle;

        public AddEditTariffForm(int? id = null)
        {
            tariffId = id;
            this.Size = new Size(480, 420);
            this.StartPosition = FormStartPosition.CenterParent;
            this.BackColor = Color.FromArgb(30, 30, 30);
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;

            lblTitle = new Label()
            {
                Text = tariffId.HasValue ? "Редактирование тарифа" : "Добавление тарифа",
                ForeColor = Color.White,
                Font = new Font("Segoe UI", 16F, FontStyle.Bold),
                Location = new Point(20, 20),
                AutoSize = true
            };
            this.Controls.Add(lblTitle);

            int y = 80;
            int step = 55;

            Label lblName = new Label() { Text = "Название:", ForeColor = Color.FromArgb(200, 200, 200), Location = new Point(20, y + 10), Size = new Size(100, 25) };
            txtName = new Guna2TextBox() { PlaceholderText = "Введите название", FillColor = Color.FromArgb(45, 45, 45), ForeColor = Color.White, BorderColor = Color.FromArgb(230, 92, 0), Location = new Point(130, y), Size = new Size(310, 40), BorderRadius = 8 };
            this.Controls.Add(lblName);
            this.Controls.Add(txtName);
            y += step;

            Label lblPrice = new Label() { Text = "Цена (руб):", ForeColor = Color.FromArgb(200, 200, 200), Location = new Point(20, y + 10), Size = new Size(100, 25) };
            txtPrice = new Guna2TextBox() { PlaceholderText = "Введите цену", FillColor = Color.FromArgb(45, 45, 45), ForeColor = Color.White, BorderColor = Color.FromArgb(230, 92, 0), Location = new Point(130, y), Size = new Size(310, 40), BorderRadius = 8 };
            this.Controls.Add(lblPrice);
            this.Controls.Add(txtPrice);
            y += step;

            Label lblSpeed = new Label() { Text = "Скорость (Мбит/с):", ForeColor = Color.FromArgb(200, 200, 200), Location = new Point(20, y + 10), Size = new Size(100, 25) };
            txtSpeed = new Guna2TextBox() { PlaceholderText = "Введите скорость", FillColor = Color.FromArgb(45, 45, 45), ForeColor = Color.White, BorderColor = Color.FromArgb(230, 92, 0), Location = new Point(130, y), Size = new Size(310, 40), BorderRadius = 8 };
            this.Controls.Add(lblSpeed);
            this.Controls.Add(txtSpeed);
            y += step;

            btnSave = new Guna2Button() { Text = "Сохранить", FillColor = Color.FromArgb(230, 92, 0), ForeColor = Color.White, Location = new Point(100, y + 20), Size = new Size(120, 40), BorderRadius = 8 };
            btnSave.Click += BtnSave_Click;
            this.Controls.Add(btnSave);

            btnCancel = new Guna2Button() { Text = "Отмена", FillColor = Color.FromArgb(80, 80, 80), ForeColor = Color.White, Location = new Point(240, y + 20), Size = new Size(120, 40), BorderRadius = 8 };
            btnCancel.Click += (s, e) => this.DialogResult = DialogResult.Cancel;
            this.Controls.Add(btnCancel);

            if (tariffId.HasValue)
                LoadTariffData();
        }

        private void LoadTariffData()
        {
            try
            {
                using (var conn = DBConnection.GetConnection())
                {
                    string sql = "SELECT name, monthly_price, speed_mbit FROM tariffs WHERE tariff_id = @id";
                    using (var cmd = new NpgsqlCommand(sql, conn))
                    {
                        cmd.Parameters.AddWithValue("@id", tariffId.Value);
                        using (var reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                txtName.Text = reader["name"].ToString();
                                txtPrice.Text = reader["monthly_price"].ToString();
                                txtSpeed.Text = reader["speed_mbit"].ToString();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки: {ex.Message}");
            }
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtName.Text) || string.IsNullOrWhiteSpace(txtPrice.Text) || string.IsNullOrWhiteSpace(txtSpeed.Text))
            {
                MessageBox.Show("Заполните все поля.");
                return;
            }

            try
            {
                using (var conn = DBConnection.GetConnection())
                {
                    if (tariffId.HasValue)
                    {
                        string sql = "UPDATE tariffs SET name=@name, monthly_price=@price, speed_mbit=@speed WHERE tariff_id=@id";
                        using (var cmd = new NpgsqlCommand(sql, conn))
                        {
                            cmd.Parameters.AddWithValue("@id", tariffId.Value);
                            cmd.Parameters.AddWithValue("@name", txtName.Text);
                            cmd.Parameters.AddWithValue("@price", decimal.Parse(txtPrice.Text));
                            cmd.Parameters.AddWithValue("@speed", int.Parse(txtSpeed.Text));
                            cmd.ExecuteNonQuery();
                        }
                        MessageBox.Show("Тариф обновлён!");
                    }
                    else
                    {
                        string sql = @"INSERT INTO tariffs (name, monthly_price, speed_mbit) VALUES (@name, @price, @speed) RETURNING tariff_id";
                        using (var cmd = new NpgsqlCommand(sql, conn))
                        {
                            cmd.Parameters.AddWithValue("@name", txtName.Text);
                            cmd.Parameters.AddWithValue("@price", decimal.Parse(txtPrice.Text));
                            cmd.Parameters.AddWithValue("@speed", int.Parse(txtSpeed.Text));
                            int newId = Convert.ToInt32(cmd.ExecuteScalar());
                            MessageBox.Show($"Тариф №{newId} добавлен!");
                        }
                    }
                }
                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка: {ex.Message}");
            }
        }
    }
}