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

namespace ZhkhApp
{
    public partial class MainForm : Form
    {
        public static string ConnectionString { get; set; }
        public static int CurrentUserId { get; set; }
        public static string CurrentUsername { get; set; }
        public static string CurrentUserFullName { get; set; }
        public static string CurrentRole { get; set; }

        private string currentTable = "apartments";

        public MainForm()
        {
            InitializeComponent();
            LoadTablesList();
            LoadData();
            SetUIPermissions();
            DisplayUserInfo();
        }

        private string GetPrimaryKeyName(string tableName)
        {
            switch (tableName)
            {
                case "apartments": return "apartment_id";
                case "persons": return "person_id";
                case "receipts": return "receipt_id";
                default: return tableName + "_id";
            }
        }

        private void LoadTablesList()
        {
            cbTables.Items.Clear();
            cbTables.Items.AddRange(new[] { "apartments", "persons", "receipts" });
            cbTables.SelectedIndex = 0;
        }

        private void CbTables_SelectedIndexChanged(object sender, EventArgs e)
        {
            currentTable = cbTables.SelectedItem.ToString();
            LoadData();
        }

        private void BtnLoad_Click(object sender, EventArgs e) => LoadData();
        private void BtnRefresh_Click(object sender, EventArgs e) => LoadData();

        private void LoadData()
        {
            try
            {
                string pkName = GetPrimaryKeyName(currentTable);
                string query = $"SELECT * FROM {currentTable} ORDER BY {pkName}";

                using (NpgsqlConnection conn = new NpgsqlConnection(ConnectionString))
                {
                    conn.Open();
                    using (NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(query, conn))
                    {
                        DataTable dt = new DataTable();
                        adapter.Fill(dt);
                        dgvList.DataSource = dt;
                    }
                }
                SetRussianHeaders();
                AddCalculatedColumn();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void AddCalculatedColumn()
        {
            if (currentTable == "receipts" && dgvList.Columns["total_with_penalty"] == null)
            {
                DataGridViewTextBoxColumn calcColumn = new DataGridViewTextBoxColumn();
                calcColumn.Name = "total_with_penalty";
                calcColumn.HeaderText = "Итого с пеней";
                calcColumn.ReadOnly = true;
                dgvList.Columns.Add(calcColumn);

                foreach (DataGridViewRow row in dgvList.Rows)
                {
                    if (row.Cells["total_sum"]?.Value != null && row.Cells["penalty"]?.Value != null)
                    {
                        decimal total = Convert.ToDecimal(row.Cells["total_sum"].Value);
                        decimal penalty = Convert.ToDecimal(row.Cells["penalty"].Value);
                        row.Cells["total_with_penalty"].Value = total + penalty;
                    }
                }
            }
        }

        private void SetRussianHeaders()
        {
            if (currentTable == "apartments")
            {
                if (dgvList.Columns["apartment_id"] != null) dgvList.Columns["apartment_id"].HeaderText = "ID";
                if (dgvList.Columns["apt_number"] != null) dgvList.Columns["apt_number"].HeaderText = "№ квартиры";
                if (dgvList.Columns["area"] != null) dgvList.Columns["area"].HeaderText = "Площадь (кв.м)";
                if (dgvList.Columns["resident_count"] != null) dgvList.Columns["resident_count"].HeaderText = "Проживает";
            }
            else if (currentTable == "persons")
            {
                if (dgvList.Columns["person_id"] != null) dgvList.Columns["person_id"].HeaderText = "ID";
                if (dgvList.Columns["last_name"] != null) dgvList.Columns["last_name"].HeaderText = "Фамилия";
                if (dgvList.Columns["first_name"] != null) dgvList.Columns["first_name"].HeaderText = "Имя";
                if (dgvList.Columns["middle_name"] != null) dgvList.Columns["middle_name"].HeaderText = "Отчество";
            }
            else if (currentTable == "receipts")
            {
                if (dgvList.Columns["receipt_id"] != null) dgvList.Columns["receipt_id"].HeaderText = "№ квитанции";
                if (dgvList.Columns["apartment_id"] != null) dgvList.Columns["apartment_id"].HeaderText = "ID квартиры";
                if (dgvList.Columns["period_month"] != null) dgvList.Columns["period_month"].HeaderText = "Месяц";
                if (dgvList.Columns["period_year"] != null) dgvList.Columns["period_year"].HeaderText = "Год";
                if (dgvList.Columns["penalty"] != null) dgvList.Columns["penalty"].HeaderText = "Пени";
                if (dgvList.Columns["total_sum"] != null) dgvList.Columns["total_sum"].HeaderText = "Сумма";
            }
        }

        private void SetUIPermissions()
        {
            if (CurrentRole == "guest")
            {
                btnAdd.Enabled = false;
                btnEdit.Enabled = false;
                btnDelete.Enabled = false;
            }
        }

        private void DisplayUserInfo()
        {
            lblUserInfo.Text = $"Пользователь: {CurrentUsername} ({CurrentRole})";
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            var editForm = new EditForm(currentTable, null);
            if (editForm.ShowDialog() == DialogResult.OK) LoadData();
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            if (dgvList.CurrentRow == null)
            {
                MessageBox.Show("Выберите запись!", "Внимание");
                return;
            }

            string pkName = GetPrimaryKeyName(currentTable);
            int id = Convert.ToInt32(dgvList.CurrentRow.Cells[pkName].Value);
            var editForm = new EditForm(currentTable, id);
            if (editForm.ShowDialog() == DialogResult.OK) LoadData();
        }

        private void BtnDelete_Click(object sender, EventArgs e)
        {
            if (dgvList.CurrentRow == null)
            {
                MessageBox.Show("Выберите запись!", "Внимание");
                return;
            }

            if (MessageBox.Show("Удалить?", "Подтверждение", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    string pkName = GetPrimaryKeyName(currentTable);
                    int id = Convert.ToInt32(dgvList.CurrentRow.Cells[pkName].Value);

                    using (NpgsqlConnection conn = new NpgsqlConnection(ConnectionString))
                    {
                        conn.Open();
                        using (NpgsqlCommand cmd = new NpgsqlCommand($"DELETE FROM {currentTable} WHERE {pkName} = @id", conn))
                        {
                            cmd.Parameters.AddWithValue("@id", id);
                            cmd.ExecuteNonQuery();
                        }
                    }
                    LoadData();
                    MessageBox.Show("Запись удалена!", "Успех");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Ошибка: {ex.Message}");
                }
            }
        }

        private void BtnLogout_Click(object sender, EventArgs e) => Application.Restart();
    }
}