using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace _0503NeshinaRogova
{
    public partial class AdminForm : Form
    {
        private int currentUserId;
        private string connectionString = "Server=cfif31.ru;Port=3306;Database=ISPr25-21_NeshinaPV_1003;Uid=ISPr25-21_NeshinaPV;Pwd=ISPr25-21_NeshinaPV;Charset=utf8mb4;";
        private Random rand = new Random();
        private int buttonEscapeCount = 0;
        private const int MAX_ESCAPES = 3;

        // Для эпилепсии
        private Timer flashTimer;
        private Color[] crazyColors = { Color.Red, Color.Lime, Color.Blue, Color.Yellow, Color.Magenta, Color.Cyan, Color.Orange, Color.Purple };

        public AdminForm(int userId)
        {
            InitializeComponent();
            currentUserId = userId;
            SetupHellMode();
            LoadDataGrid();
        }

        private void SetupHellMode()
        {
            flashTimer = new Timer();
            flashTimer.Interval = 80;
            flashTimer.Tick += (s, e) =>
            {
                this.BackColor = crazyColors[rand.Next(crazyColors.Length)];
                this.ForeColor = Color.Black;
                if (rand.Next(2) == 0) this.labelTitle.ForeColor = Color.White; else this.labelTitle.ForeColor = Color.Yellow;
            };
            flashTimer.Start();
            SubscribeButtonToEscape(button1);
            SubscribeButtonToEscape(button2);
            SubscribeButtonToEscape(button3);
            Label lblTitle = new Label();
            lblTitle.Text = "АДМИНКА (ПОЙМАЙ КНОПКУ)";
            lblTitle.Font = new Font("Comic Sans MS", 16, FontStyle.Bold | FontStyle.Italic);
            lblTitle.AutoSize = true;
            lblTitle.Location = new Point(300, 5);
            lblTitle.ForeColor = Color.Black;
            lblTitle.BackColor = Color.White;
            this.Controls.Add(lblTitle);
            this.labelTitle = lblTitle; 
        }

        private Label labelTitle;

        private void SubscribeButtonToEscape(Button btn)
        {
            btn.MouseEnter += (s, e) =>
            {
                if (buttonEscapeCount < MAX_ESCAPES)
                {
                    MoveButtonRandomly(btn);
                    buttonEscapeCount++;
                    btn.Text = "Не поймаешь!";
                    btn.BackColor = crazyColors[rand.Next(crazyColors.Length)];
                }
                else
                {
                    btn.Text = "Ладно, жми...";
                    btn.BackColor = Color.Green;
                }
            };
        }

        private void MoveButtonRandomly(Button btn)
        {
            int maxX = this.ClientSize.Width - btn.Width;
            int maxY = this.ClientSize.Height - btn.Height;
            int newX = rand.Next(0, Math.Max(10, maxX));
            int newY = rand.Next(0, Math.Max(10, maxY));
            btn.Location = new Point(newX, newY);
            btn.Width = rand.Next(80, 150);
            btn.Height = rand.Next(30, 60);
            btn.Font = new Font("Comic Sans MS", rand.Next(8, 12), FontStyle.Bold);
        }

        private void LoadDataGrid()
        {
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    string query = @"
                SELECT 
                    r.request_id AS 'ID',
                    DATE_FORMAT(r.start_date, '%d.%m.%Y') AS 'Дата',
                    t.tech_type_name AS 'Тип',
                    r.climate_tech_model AS 'Модель',
                    r.problem_description AS 'Проблема',
                    s.status_name AS 'Статус',
                    IFNULL(DATE_FORMAT(r.completion_date, '%d.%m.%Y'), '-') AS 'Готово',
                    IFNULL(r.repair_parts, '-') AS 'Запчасти',
                    IFNULL(m.fio, 'Нет мастера') AS 'Мастер',
                    c.fio AS 'Клиент'
                FROM requests r
                JOIN tech_types t ON r.tech_type_id = t.tech_type_id
                JOIN request_statuses s ON r.status_id = s.status_id
                LEFT JOIN users m ON r.master_id = m.user_id
                JOIN users c ON r.client_id = c.user_id
                ORDER BY r.request_id DESC";

                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    DataTable dt = new DataTable();
                    using (MySqlDataAdapter adapter = new MySqlDataAdapter(cmd))
                    {
                        adapter.Fill(dt);
                    }
                    dataGridViewRequests.DataSource = dt;
                    dataGridViewRequests.BackgroundColor = Color.Yellow;
                    dataGridViewRequests.GridColor = Color.Red;
                    dataGridViewRequests.AlternatingRowsDefaultCellStyle.BackColor = Color.Orange;
                    dataGridViewRequests.DefaultCellStyle.ForeColor = Color.DarkBlue;
                    dataGridViewRequests.DefaultCellStyle.Font = new Font("Comic Sans MS", 9, FontStyle.Italic);
                    dataGridViewRequests.ColumnHeadersDefaultCellStyle.BackColor = Color.Purple;
                    dataGridViewRequests.ColumnHeadersDefaultCellStyle.ForeColor = Color.Lime;
                    dataGridViewRequests.ColumnHeadersDefaultCellStyle.Font = new Font("Comic Sans MS", 10, FontStyle.Bold | FontStyle.Underline);
                    dataGridViewRequests.RowHeadersVisible = false;
                    foreach (DataGridViewColumn col in dataGridViewRequests.Columns)
                    {
                        col.Width = rand.Next(50, 150);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"ОШИБКАААА: {ex.Message}", "ВСЁ СЛОМАЛОСЬ", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            flashTimer.Stop();
            Form1 form1 = new Form1();
            form1.Show();
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            EditRequestForm editForm = new EditRequestForm(connectionString, false, 0);
            if (editForm.ShowDialog() == DialogResult.OK)
            {
                LoadDataGrid();
                MessageBox.Show("Заявка добавлена! (Надеюсь, ты доволен)", "УСПЕХ", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (dataGridViewRequests.CurrentRow == null)
            {
                MessageBox.Show("Выбери строку, горе-админ!", "ВНИМАНИЕ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            int requestId = Convert.ToInt32(dataGridViewRequests.CurrentRow.Cells["ID"].Value);
            EditRequestForm editForm = new EditRequestForm(connectionString, true, requestId);
            if (editForm.ShowDialog() == DialogResult.OK)
            {
                LoadDataGrid();
                MessageBox.Show("Обновлено! (И зачем ты это сделал?)", "ОК", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (dataGridViewRequests.CurrentRow == null)
            {
                MessageBox.Show("Строка не выбрана! Попробуй еще раз поймать курсор.", "ОШИБКА", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            int requestId = Convert.ToInt32(dataGridViewRequests.CurrentRow.Cells["ID"].Value);
            string model = dataGridViewRequests.CurrentRow.Cells["Модель"].Value?.ToString() ?? "Неизвестно";

            DialogResult result = MessageBox.Show(
                $"Точно удалить заявку №{requestId} ({model})?\nЭто действие необратимо как твоя глупость!",
                "ТЫ УВЕРЕН?",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                try
                {
                    using (MySqlConnection conn = new MySqlConnection(connectionString))
                    {
                        conn.Open();
                        using (MySqlTransaction transaction = conn.BeginTransaction())
                        {
                            try
                            {
                                string deleteComments = "DELETE FROM comments WHERE request_id = @id";
                                MySqlCommand cmdComm = new MySqlCommand(deleteComments, conn, transaction);
                                cmdComm.Parameters.AddWithValue("@id", requestId);
                                cmdComm.ExecuteNonQuery();
                                string deleteRequest = "DELETE FROM requests WHERE request_id = @id";
                                MySqlCommand cmdReq = new MySqlCommand(deleteRequest, conn, transaction);
                                cmdReq.Parameters.AddWithValue("@id", requestId);
                                int rows = cmdReq.ExecuteNonQuery();
                                transaction.Commit();

                                if (rows > 0)
                                {
                                    LoadDataGrid();
                                    MessageBox.Show("Удалено! (Плачь, заявка исчезла)", "ГОТОВО", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                }
                            }
                            catch
                            {
                                transaction.Rollback();
                                throw;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"НЕ ВЫШЛО: {ex.Message}", "КРИТИЧЕСКИЙ СБОЙ", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
}