import React, { useEffect, useState } from 'react'
import MultiLevelDropdown from '../../../../ui/inputs/MultiLevelDropDown'
import { AddIcon } from '../../../../icons/ExportCommonIcons'
import axios from 'axios'

type Props = {}

const PieChartInput = (props: Props) => {
    const [dropDowndata, setDropDownData] = useState({})
    const [selections, setSelections] = useState<Record<string, {name: string, fields: string}>>({})

    useEffect(() => {
        const fetchZoneData = async () => {
            try {
                const response = await axios.get('http://192.168.0.192:5010/getinput');
                if (response.status === 200) {
                    console.log('dropdown data:', response.data);
                    setDropDownData(response.data)
                } else {
                    console.log('Unexpected response:', response);
                }
            } catch (error) {
                console.error('There was an error!', error);
            }
        };
        fetchZoneData();
    }, []);

    useEffect(() => {console.log(selections);
    },[selections])

    const handleSelect = (inputKey: string, selectedData: {name: string, fields: string} | null) => {
        setSelections(prev => {
            if (selectedData === null) {
                const newSelections = {...prev};
                delete newSelections[inputKey];
                return newSelections;
            } else {
                return {
                    ...prev,
                    [inputKey]: selectedData
                };
            }
        });
    };

    return (
        <>
        <div className="inputs-wrapper">
            {[...Array(3)].map((_, index) => {
                const inputKey = `input${index+1}`;
                return (
                    <div key={index} className="datas">
                        <div className="datas__label">Input {index+1}</div>
                        <div className="datas__class">
                            <MultiLevelDropdown 
                                data={dropDowndata} 
                                onSelect={(selectedData) => handleSelect(inputKey, selectedData)}
                                onUnselect={() => handleSelect(inputKey, null)}
                                selectedValue={selections[inputKey]}
                            />
                            <div className="icon">
                                <AddIcon />
                            </div>
                        </div>
                    </div>
                );
            })}
        </div>
        <div>
            
        </div>
        </>
    )
}

export default PieChartInput