using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Shapes;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using AvaloniaApplication1.DataBase;
using DaireApplication.DataBase;
using DaireApplication.Views;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace DaireApplication;

public partial class Home : UserControl
{
    private Button? _previousButton;
    private Button? currentButton;
    private UserTable _userRepo = new UserTable();
    private MainWindow? _mainWindow;

    public Home()
    {



    }
    public Home(MainWindow mainWindow)
    {
        _mainWindow = mainWindow;
        InitializeComponent();

        // Migrate legacy data to AppData directory
        DataPathManager.MigrateLegacyData();

        setDefaultSettings();
        setDefaultUsers();
        setDefaultRecipe();
        setDefaultMachine();
        SetDefaultMapping();
        SetDefaultConfigration();
        SetDefaultScreen();
        SetDefaultErrorSettings();

        addDynamicButtons();
        _mainWindow.UserName.Holding -= Admin.CloseApplication;




    }
    private async void OnUserButtonClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)  // Ensure the sender is the button that triggered the event
        {
            currentButton = button;
            if (_previousButton != null)
            {
                if (_previousButton == button)
                {
                    if (button.Tag == "1")
                    {
                        CalcGrid.IsVisible = !CalcGrid.IsVisible;
                        machinePic.IsVisible = !machinePic.IsVisible;
                        return;
                    }
                    else
                    {
                        loginBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

                    }

                }


                ResetButtonColor(_previousButton);

            }
            var textBlock = button.Content as TextBlock;

            if (textBlock != null)
            {
                textBlock.Foreground = Avalonia.Media.Brushes.DeepPink;
            }
            button.BorderBrush = Avalonia.Media.Brushes.DeepPink;
            button.BorderThickness = new Thickness(3);
            _previousButton = button;
            if (button.Tag == "1")
            {
                CalcGrid.IsVisible = !CalcGrid.IsVisible;
                machinePic.IsVisible = !machinePic.IsVisible;
            }
            else
            {
                loginBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

            }
            //CalcGrid.IsVisible = !CalcGrid.IsVisible;
            //machinePic.IsVisible = !machinePic.IsVisible;


        }

        //End UI...

    }

    private void LogIn(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {

            var users = _userRepo.ReadUsers();
            string inputText = InputTextBox.Text;
            foreach (var item in users)
            {
                if (currentButton.Content is Grid grid)
                {
                    if (grid.Children[0] is TextBlock textBlock)
                    {
                        if (textBlock.Text == item.UserName)
                        {
                            if (item.IsActive)
                            {
                                if (inputText == item.Password)
                                {
                                    var userName = _mainWindow.FindControl<Button>("UserName");
                                    userName.Content = item.UserName;
                                    Program.currentUser = item;
                                    if (item.IsAdmin == true)
                                    {
                                        _mainWindow.holdingRegister.resetError = 0;

                                        _mainWindow.restBoard = true;

                                        _mainWindow.FindControl<ContentControl>("ContentArea").Content = new Admin(_mainWindow, item);
                                        return;

                                    }
                                    else
                                    {
                                        _mainWindow.FindControl<ContentControl>("ContentArea").Content = new Recipe(_mainWindow, item);


                                        InputTextBox.Text = string.Empty;
                                        return;
                                    }

                                }
                                else
                                {
                                    _mainWindow.TextCenter.HorizontalAlignment = HorizontalAlignment.Center;
                                    _mainWindow.footerMsg.Text = "Wrong Password!!";
                                    _mainWindow.footerMsg.IsVisible = true;
                                    _mainWindow.footer.Background = Avalonia.Media.Brushes.Red;
                                    _mainWindow.footerMsg.Foreground = Avalonia.Media.Brushes.White;
                                    _mainWindow.footerMsg.HorizontalAlignment = HorizontalAlignment.Center;
                                    _mainWindow.footerDateContainer.IsVisible = false;
                                    _mainWindow.footerStartBtn.IsVisible = false;
                                }
                            }
                            else
                            {
                                var userName = _mainWindow.FindControl<Button>("UserName");
                                userName.Content = item.UserName;
                                Program.currentUser = item;
                                if (item.IsAdmin == true)
                                {
                                    _mainWindow.holdingRegister.resetError = 0;
                                    _mainWindow.restBoard = true;

                                    _mainWindow.FindControl<ContentControl>("ContentArea").Content = new Admin(_mainWindow, item);

                                    return;

                                }
                                else
                                {
                                    _mainWindow.FindControl<ContentControl>("ContentArea").Content = new Recipe(_mainWindow, item);


                                    InputTextBox.Text = string.Empty;
                                    return;
                                }
                            }
                        }


                    }
                }




            }

        }


        // Display or use the input text

        // Clear the text after showing the message
        InputTextBox.Text = string.Empty;
    }

    private void OnKeyClick(object? sender, RoutedEventArgs e)
    {
        if (sender is Button button)
        {
            // Append the button's content to the input box
            InputTextBox.Text += button.Content?.ToString();
        }

    }
    private void OnBackClick(object? sender, RoutedEventArgs e)
    {
        if (!string.IsNullOrEmpty(InputTextBox.Text))
        {
            // Remove the last character from the text box
            InputTextBox.Text = InputTextBox.Text.Remove(InputTextBox.Text.Length - 1);
        }
    }
    private void ResetButtonColor(Button button)
    {
        button.BorderBrush = Avalonia.Media.Brushes.White;

        var textBlock = button.Content as TextBlock;

        if (textBlock != null)
        {
            textBlock.Foreground = Avalonia.Media.Brushes.Black;
        }
        // Reset the color of the TextBlock inside the button
    }


    private void addDynamicButtons()
    {
        var users = _userRepo.ReadUsers();
        var grid = this.FindControl<Grid>("DynamicGrid");
        int userIdex = 0;
        if (users.Count < 2)
        {
            for (int i = 0; i < (int)Math.Ceiling((double)users.Count / 2); i++)  // Example: 20 rows
            {
                grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

                // Add content for each column
                for (int col = 0; col < 2; col++)
                {
                    // StackPanel for the LED indicator dots
                    var indicatorPanel = new StackPanel
                    {
                        Orientation = Orientation.Horizontal,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        Margin = new Thickness(10),
                        Spacing = 10
                    };

                    // Adding the indicator dots dynamically
                    if (users[userIdex + col].IsAdmin)
                    {
                        var colors = new[] { Brush.Parse("#A4275D"), Brush.Parse("#A4275D"), Brush.Parse("#A4275D") };
                        foreach (var color in colors)
                        {
                            indicatorPanel.Children.Add(new Rectangle
                            {
                                Width = 30,
                                Height = 10,
                                Fill = color,
                                RadiusX = 3,
                                RadiusY = 3,
                                Margin = new Thickness(3),
                                VerticalAlignment = VerticalAlignment.Bottom,
                            });
                        }
                    }
                    else if (users[userIdex + col].CanEdit)
                    {
                        var colors = new[] { Brush.Parse("#A4275D"), Brush.Parse("#A4275D") };
                        foreach (var color in colors)
                        {
                            indicatorPanel.Children.Add(new Rectangle
                            {
                                Width = 30,
                                Height = 10,
                                Fill = color,
                                RadiusX = 3,
                                RadiusY = 3,
                                Margin = new Thickness(3),
                                VerticalAlignment = VerticalAlignment.Bottom,
                            });
                        }
                    }
                    else
                    {
                        var colors = new[] { Brush.Parse("#A4275D") };
                        foreach (var color in colors)
                        {
                            indicatorPanel.Children.Add(new Rectangle
                            {
                                Width = 30,
                                Height = 10,
                                Fill = color,
                                RadiusX = 3,
                                RadiusY = 3,
                                Margin = new Thickness(3),
                                VerticalAlignment = VerticalAlignment.Bottom,
                            });
                        }
                    }

                    // Create a Grid for button content with two rows:
                    // Row 0 (star) holds the text (centered) and Row 1 (auto) holds the indicator dots at the bottom.
                    var buttonContent = new Grid();
                    buttonContent.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
                    buttonContent.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

                    // TextBlock centered in first row
                    var textBlock = new TextBlock
                    {
                        Padding = new Thickness(10),
                        Text = users[userIdex + col].UserName,
                        FontSize = 40,
                        FontWeight = FontWeight.Normal,
                        Foreground = Avalonia.Media.Brushes.Black,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Center,
                    };

                    // Place the text in the first row
                    Grid.SetRow(textBlock, 0);
                    // Place the indicator panel in the second row
                    Grid.SetRow(indicatorPanel, 1);

                    // Add both elements to the grid
                    buttonContent.Children.Add(textBlock);
                    buttonContent.Children.Add(indicatorPanel);

                    // Create the button with the new content layout
                    var button = new Button
                    {
                        Width = 290,
                        Height = 190,
                        Margin = new Thickness(10),
                        Content = buttonContent,
                        Tag = users[userIdex + col].IsActive ? "1" : "0",
                        CornerRadius = new CornerRadius(10),
                        Background = Avalonia.Media.Brushes.White,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Bottom,
                    };

                    button.Click += OnUserButtonClick;
                    grid.Children.Add(button);
                    Grid.SetRow(button, i);
                    Grid.SetColumn(button, col);
                }
                userIdex += 2;
            }

        }
        else
        {
            for (int i = 0; i < (int)Math.Ceiling((double)users.Count / 2); i++)  // Example: 20 rows
            {
                grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

                // Add content for each column
                for (int col = 0; col < 2; col++)
                {
                    // StackPanel for the LED indicator dots
                    var indicatorPanel = new StackPanel
                    {
                        Orientation = Orientation.Horizontal,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        Margin = new Thickness(10),
                        Spacing = 10
                    };

                    // Adding the indicator dots dynamically
                    if (users[userIdex + col].IsAdmin)
                    {
                        var colors = new[] { Brush.Parse("#A4275D"), Brush.Parse("#A4275D"), Brush.Parse("#A4275D") };
                        foreach (var color in colors)
                        {
                            indicatorPanel.Children.Add(new Rectangle
                            {
                                Width = 30,
                                Height = 10,
                                Fill = color,
                                RadiusX = 3,
                                RadiusY = 3,
                                Margin = new Thickness(3),
                                VerticalAlignment = VerticalAlignment.Bottom,
                            });
                        }
                    }
                    else if (users[userIdex + col].CanEdit)
                    {
                        var colors = new[] { Brush.Parse("#A4275D"), Brush.Parse("#A4275D") };
                        foreach (var color in colors)
                        {
                            indicatorPanel.Children.Add(new Rectangle
                            {
                                Width = 30,
                                Height = 10,
                                Fill = color,
                                RadiusX = 3,
                                RadiusY = 3,
                                Margin = new Thickness(3),
                                VerticalAlignment = VerticalAlignment.Bottom,
                            });
                        }
                    }
                    else
                    {
                        var colors = new[] { Brush.Parse("#A4275D") };
                        foreach (var color in colors)
                        {
                            indicatorPanel.Children.Add(new Rectangle
                            {
                                Width = 30,
                                Height = 10,
                                Fill = color,
                                RadiusX = 3,
                                RadiusY = 3,
                                Margin = new Thickness(3),
                                VerticalAlignment = VerticalAlignment.Bottom,
                            });
                        }
                    }

                    // Create a Grid for button content with two rows:
                    // Row 0 (star) holds the text (centered) and Row 1 (auto) holds the indicator dots at the bottom.
                    var buttonContent = new Grid();
                    buttonContent.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
                    buttonContent.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

                    // TextBlock centered in first row
                    var textBlock = new TextBlock
                    {
                        Padding = new Thickness(10),
                        Text = users[userIdex + col].UserName,
                        FontSize = 40,
                        FontWeight = FontWeight.Normal,
                        Foreground = Avalonia.Media.Brushes.Black,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Center,
                    };

                    // Place the text in the first row
                    Grid.SetRow(textBlock, 0);
                    // Place the indicator panel in the second row
                    Grid.SetRow(indicatorPanel, 1);

                    // Add both elements to the grid
                    buttonContent.Children.Add(textBlock);
                    buttonContent.Children.Add(indicatorPanel);

                    // Create the button with the new content layout
                    var button = new Button
                    {
                        Width = 290,
                        Height = 190,
                        Margin = new Thickness(10),
                        Tag = users[userIdex + col].IsActive ? "1" : "0",
                        Content = buttonContent,
                        CornerRadius = new CornerRadius(10),
                        Background = Avalonia.Media.Brushes.White,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Bottom,
                    };

                    button.Click += OnUserButtonClick;
                    grid.Children.Add(button);
                    Grid.SetRow(button, i);
                    Grid.SetColumn(button, col);
                }
                userIdex += 2;
            }

        }
    }


    private void setDefaultUsers()
    {
        string filePath = DataPathManager.GetDataFilePath("Users.csv");
        List<UserTable> users = new List<UserTable>();

        if (!File.Exists(filePath))
        {
            string csvHeader = "ID,UserName,Password,CanEdit,IsAdmin,IsActive";

            users.Add(new UserTable
            {
                Id = 1,
                UserName = "ADMIN",
                Password = "1111",
                CanEdit = true,
                IsAdmin = true,
                IsActive = false
            }
           );
            users.Add(new UserTable
            {
                Id = 2,
                UserName = "CHEF",
                Password = "2222",
                CanEdit = true,
                IsAdmin = false,
                IsActive = false

            }
          );
            users.Add(new UserTable
            {
                Id = 3,
                UserName = "OPERATOR1",
                Password = "3333",
                CanEdit = false,
                IsAdmin = false,
                IsActive = false


            }
          );
            users.Add(new UserTable
            {
                Id = 4,
                UserName = "OPERATOR2",
                Password = "4444",
                CanEdit = false,
                IsAdmin = false,
                IsActive = false


            }
          );
            List<string> lines = new List<string>();
            foreach (var item in users)
            {
                lines.Add(string.Join(",", [item.Id, item.UserName, item.Password, item.CanEdit ? "1" : "0", item.IsAdmin ? "1" : "0", item.IsActive ? "1" : "0"]));
            }
            File.WriteAllLines(filePath, new string[] { csvHeader });
            File.AppendAllLines(filePath, lines);
        }
    }

    private void setDefaultRecipe()
    {
        string filePath = DataPathManager.GetDataFilePath("Recipe.csv");
        List<RecipeTable> recipes = new List<RecipeTable>();

        if (!File.Exists(filePath))
        {
            string csvHeader = "ID,Name,TankTemp,FountainTemp,Mixer,Fountain,MoldHeater,Vibration,VibHeater,Pedal,PedalOnTime,PedalOffTime,HeatingGoal,CoolingGoal,PouringGoal";

            recipes.Add(new RecipeTable
            {
                Id = 1,
                Name = "MILK",
                Mixer = false,
                Fountain = false,
                MoldHeater = false,
                Vibration = false,
                VibHeater = false,
                Pedal = false

            }
           );
            List<string> lines = new List<string>();
            foreach (var item in recipes)
            {
                if (item != null)
                {
                    lines.Add(string.Join(",", [1, item.Name, item.TankTemp, item.FountainTemp, item.Mixer.Value ? "1" : "0", item.Fountain.Value ? "1" : "0", item.MoldHeater.Value ? "1" : "0", item.Vibration.Value ? "1" : "0", item.VibHeater.Value ? "1" : "0", item.Pedal.Value ? "1" : "0", item.PedalOnTime, item.PedalOffTime, item.HeatingGoal, item.CoolingGoal, item.PouringGoal]));
                }
            }

            File.WriteAllLines(filePath, new string[] { csvHeader });
            File.AppendAllLines(filePath, lines);
        }
    }

    private void setDefaultMachine()
    {
        string filePath = DataPathManager.GetDataFilePath("Machine.csv");
        MachineTable machine = new MachineTable();

        if (!File.Exists(filePath))
        {
            string csvHeader = "ID,TankMaxHeat,PumbMaxHeat,PumbDelay,MixerDelay,HeatingDelay,CoolingDelay,PouringDelay,PumbMinHeat,AbsMaxTemp,AbsMinTemp,PreHeatingTemp,SetTemp1,SetTemp2,SetTemp3,SetTemp4";

            string line = string.Join(",", ["1", machine.TankMaxHeat, machine.PumbMaxHeat, machine.PumbDelay, machine.MixerDelay, machine.HeatingDelay, machine.CoolingDelay, machine.PouringDelay, machine.PumbMinHeat, machine.AbsMaxHeat, machine.AbsMinHeat, machine.PreHeatingTemp, machine.setTemp1, machine.setTemp2, machine.setTemp3, machine.setTemp4]);

            File.WriteAllLines(filePath, new string[] { csvHeader });
            File.AppendAllText(filePath, line);
        }
    }


    private void SetDefaultMapping()
    {
        string filePath = DataPathManager.GetDataFilePath("Mapping.csv");

        if (!File.Exists(filePath))
        {
            string csvHeader = "Id,Name,Address,IsRead,BitNumbers";

            string[] defaultMappings =
            {
            string.Join(",", "1", "Pedal", "1", "1", "0"),
            string.Join(",", "2", "Cover Sensor", "1", "1", "1"),
            string.Join(",", "3", "E-Stop", "1", "1", "2"),
            string.Join(",", "4", "Tank Bottom Temp", "8", "1", "8"),
            string.Join(",", "5", "Tank Wall Temp", "9", "1", "9"),
            string.Join(",", "6", "Pump Temp", "10", "1", "10"),
            string.Join(",", "7", "Fountain Temp", "11", "1", "11"),
            string.Join(",", "8", "Vibrator Heater", "2", "0", "0"),
            string.Join(",", "9", "Mold Heater", "2", "0", "1"),
            string.Join(",", "10", "Alarm", "2", "0", "2"),
            string.Join(",", "11", "Vibrator", "1", "0", "0"),
            string.Join(",", "12", "Water", "1", "0", "1"),
            string.Join(",", "13", "Compressor", "1", "0", "2"),
            string.Join(",", "14", "HELIX Heater", "1", "0", "3"),
            string.Join(",", "15", "Tank Heater Bottom", "1", "0", "4"),
            string.Join(",", "16", "Tank Heater Wall", "1", "0", "5"),
            string.Join(",", "17", "Mixer", "3", "0", "0"),
            string.Join(",", "18", "Helix", "3", "0", "1")
        };

            File.WriteAllLines(filePath, new[] { csvHeader }.Concat(defaultMappings));
        }
    }

    private void SetDefaultConfigration()
    {
        string filePath = DataPathManager.GetDataFilePath("Configration.csv");

        if (!File.Exists(filePath))
        {
            string csvHeader = "Id,Max,Min,H_out,FC_out,SC_out,kp,ki,kd,kl,Name,I_Nuet,I_Mot1,I_Mot2,FC_Threshold,HeatConRange";

            string[] defaultConfigrations =
            {
            string.Join(",", "1", $"70", "0", "4", "-1", "-1", "50", "30", "20", "0","Tank Heater Bottom","14","3","3","0.3","10.0"),
            string.Join(",", "2", $"70", "0", "5", "-1", "-1", "50", "30", "20", "0","Tank Heater Wall","0","0","0","0.3","10.0"),
            string.Join(",", "3", $"70", $"-10", "3", "2|1", "1", "50", "30", "20", "0","HELIX Heater","0","0","0","0.3","10.0"),
            string.Join(",", "4", $"70", "0", "3", "2|1", "1", "50", "30", "20", "0","","0","0","0","0.3","5")
        };

            File.WriteAllLines(filePath, new[] { csvHeader }.Concat(defaultConfigrations));
        }
    }

    private void setDefaultSettings()
    {
        _mainWindow.minimizeBtn.IsVisible = false;

        //Set Track Up
        _mainWindow.HomeTrack.IsVisible = true;
        //_mainWindow.HomePolygon.Stroke = Brush.Parse("#A4275D");
        _mainWindow.RecipeSelTrack.IsVisible = false;
        _mainWindow.RecipeEditTrack.IsVisible = false;
        _mainWindow.RecipePanelTrack.IsVisible = false;
        _mainWindow.RunInterfaceTrack.IsVisible = false;
        _mainWindow.SettingTrack.IsVisible = false;
        _mainWindow.TitleBtn.IsVisible = false;
        _mainWindow.DiagnosticsTrack.IsVisible = false;
        _mainWindow.AdvanceSettingsTrack.IsVisible = false;
        _mainWindow.SoftwareTrack.IsVisible = false;
        _mainWindow.version.IsVisible = false;
        _mainWindow.ManualControlTrack.IsVisible = false;




        //Set Footer
        _mainWindow.footerMsg.Text = "";
        _mainWindow.footerMsg.MaxWidth = 1000;
        _mainWindow.footer.Background = Avalonia.Media.Brushes.WhiteSmoke;
        _mainWindow.footerMsg.Foreground = Avalonia.Media.Brushes.Black;
        _mainWindow.footerDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
        _mainWindow.footerTime.Text = DateTime.Now.ToString("hh:mm tt");
        _mainWindow.footerDateContainer.IsVisible = true;
        _mainWindow.footerStartBtn.IsVisible = false;
        _mainWindow.adminBtns.IsVisible = false;
        _mainWindow.chefBtns.IsVisible = false;

    }

    private void SetDefaultErrorSettings()
    {
        string filePath = DataPathManager.GetDataFilePath("ErrorSettings.csv");
        if (!File.Exists(filePath))
        {
            ErrorSettingsTable error = new ErrorSettingsTable
            {
                Id = 1,
                gridFreq = 50,
                phaseNumber = 3,
                extPower = true,
                phaseVoltage = 220
            };

            string csvHeader = "Id,gridFreq,phaseNumber,extPower,phaseVoltage";
            string line = string.Join(",", new[] { error.Id.ToString(), error.gridFreq.ToString(), error.phaseNumber.ToString(), error.extPower ? "1" : "0", error.phaseVoltage.ToString() });

            File.WriteAllLines(filePath, new[] { csvHeader, line });
        }
    }
    private void SetDefaultScreen()
    {
        string filePath = DataPathManager.GetDataFilePath("Screen.csv");
        if (!File.Exists(filePath))
        {
            ScreeenTable screen = new ScreeenTable
            {
                Id = 1,
                brightness = 100,
                dimSec = 3300,
                offSec = 3600,
                port = "",
                boundRate = 19200,
                parity = 1,
                stopBits = 0,
                sendingTime = 50,
                warningLimit = 1,
                errorLimit = 2
            };

            string csvHeader = "Id,Brightness,DimSec,OffSec,Port,BoundRate,Parity,StopBits,SendingTime,WarningLimit,ErrorLimit";
            string line = string.Join(",", new[] {
                screen.Id.ToString(),
                screen.brightness.ToString(),
                screen.dimSec.ToString(),
                screen.offSec.ToString(),
                screen.port,
                screen.boundRate.ToString(),
                screen.parity.ToString(),
                screen.stopBits.ToString(),
                screen.sendingTime.ToString(),
                screen.warningLimit.ToString(),
                screen.errorLimit.ToString()
            });

            File.WriteAllLines(filePath, new[] { csvHeader, line });
        }

    }
}