using System.Collections.Generic;
using UnityEngine.UIElements;
using WorldBuilder.Plugins;
using WorldBuilder.Plugins.UI;
using WorldBuilder.UI;
using XR4EDPlugin.BackendCalls;
using Nuro.Processes;

public class XR4EDWizardDemoWindow : UIWindow
{
    // left Table
    private IUITable m_ProductsTable = null;
    // right table
    private IUITable m_FilesTable = null;

    public XR4EDWizardDemoWindow(IReferenceProvider referenceProvider, VisualElement parent) :
        base(referenceProvider, parent, UIWindowTransitions.BottomSideTransition,
            WindowStyles.Default | WindowStyles.Footer | WindowStyles.FotterPadding,
            "XR4ED_WizardDemoWindow")
    {
        IUIElementFactory elementFactory = referenceProvider.ElementFactory;

        Window.style.width = 1400;

        CreateTopSectionUI(elementFactory);

        elementFactory.CreateSpaceVertical(Content, 10);
        elementFactory.CreateSeperatorHorizontal(Content);
        elementFactory.CreateSpaceVertical(Content, 10);

        CreatePurchasedProductsSection(elementFactory);

        CreateFooter(elementFactory);
    }

    private void CreateTopSectionUI(IUIElementFactory elementFactory)
    {
        VisualElement topContainer = elementFactory.CreateContainer(Content, ContainerStyles.Horizontal);

        elementFactory.CreateLabel(topContainer, "Wizard Demo", LabelStyles.WindowTitle);
    }

    private void CreateFooter(IUIElementFactory elementFactory)
    {
        VisualElement bottomContainer = elementFactory.CreateContainer(Footer, ContainerStyles.Horizontal);

        Button closeButton = elementFactory.CreateButton(bottomContainer, "Close", ButtonStyles.Secondary);
        closeButton.clicked += () => Close();
    }

    private void CreatePurchasedProductsSection(IUIElementFactory elementFactory)
    {
        VisualElement productsContainer = elementFactory.CreateContainer(Content, ContainerStyles.Horizontal);
        productsContainer.style.height = 500f;

        VisualElement leftContainer = elementFactory.CreateContainer(productsContainer, ContainerStyles.PaddingRight);
        elementFactory.CreateLabel(leftContainer, "Purchased Products", LabelStyles.Label);

        VisualElement rightContainer = elementFactory.CreateContainer(productsContainer, ContainerStyles.PaddingLeft);
        elementFactory.CreateLabel(rightContainer, "Files and Images", LabelStyles.Label);

        string[] productsTableLabels = new string[] { "Product Name", "Product GUID"};
        int[] availableFilesTableWidths = new int[] { 300, 0 };

        m_ProductsTable = elementFactory.CreateTable(
            leftContainer,
            productsTableLabels,
            availableFilesTableWidths,
            selectability: IUITable.Selectability.SingleLines);

        string[] filesTableLabels = new string[] { "Original File Name", "File Type", "File GUID" };
        int[] filesTableWidths = new int[] { 300, 100, 200 };

        m_FilesTable = elementFactory.CreateTable(
            rightContainer,
            filesTableLabels,
            filesTableWidths,
            selectability: IUITable.Selectability.None);

        GetProducts();
    }

    private void GetProducts()
    {
        XR4EDPurchasedItemsProcess getProductsProcess = new XR4EDPurchasedItemsProcess("Demo Wizard - Get Products Process");
        getProductsProcess.onFinished += (status) =>
        {
            if (status == Process.ProcessStatus.Succeeded)
            {
                foreach (XR4EDPurchasedItemsProcess.OrderItem product in getProductsProcess.OrderItems)
                    AddProduct(product);
            }
            else
            {
                ReferenceProvider.PopupSystem.ShowErrorPopup("Failed to access products.");
            }
        };
        getProductsProcess.Start();
    }

    private void AddProduct(XR4EDPurchasedItemsProcess.OrderItem product)
    {
        m_ProductsTable.Add(new List<string> { product.name, product.productGuid }, product);

        m_ProductsTable.onSelectionStatusChanged -= ProductTableLineClicked;
        m_ProductsTable.onSelectionStatusChanged += ProductTableLineClicked;
    }

    private void ProductTableLineClicked(VisualElement line, IUITableEntry.SelectedStates status)
    {
        if (line == null)
            return;

        if (status == IUITableEntry.SelectedStates.Selected)
        {
            XR4EDPurchasedItemsProcess.OrderItem[] orderItems = m_ProductsTable.GetAllSelectedDataAs<XR4EDPurchasedItemsProcess.OrderItem>();

            if( orderItems != null && orderItems.Length == 1)
                UpdateFilesTable(orderItems[0]);
            else
            {
                ReferenceProvider.PopupSystem.ShowErrorPopup("Failed to display product files.");
            }
        }
    }

    private void UpdateFilesTable(XR4EDPurchasedItemsProcess.OrderItem product)
    {
        m_FilesTable.Clear();

        if (product.files != null)
        {
            foreach (XR4EDPurchasedItemsProcess.XR4ED_File file in product.files)
            {
                m_FilesTable.Add(new List<string> { file.originalFilename, file.fileType.ToString(), file.guid });
            }
        }

        if (product.images != null)
        {
            foreach (XR4EDPurchasedItemsProcess.XR4ED_File file in product.images)
            {
                m_FilesTable.Add(new List<string> { file.originalFilename, file.fileType.ToString(), file.guid });
            }
        }
    }
}
