using qtcnet_client.Controls;
using qtcnet_client.Factories;
using qtcnet_client.Properties;
using QtCNETAPI.Dtos.User;
using QtCNETAPI.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace qtcnet_client.Forms
{
    public partial class DirectMessageForm : Form
    {
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string UserId { get; set; } = string.Empty;
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public string Username { get; set; } = "Username";
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public Image ProfileImage { get; set; } = Resources.DefaultPfp;

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Dictionary<string, Bitmap> UserProfileImages { get; set; } = [];
        public string SentMessage { get; private set; } = string.Empty;

        public event EventHandler? OnSend;
        public event EventHandler? OnClose;

        private readonly ImageFactory _imgFactory;
        public DirectMessageForm(ImageFactory imageFactory)
        {
            _imgFactory = imageFactory;
            InitializeComponent();
        }

        private void DirectMessageForm_Load(object sender, EventArgs e)
        {
            lblUsername.Text = Username;
            pbProfileImage.Image = ProfileImage;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (ValidateChatBox())
            {
                SentMessage = rtxtChatbox.Text;
                OnSend?.Invoke(this, EventArgs.Empty);
                rtxtChatbox.Clear();
            }
        }

        private void rtxtChatbox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (ValidateChatBox())
                {
                    SentMessage = rtxtChatbox.Text;
                    OnSend?.Invoke(this, EventArgs.Empty);
                    rtxtChatbox.Clear();
                }
            }
        }

        private void DirectMessageForm_FormClosed(object sender, FormClosedEventArgs e) => OnClose?.Invoke(this, EventArgs.Empty);

        public async Task LoadProfileImage(MessageControl ctrl, UserInformationDto user)
        {
            _ = Task.Run(async () =>
            {
                var img = await AddUserProfileImageToDictionary(user);

                if (img == null || ctrl.IsDisposed)
                    return;

                if (ctrl.InvokeRequired)
                    ctrl.Invoke(() =>
                    {
                        ctrl.ProfileImage = img;
                        ctrl.ReloadProfileImage();
                    });
                else
                {
                    ctrl.ProfileImage = img;
                    ctrl.ReloadProfileImage();
                }
            });
        }

        private async Task<Bitmap?> AddUserProfileImageToDictionary(UserInformationDto user)
        {
            if (UserProfileImages.TryGetValue(user.Id, out var image))
                return image;
            else
            {
                var img = _imgFactory.GetAndCreateProfileImage(user.Id, -1, user.ProfileCosmeticId);
                UserProfileImages.Add(user.Id, img);
                return img;
            }
        }

        public void AddMessage(MessageControl messageCtrl)
        {
            messageCtrl.Width = flpMessages.ClientSize.Width - 10;
            messageCtrl.Margin = new Padding(0, 0, 0, 6);

            if (flpMessages.InvokeRequired)
            {
                Invoke(() =>
                {
                    flpMessages.Controls.Add(messageCtrl);
                    flpMessages.ScrollControlIntoView(messageCtrl);
                });
            }
            else
            {
                flpMessages.Controls.Add(messageCtrl);
                flpMessages.ScrollControlIntoView(messageCtrl);
            }
        }

        private bool ValidateChatBox()
        {
            return !string.IsNullOrWhiteSpace(rtxtChatbox.Text) || !string.IsNullOrEmpty(rtxtChatbox.Text);
        }
    }
}
