using Percent___Qualification_work.Classes;
using Percent___Qualification_work.Properties;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace Percent___Qualification_work.userControls
{
    public partial class planList : UserControl
    {
        // Class-level variables
        private const int PlansPerPage = 4;
        private int currentPage = 1;
        public List<DataRow> plansList;
        private string order;

        // Constructor
        public planList()
        {
            InitializeComponent();
  
            newPlanPanel.Visible = false;
            priorityPicker.DropDownStyle = ComboBoxStyle.DropDownList;
            orderPicker.DropDownStyle = ComboBoxStyle.DropDownList;
            order = "date";
        }

        // Load plans for the specified user
        public void LoadPlans(int userID)
        {
            DataTable plansTable = DatabaseConnection.Instance.GetPlans(userID, order);
            plansList = plansTable.AsEnumerable().ToList(); // Convert DataTable to List 
            DisplayPlans(); // Display the first page of plans
        }

        // Display plans for the current page
        private void DisplayPlans()
        {
            planListFlowPanel.Controls.Clear(); // Clear existing controls

            // Calculate start and end indices for pagination
            int startIndex = (currentPage - 1) * PlansPerPage;
            int endIndex = Math.Min(startIndex + PlansPerPage, plansList.Count);

            // Create and add a card for each plan in the current page
            for (int i = startIndex; i < endIndex; i++)
            {
                DataRow plan = plansList[i];
                Panel planCard = CreatePlanCard(plan);
                planListFlowPanel.Controls.Add(planCard);
            }

            UpdatePaginator(); // Update pagination buttons
        }

        // Create a card for a plan
        private Panel CreatePlanCard(DataRow plan)
        {

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

            // Display plan data
            Label planName = new Label { Text = plan["name"].ToString(), AutoSize = true, Location = new Point(10, 10) };
            Label planDate = new Label { Text = $"Date: {DateTime.Parse(plan["date"].ToString()):dd.MM.yyyy}", AutoSize = true, Location = new Point(10, 30) };
            Label planPriority = new Label { Text = $"Priority: {plan["priority"]}", AutoSize = true, Location = new Point(100, 30) };

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

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

            // Add controls to the card
            card.Controls.Add(planName);
            card.Controls.Add(planDate);
            card.Controls.Add(planPriority);
            card.Controls.Add(editButton);
            card.Controls.Add(deleteButton);

            return card;
        }

        // Update paginator buttons based on the current page
        private void UpdatePaginator()
        {
            prevButton.Enabled = currentPage > 1;
            nextButton.Enabled = currentPage < (plansList.Count + PlansPerPage - 1) / PlansPerPage;
        }

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

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

        // Edit a plan 
        private void EditPlan(int planID)
        {
            EditPlanControl editPlanControl = new EditPlanControl();
            editPlanControl.PlanUpdated += (s, e) => LoadPlans(Authentication.ActiveUserID);

            mainPanel.Controls.Add(editPlanControl);
            editPlanControl.Dock = DockStyle.Fill;
            editPlanControl.BringToFront();
            editPlanControl.Visible = true;
            editPlanControl.InitializeEditPlanControl(planID); // Call the initialization method
        }

        // Delete a plan
        private void DeletePlan(int planID)
        {

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

            if (result == DialogResult.Yes)
            {
                DatabaseConnection.Instance.DeletePlan(planID);
                LoadPlans(Authentication.ActiveUserID); // Reload the current page after deletion

            }
        }

        private void orderPicker_SelectedIndexChanged(object sender, EventArgs e)
        {
            order = orderPicker.Text;
            LoadPlans(Authentication.ActiveUserID);
        }

        // ComboBox item class
        public class ComboBoxItem
        {
            public string Text { get; set; }
            public int Value { get; set; }

            public override string ToString()
            {
                return Text; // Display the text in the ComboBox
            }
        }

        // Open the new plan panel
        private void newPlan_Click(object sender, EventArgs e)
        {
            newPlanPanel.Visible = true;
        }

        // Close the new plan panel
        public void HidePanel()
        {
            newPlanPanel.Visible = false;
        }

        // Clear input fields in the new plan panel
        public void ClearInputs()
        {
            newPlanPanel.Visible = false;
            planName.Text = string.Empty;
            priorityPicker.SelectedItem = null;
        }

        // Populate the priority ComboBox
        private void PopulateCombo()
        {
            priorityPicker.Items.Add(new ComboBoxItem { Text = "Low", Value = 1 });
            priorityPicker.Items.Add(new ComboBoxItem { Text = "Medium", Value = 2 });
            priorityPicker.Items.Add(new ComboBoxItem { Text = "High", Value = 3 });
        }

        // Load event handler for the plan list control
        private void planList_Load(object sender, EventArgs e)
        {
            PopulateCombo();
            LoadPlans(Authentication.ActiveUserID);
        }

        // Add a new plan
        private void addPlanbtn_Click(object sender, EventArgs e)
        {
            string plan = planName.Text;
            string date = datePicker1.Value.ToString("yyyy-MM-dd"); // Format to MySQL 'DATE' format
            var priority = priorityPicker.SelectedItem as ComboBoxItem;

            if (!string.IsNullOrEmpty(plan) && !string.IsNullOrEmpty(date) && priority != null)
            {
                // Use the formatted date string for the database insertion
                DatabaseConnection.Instance.AddPlan(Authentication.ActiveUserID, plan, date, priority.Value);
                MessageBox.Show("Plan added successfully!");
            }
            else
            {
                MessageBox.Show("Please fill in all the fields!");
                return;
            }

            ClearInputs();
            LoadPlans(Authentication.ActiveUserID);
        }

        // Back button -> clear new plan inputs and hides it
        private void backButton_Click(object sender, EventArgs e)
        {
            ClearInputs();
            HidePanel();
        }     
    }
}
