import React, { useState } from 'react';
import { Button } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import Papa from 'papaparse';

const LCPDataUploader = ({ onJsonDataUpdate }) => {
    const [error, setError] = useState(null);
    const [csvFile, setCsvFile] = useState(null);

    const handleFileUpload = (event) => {
        const file = event.target.files[0];
        if (!file) return;

        setCsvFile(file);

        // Clear any previous errors
        setError(null);

        // Log the file info for debugging
        console.log('Selected file:', file);

        // Parse the CSV using PapaParse
        Papa.parse(file, {
            complete: (result) => {
                console.log('CSV parsing result:', result); // Log the result object
                try {
                    const jsonData = convertCsvToJson(result.data);
                    console.log('Converted JSON:', jsonData); // Log the converted JSON data
                    onJsonDataUpdate(jsonData); // Pass the parsed JSON data to the parent component
                } catch (parseError) {
                    console.error('Error during CSV conversion:', parseError);
                    setError('Error during CSV conversion');
                }
            },
            error: (error) => {
                console.error('Error parsing CSV:', error);
                setError('Error parsing CSV file');
            },
        });
    };

    // Helper function to convert CSV rows into JSON format
    const convertCsvToJson = (csvData) => {
        console.log('Converting CSV to JSON. Raw CSV data:', csvData);

        // Get the headers from the first row of the CSV data
        const headers = csvData[0];

        // Define a new array to hold the processed JSON
        const jsonData = [];

        // Process the rows (skip the first row as it contains headers)
        csvData.slice(1).forEach((row, index) => {
            const obj = {};

            // Map each column in the row to an object key based on the headers
            headers.forEach((header, headerIndex) => {
                obj[header] = row[headerIndex] || ''; // Set the value, default to an empty string if not available
            });

            // Add a unique ID to each row (optional, just to ensure uniqueness)
            obj.ID = `lcpDatapoint-${index}`;

            console.log('Processed row:', obj); // Log each row's conversion
            jsonData.push(obj);
        });

        console.log('Final JSON Data:', jsonData);
        return jsonData;
    };

    return (
        <div>
            <Button isPrimary onClick={() => document.getElementById('csv-upload-input').click()}>
                {__('Upload CSV', 'lcp')}
            </Button>

            <input
                type="file"
                id="csv-upload-input"
                style={{ display: 'none' }}
                accept=".csv"
                onChange={handleFileUpload}
            />

            {error && <p style={{ color: 'red' }}>{error}</p>}
            {csvFile && <p>{__('File selected: ', 'lcp')}{csvFile.name}</p>}
        </div>
    );
};

export default LCPDataUploader;
