'use client'

import React, { useState, useEffect, Suspense } from 'react';
import { Tree } from 'primereact/tree';
import { PrimeIcons } from 'primereact/api';
import { debug } from 'console';

export default function AffinityGroupsTree() {
    const [nodes, setNodes] = useState([]);
    const parseNode = (record: any, included: any[]) => {
        if (!record.attributes) {
            record = included.find((a) => a.id === record.id);
        }
        
        const children = (record?.relationships?.children?.data || []).map((child: any) => {
            return (parseNode(child, included));
        });

        return ({
            key: record.id,
            label: record.attributes.name,
            icon: record.attributes.icon,
            children: children,
            className: "px-4",
        })
    }


    useEffect(() => {
        if (nodes.length > 0) {
            return;
        }
        fetch("http://localhost:3001/groups.json")
            .then((response) => response.json())
            .then((data) => {
                setNodes(data.data.map((record: any) => {
                    return (parseNode(record, data.included));
                }))
            });
    });

    return (
        <div className="card flex justify-content-center">
            <Suspense>
                <Tree value={nodes} dragdropScope="affinity-groups" onDragDrop={(e) => setNodes(e.value)} className="w-full md:w-30rem" />
            </Suspense>
        </div>
    )
}