using System;
using System.Data;
using System.Windows.Forms;
using Npgsql;

namespace ProviderApp
{
    public partial class TariffsForm : UserControl
    {
        private DataTable tariffsTable;

        public TariffsForm()
        {
            InitializeComponent();
            this.Load += TariffsForm_Load;
            btnAdd.Click += BtnAdd_Click;
            btnEdit.Click += BtnEdit_Click;
            btnDelete.Click += BtnDelete_Click;
            btnExport.Click += BtnExport_Click;
            StyleDataGridView();
        }


        private void StyleDataGridView()
        {
            dgvTariffs.ColumnHeadersDefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(230, 92, 0);
            dgvTariffs.ColumnHeadersDefaultCellStyle.ForeColor = System.Drawing.Color.White;
            dgvTariffs.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("Segoe UI", 11F, System.Drawing.FontStyle.Bold);
            dgvTariffs.DefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(40, 40, 40);
            dgvTariffs.DefaultCellStyle.ForeColor = System.Drawing.Color.White;
            dgvTariffs.AlternatingRowsDefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(45, 45, 45);
            dgvTariffs.EnableHeadersVisualStyles = false;
        }

        private void TariffsForm_Load(object sender, EventArgs e)
        {
            LoadTariffs();
            btnAdd.Visible = AuthHelper.CurrentUser.IsManager;
            btnEdit.Visible = AuthHelper.CurrentUser.IsManager;
            btnDelete.Visible = AuthHelper.CurrentUser.IsAdmin;
            btnExport.Visible = AuthHelper.CurrentUser.IsManager;
        }
        public void RefreshData()
        {
            LoadTariffs();
        }
        private void LoadTariffs()
        {
            try
            {
                using (var conn = DBConnection.GetConnection())
                {
                    string sql = "SELECT tariff_id, name, monthly_price, speed_mbit FROM tariffs ORDER BY tariff_id";
                    using (var cmd = new NpgsqlCommand(sql, conn))
                    {
                        DataTable dt = new DataTable();
                        using (var da = new NpgsqlDataAdapter(cmd))
                        {
                            da.Fill(dt);
                        }
                        tariffsTable = dt;
                        dgvTariffs.DataSource = tariffsTable;

                        if (dgvTariffs.Columns["tariff_id"] != null)
                            dgvTariffs.Columns["tariff_id"].HeaderText = "ID";
                        if (dgvTariffs.Columns["name"] != null)
                            dgvTariffs.Columns["name"].HeaderText = "Название";
                        if (dgvTariffs.Columns["monthly_price"] != null)
                            dgvTariffs.Columns["monthly_price"].HeaderText = "Цена, руб";
                        if (dgvTariffs.Columns["speed_mbit"] != null)
                            dgvTariffs.Columns["speed_mbit"].HeaderText = "Скорость, Мбит/с";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки тарифов: {ex.Message}");
            }
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            if (!AuthHelper.CheckPermission("manager")) return;
            AuthHelper.LogAction("Попытка добавления тарифа", "tariffs");

            using (var form = new AddEditTariffForm())
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    AuthHelper.LogAction("Тариф добавлен", "tariffs");
                    LoadTariffs();
                }
            }
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            if (!AuthHelper.CheckPermission("manager")) return;

            if (dgvTariffs.CurrentRow == null)
            {
                MessageBox.Show("Выберите тариф.");
                return;
            }
            int tariffId = Convert.ToInt32(dgvTariffs.CurrentRow.Cells["tariff_id"].Value);
            AuthHelper.LogAction($"Попытка редактирования тарифа ID={tariffId}", "tariffs", tariffId);

            using (var form = new AddEditTariffForm(tariffId))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    AuthHelper.LogAction($"Тариф ID={tariffId} отредактирован", "tariffs", tariffId);
                    LoadTariffs();
                }
            }
        }

        private void BtnDelete_Click(object sender, EventArgs e)
        {
            if (!AuthHelper.CheckPermission("admin")) return;

            if (dgvTariffs.CurrentRow == null)
            {
                MessageBox.Show("Выберите тариф.");
                return;
            }
            if (MessageBox.Show("Удалить тариф?", "Подтверждение", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                int tariffId = Convert.ToInt32(dgvTariffs.CurrentRow.Cells["tariff_id"].Value);
                try
                {
                    using (var conn = DBConnection.GetConnection())
                    {
                        string sql = "DELETE FROM tariffs WHERE tariff_id = @id";
                        using (var cmd = new NpgsqlCommand(sql, conn))
                        {
                            cmd.Parameters.AddWithValue("@id", tariffId);
                            cmd.ExecuteNonQuery();
                        }
                    }
                    AuthHelper.LogAction($"Тариф ID={tariffId} удалён", "tariffs", tariffId);
                    LoadTariffs();
                    MessageBox.Show("Тариф удалён.");
                }
                catch (PostgresException ex) when (ex.SqlState == "23503")
                {
                    MessageBox.Show("Нельзя удалить тариф, так как он используется в договорах.");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Ошибка удаления: {ex.Message}");
                }
            }
        }

        private void BtnExport_Click(object sender, EventArgs e)
        {
            if (!AuthHelper.CheckPermission("manager")) return;

            try
            {
                using (var conn = DBConnection.GetConnection())
                {
                    string sql = "SELECT tariff_id as \"ID\", name as \"Название\", monthly_price as \"Цена, руб\", speed_mbit as \"Скорость, Мбит/с\" FROM tariffs ORDER BY tariff_id";
                    using (var cmd = new NpgsqlCommand(sql, conn))
                    {
                        DataTable dt = new DataTable();
                        using (var da = new NpgsqlDataAdapter(cmd))
                        {
                            da.Fill(dt);
                        }
                        AuthHelper.LogAction("Экспорт тарифов в CSV", "tariffs");
                        CsvExporter.ExportToCsv(dt, $"Тарифы_{DateTime.Now:yyyyMMdd_HHmmss}.csv");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка экспорта: {ex.Message}");
            }
        }
    }
}