using Accessibility;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using qtc_net_client_2.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace qtc_net_client_2.Controls
{
    public class ContactEntryControl : Control
    {
        public Image? Avatar { get; set; }
        public string Username = "Username";
        public Color StatusColor = Color.Gray;

        private Font? usernameFont;

        public event EventHandler? ContactDoubleClicked;

        private bool IsHoveredOn;
        public ContactEntryControl()
        {
            // reduce flicker
            SetStyle(ControlStyles.AllPaintingInWmPaint |
                     ControlStyles.ResizeRedraw |
                     ControlStyles.UserPaint |
                     ControlStyles.OptimizedDoubleBuffer, true);

            Height = 36;
        }

        protected override void OnPaintBackground(PaintEventArgs pevent) { } // prevent this

        protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

            Rectangle rect = ClientRectangle;

            using var brush = new LinearGradientBrush(rect, StatusColor, BackColor, LinearGradientMode.Horizontal);

            Color usernameForeColor = Color.Black;
            if(IsHoveredOn)
            {
                usernameForeColor = Color.White;
                usernameFont = new Font("Segoe UI", 9, FontStyle.Bold | FontStyle.Underline);
            }
            else
            {
                usernameFont = new Font("Segoe UI", 9, FontStyle.Bold);
            }

            e.Graphics.FillRectangle(brush, rect);

            int margin = 6;
            int imgSize = 32;

            Rectangle avatarRect = new(margin, (Height - imgSize) / 2, imgSize, imgSize);
            e.Graphics.DrawImage(Avatar ?? Resources.DefaultPfp, avatarRect);

            int textLeft = avatarRect.Right + margin;

            Rectangle rectText = new(textLeft, 0, Width - textLeft - 8, Height - 16);
            TextRenderer.DrawText(e.Graphics, Username, usernameFont, rectText, usernameForeColor, TextFormatFlags.Left | TextFormatFlags.VerticalCenter);
        }

        protected override void OnMouseDoubleClick(MouseEventArgs e)
        {
            base.OnMouseDoubleClick(e);
            ContactDoubleClicked?.Invoke(this, EventArgs.Empty);
        }

        protected override void OnMouseHover(EventArgs e)
        {
            base.OnMouseHover(e);
            IsHoveredOn = true;
            Invalidate();
        }

        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);
            IsHoveredOn = false;
            Invalidate();
        }
    }
}
