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

namespace Crysome.Client.Handlers;

public class ChatForm : Form
{
	private readonly Action<string> _onSend;

	private ListBox _listBox;

	private TextBox _textBox;

	private Button _sendBtn;

	public ChatForm(Action<string> onSend)
	{
		_onSend = onSend;
		Text = "Chat";
		base.Size = new Size(400, 350);
		base.FormBorderStyle = FormBorderStyle.Sizable;
		base.StartPosition = FormStartPosition.CenterScreen;
		base.ShowIcon = false;
		base.FormClosing += delegate
		{
			ChatHandlers.OnFormClosed();
		};
		_listBox = new ListBox
		{
			Dock = DockStyle.Fill,
			Font = new Font("Segoe UI", 10f)
		};
		Panel panel = new Panel
		{
			Dock = DockStyle.Bottom,
			Height = 40
		};
		_textBox = new TextBox
		{
			Dock = DockStyle.Fill,
			Font = new Font("Segoe UI", 10f),
			Margin = new Padding(4)
		};
		_sendBtn = new Button
		{
			Text = "Send",
			Dock = DockStyle.Right,
			Width = 70
		};
		_textBox.KeyDown += delegate(object s, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Return)
			{
				e.SuppressKeyPress = true;
				Send();
			}
		};
		_sendBtn.Click += delegate
		{
			Send();
		};
		panel.Controls.Add(_textBox);
		panel.Controls.Add(_sendBtn);
		base.Controls.Add(_listBox);
		base.Controls.Add(panel);
	}

	public void AddMessage(string from, string msg)
	{
		if (base.InvokeRequired)
		{
			BeginInvoke((MethodInvoker)delegate
			{
				AddMessage(from, msg);
			});
		}
		else if (_listBox != null)
		{
			_listBox.Items.Add("[" + from + "]: " + msg);
			_listBox.TopIndex = Math.Max(0, (_listBox.Items?.Count ?? 1) - 1);
		}
	}

	private void Send()
	{
		string text = _textBox?.Text?.Trim();
		if (!string.IsNullOrEmpty(text))
		{
			_textBox.Clear();
			AddMessage("You", text);
			_onSend?.Invoke(text);
		}
	}
}
