import { useState, useEffect } from '@wordpress/element';
import {Icon, chevronDownSmall} from '@wordpress/icons';

import { Button, Modal } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import LCPDataGrid from './LCPDataGrid';

const LCPDatasetBuilder = ({ attributes, setAttributes }) => {
    const [isOpen, setIsOpen] = useState(false);
    const [activeTab, setActiveTab] = useState(0); // Track the active tab
    const [datasets, setDatasets] = useState(attributes.datasets); // Use useState for datasets

    // Sync state with attributes if they change outside the component
    useEffect(() => {
        setDatasets(attributes.datasets);
    }, [attributes.datasets]);

    const handleUpdateDataset = (index, newData) => {
       // console.log("newData (formatted for copy-pasting):", JSON.stringify(newData, null, 2));

        // Check if newData.data is an array
        if (Array.isArray(newData.data)) {
            // Create a new reference for the datasets array
            const updatedDatasets = datasets.map((dataset, i) => {
                if (i === index) {
                    // If this is the dataset we're updating, replace it with a new object
                    return {
                        ...dataset,  // Copy the existing dataset
                        data: [...newData.data],  // Deep copy the data array
                    };
                }
                return dataset; // Leave other datasets unchanged
            });

         //   console.log("Updated Datasets:", JSON.stringify(updatedDatasets, null, 2));

            // Call setAttributes with the updated datasets
            setAttributes({
                ...attributes,  // Ensure we're not overriding other attributes accidentally
                datasets: updatedDatasets, // Set the new datasets array
            });

         //   console.log("Attributes after setAttributes:", JSON.stringify({ ...attributes, datasets: updatedDatasets }, null, 2));
        } else {
          //  console.error("Invalid data format in newData:", newData);
        }
    };

    return (
        <>
            <Button
                variant="secondary"
                onClick={() => setIsOpen(true)}
                style={{ marginBottom: '10px', width: '100%',  }}
            >
                {__('Edit Dataset', 'lcp-visualize')}
            </Button>

            {isOpen && (
                <Modal
                    onRequestClose={() => setIsOpen(false)}
                    title={__('Dataset Builder', 'lcp-visualize')}
                    style={{ width: '90vw', height: '90vh',
                        background:'#efefef',
                        padding:'0px',
                     }}
                >
                    <div style={{ height: 'calc(90vh - 40px)', padding: '0px' }}>
                        {/* Tabs */}
                        <div style={{ display: 'flex' }}>
                            {datasets.map((dataset, index) => (
                                <button
                                    key={index}

                                    onClick={() => setActiveTab(index)} // Set the active tab
                                    style={{
                                        display: 'flex',
                                        alignItems:'center',
                                        justifyContent:'center',
                                        position: 'relative',
                                        minWidth: '100px',
                                        height: '35px',
                                        lineHeight: '35px',
                                        padding: '0 10px',
                                        margin: '0 3px',
                                        backgroundColor: '#fff',
                                        border: '1px solid #ccc',
                                        borderBottomColor: activeTab === index ? '#fff' : '#ccc',
                                        borderRadius: '3px',
                                        color: activeTab === index ? 'white' : 'black',
                                        border: '1px solid #ccc',
                                        borderRadius: '5px',
                                        cursor: 'pointer',
                                        transition: 'background-color 0.3s ease',
                                    }}
                                >   <span style={{
                                    display: 'inline-block', 
                                    marginRight: '5px',
                                    color: activeTab === index ? '#333' : '#aaa',
                                    fontWeight: 'bold'
                                    }}>
                                        {dataset.name}
                                    </span>
                                    <Icon icon={ chevronDownSmall } style={{position:'relative',top:'0px'}} />
                                    
                                </button>
                            ))}
                        </div>

                        {/* Render all the LCPDataGrid components */}
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                            {datasets.map((dataset, index) => (
                                <div
                                    key={index}
                                    style={{
                                        display: activeTab === index ? 'block' : 'none', // Show only the active tab
                                        transition: 'display 0.3s ease',
                                    }}
                                >
                                    <LCPDataGrid
                                        dataset={dataset.data}  // Pass the specific dataset data (only the data, not the entire dataset)
                                        index={index}
                                        updateDataset={handleUpdateDataset} // Function defined outside of class context
                                    />
                                </div>
                            ))}
                        </div>
                    </div>
                </Modal>
            )}
        </>
    );
};

export default LCPDatasetBuilder;
