﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace WinFormsApp2
{
    public partial class ToastForm : Form
    {
        private System.Windows.Forms.Timer timerShow;
        private System.Windows.Forms.Timer timerClose;
        private int targetX;
        private int speed = 10;
        private NotificationType notificationType;

        public ToastForm(string title, string message, NotificationType type = NotificationType.Info, int displayDuration = 3000)
        {
            this.notificationType = type;

            this.FormBorderStyle = FormBorderStyle.None;
            this.StartPosition = FormStartPosition.Manual;
            this.Size = new Size(350, 100); // Увеличили ширину
            this.TopMost = true;
            this.ShowInTaskbar = false;

            // Цвет фона в зависимости от типа
            Color backColor, foreColor;
            string icon;

            switch (type)
            {
                case NotificationType.Critical:
                    backColor = Color.FromArgb(244, 67, 54); // Красный
                    foreColor = Color.White;
                    icon = "⚠";
                    break;
                case NotificationType.Warning:
                    backColor = Color.FromArgb(255, 152, 0); // Оранжевый
                    foreColor = Color.White;
                    icon = "⚠";
                    break;
                case NotificationType.Info:
                default:
                    backColor = Color.FromArgb(76, 175, 80); // Зелёный
                    foreColor = Color.White;
                    icon = "✓";
                    break;
            }

            this.BackColor = backColor;

            // Панель для иконки слева
            Panel iconPanel = new Panel()
            {
                BackColor = Color.FromArgb(30, 0, 0, 0), // Слегка затемненная область
                Size = new Size(60, this.Height),
                Location = new Point(0, 0)
            };

            // Иконка внутри панели
            Label lblIcon = new Label()
            {
                Text = icon,
                ForeColor = foreColor,
                Font = new Font("Segoe UI", 24, FontStyle.Bold),
                AutoSize = false,
                Size = new Size(60, this.Height),
                TextAlign = ContentAlignment.MiddleCenter,
                Location = new Point(0, 0)
            };

            iconPanel.Controls.Add(lblIcon);
            this.Controls.Add(iconPanel);

            // Заголовок (справа от иконки)
            Label lblTitle = new Label()
            {
                Text = title,
                ForeColor = foreColor,
                Font = new Font("Segoe UI", 10, FontStyle.Bold),
                Location = new Point(70, 15), // Смещаем вправо от иконки
                AutoSize = false,
                Size = new Size(240, 25) // Ширина с учетом кнопки закрытия
            };

            // Сообщение (справа от иконки, под заголовком)
            Label lblMessage = new Label()
            {
                Text = message,
                ForeColor = foreColor,
                Font = new Font("Segoe UI", 9),
                Location = new Point(70, 42), // Под заголовком
                AutoSize = false,
                Size = new Size(240, 45) // Достаточно места для 2 строк
            };

            // Кнопка закрытия (в правом верхнем углу)
            Button btnClose = new Button()
            {
                Text = "×",
                ForeColor = foreColor,
                BackColor = Color.Transparent,
                FlatStyle = FlatStyle.Flat,
                Font = new Font("Segoe UI", 16, FontStyle.Bold),
                Size = new Size(30, 30),
                Location = new Point(this.Width - 35, 5),
                Cursor = Cursors.Hand
            };
            btnClose.FlatAppearance.BorderSize = 0;
            btnClose.FlatAppearance.MouseOverBackColor = Color.FromArgb(50, 255, 255, 255);
            btnClose.Click += (s, e) => this.Close();

            this.Controls.Add(lblTitle);
            this.Controls.Add(lblMessage);
            this.Controls.Add(btnClose);

            // Позиция: снизу справа
            int screenWidth = Screen.PrimaryScreen.WorkingArea.Width;
            int screenHeight = Screen.PrimaryScreen.WorkingArea.Height;
            this.Location = new Point(screenWidth, screenHeight - this.Height - 10);
            targetX = screenWidth - this.Width - 10;

            // Таймер для появления
            timerShow = new System.Windows.Forms.Timer();
            timerShow.Interval = 15;
            timerShow.Tick += TimerShow_Tick;

            // Таймер для скрытия
            timerClose = new System.Windows.Forms.Timer();
            timerClose.Interval = displayDuration;
            timerClose.Tick += TimerClose_Tick;

            // Тень и рамка
            this.Paint += (s, e) =>
            {
                // Тень
                using (var shadowBrush = new System.Drawing.Drawing2D.LinearGradientBrush(
                    this.ClientRectangle,
                    Color.FromArgb(50, 0, 0, 0),
                    Color.FromArgb(20, 0, 0, 0),
                    90f))
                {
                    e.Graphics.FillRectangle(shadowBrush, 0, 0, this.Width, 3);
                }

                // Тонкая рамка
                ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle,
                    Color.FromArgb(150, 0, 0, 0), 1, ButtonBorderStyle.Solid,
                    Color.FromArgb(150, 0, 0, 0), 1, ButtonBorderStyle.Solid,
                    Color.FromArgb(150, 0, 0, 0), 1, ButtonBorderStyle.Solid,
                    Color.FromArgb(150, 0, 0, 0), 1, ButtonBorderStyle.Solid);
            };
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            timerShow.Start();
        }

        private void TimerShow_Tick(object sender, EventArgs e)
        {
            if (this.Left > targetX)
            {
                this.Left -= speed;
            }
            else
            {
                this.Left = targetX; // Точная позиция
                timerShow.Stop();
                timerClose.Start();
            }
        }

        private void TimerClose_Tick(object sender, EventArgs e)
        {
            timerClose.Stop();

            // Анимация скрытия (выезжает вправо)
            System.Windows.Forms.Timer timerHide = new System.Windows.Forms.Timer();
            timerHide.Interval = 15;
            timerHide.Tick += (s, args) =>
            {
                if (this.Left < Screen.PrimaryScreen.WorkingArea.Width)
                {
                    this.Left += speed;
                }
                else
                {
                    timerHide.Stop();
                    this.Close();
                }
            };
            timerHide.Start();
        }

        protected override void OnMouseEnter(EventArgs e)
        {
            base.OnMouseEnter(e);
            // Останавливаем таймер закрытия при наведении
            timerClose?.Stop();
        }

        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);
            // Возобновляем таймер
            if (timerClose != null && !timerClose.Enabled)
            {
                timerClose.Start();
            }
        }

        protected override CreateParams CreateParams
        {
            get
            {
                // Делаем форму кликабельной, но не перехватывающей фокус
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x00000008; // WS_EX_TOPMOST
                return cp;
            }
        }
    }
}