using Percent___Qualification_work.Classes;
using Percent___Qualification_work.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace Percent___Qualification_work.userControls
{
    public partial class Notepad : UserControl
    {

        private const int notesPerPage = 4;
        private int currentPage = 1;
        public List<DataRow> notesList;

        public Notepad()
        {
            InitializeComponent();
            newNotePanel.Visible = false;
        }

        private void LoadNotes(int userID)
        {
            DataTable notesTable = DatabaseConnection.Instance.GetNotes(userID);
            notesList = notesTable.AsEnumerable().ToList();
            DisplayNotes();
        }

        private void DisplayNotes()
        {
            noteflowPanel.Controls.Clear();

            int startIndex = (currentPage - 1) * notesPerPage;
            int endIndex = Math.Min(startIndex + notesPerPage, notesList.Count);

            for(int i = startIndex; i < endIndex; i++)
            {
                DataRow note = notesList[i];
                Panel noteCard = CreateNoteCard(note);
                noteflowPanel.Controls.Add(noteCard);

            }

            UpdatePaginator();
        }

        private void UpdatePaginator()
        {
            prevButton.Enabled = currentPage > 1;
            nextButton.Enabled = currentPage < (notesList.Count + notesPerPage - 1) / notesPerPage;
        }

        // Navigate to the previous page
        private void prevButton_Click_1(object sender, EventArgs e)
        {
            if (currentPage > 1)
            {
                currentPage--;
                DisplayNotes();
            }
        }

        // Navigate to the next page
        private void nextButton_Click(object sender, EventArgs e)
        {
            if (currentPage < (notesList.Count + notesPerPage - 1) / notesPerPage)
            {
                currentPage++;
                DisplayNotes();
            }
        }

        private Panel CreateNoteCard(DataRow note)
        {

            // Card for the Note
            Panel card = new Panel
            {
                BorderStyle = BorderStyle.FixedSingle,
                Size = new Size(760, 50)
            };

            // Display Note data
            Label noteName = new Label { Text = note["name"].ToString(), AutoSize = true, Location = new Point(10, 18) };

            Button editButton = new Button { Image = Resources.edit, Size = new Size(30, 30), Location = new Point(610, 10), Tag = note["id"] };
            editButton.Click += (s, e) => EditNote(Convert.ToInt32(note["id"]));

            Button downloadButton = new Button { Image = Resources.download, Size = new Size(30, 30), Location = new Point(660,10), Tag = note["id"] };
            downloadButton.Click += (s, e) => DownloadNote(Convert.ToInt32(note["id"]));

            Button deleteButton = new Button { Image = Resources.cross, Size = new Size(30, 30), Location = new Point(710, 10), Tag = note["id"] };
            deleteButton.Click += (s, e) => DeleteNote(Convert.ToInt32(note["id"]));

            

            // Add controls to the card
            card.Controls.Add(noteName);
            card.Controls.Add(editButton);
            card.Controls.Add (downloadButton);
            card.Controls.Add(deleteButton);

            return card;
        }

        private void newNoteBtn_Click(object sender, EventArgs e)
        {
            newNotePanel.Visible = true;
            int count = DatabaseConnection.Instance.NoteCount(Authentication.ActiveUserID) +1;
            noteName.Text = "New note " + count;
        }

        private void saveNote_Click(object sender, EventArgs e)
        {
            string name = noteName.Text;
            string text = noteText.Text;

            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(text))
            {
                // Use the formatted date string for the database insertion
                DatabaseConnection.Instance.NewNote(Authentication.ActiveUserID, name, text);
                MessageBox.Show("Note save successfully");
                LoadNotes(Authentication.ActiveUserID);
            }
            else
            {
                MessageBox.Show("Please fill in all the fields!");
                return;
            }

            Return();

        }

        private void EditNote(int noteID)
        {
            EditNoteControl editNoteControl = new EditNoteControl();
            editNoteControl.NoteUpdated += (s, e) => LoadNotes(Authentication.ActiveUserID);

            mainPanel.Controls.Add(editNoteControl);
            editNoteControl.Dock = DockStyle.Fill;
            editNoteControl.BringToFront();
            editNoteControl.Visible = true;
            editNoteControl.InitializeEditNoteControl(noteID); // Call the initialization method
        }

        private void DownloadNote(int noteID)
        {
            DialogResult result = MessageBox.Show("Are you sure you want to download this note as a .txt file?", "Confirm download", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                string[] noteData = DatabaseConnection.Instance.GetNoteText(noteID);

                if (noteData != null && noteData.Length == 2)
                {
                    string defaultFileName = noteData[0] + ".txt"; // Use note name as default filename
                    string fileText = noteData[1];

                    // Ensure valid filename by replacing invalid characters
                    defaultFileName = string.Join("_", defaultFileName.Split(Path.GetInvalidFileNameChars())); // Replaces the invalid characters that are not allowed in the file name

                    // Configure SaveFileDialog
                    using (SaveFileDialog saveFileDialog = new SaveFileDialog())
                    {
                        saveFileDialog.FileName = defaultFileName;
                        saveFileDialog.Filter = "Text Files (*.txt)|*.txt";
                        saveFileDialog.DefaultExt = "txt";  // Sets the extension to .txt by default

                        if (saveFileDialog.ShowDialog() == DialogResult.OK)
                        {
                            string filePath = saveFileDialog.FileName; // User chooses the file directory

                            
                            File.WriteAllText(filePath, fileText); // Write the text to the selected file

                            MessageBox.Show("Note downloaded successfully as " + filePath, "Download Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Failed to download the note. No data found.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void DeleteNote(int noteID)
        {

            DialogResult result = MessageBox.Show("Are you sure you want to delete this note?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                DatabaseConnection.Instance.DeleteNote(noteID);
                LoadNotes(Authentication.ActiveUserID); // Reload the current page after deletion

            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            Return();
        }

        private void Return()
        {
            newNotePanel.Visible = false;
            noteName.Text = string.Empty;
            noteText.Text = string.Empty;
        }

        private void Notepad_Load(object sender, EventArgs e)
        {
            LoadNotes(Authentication.ActiveUserID);
        }
    }
}
