import React, {useState} from "react";
import OrgPanel from "./OrgPanel";
import {useAuth} from "react-oidc-context";
import type {OrgObject} from "./hooks/OrgContext.ts";
import type { JSX } from "react/jsx-runtime";
import CreateOrg from "./CreateOrg.tsx";
import {useRefreshContext} from "./hooks/RefreshContext.ts";

const Organisations: React.FC = () => {
    const auth = useAuth();
    const [orgData, setCurrentOrgData] = useState<OrgObject[]>();
    const { refreshKey } = useRefreshContext();
    React.useEffect(() => {
        const fetchOrgData = async () => {
            console.log("Fetching org data");
            if (!auth.user) return
            try {
                const requestOptions = {
                    method: 'GET',
                    headers: {
                        Authorization: `Bearer ${auth.user.access_token}`,
                        'Content-Type': 'application/json'
                    }
                }
                const response = await fetch("/api/v1/user/self/orgs", requestOptions);
                const orgsObject = await response.json();
                setCurrentOrgData(orgsObject['organisations'])

            } catch (e) {
                    console.error(e);
                }
        }
        fetchOrgData()
            .catch(console.error);
    }, [auth.user, refreshKey]);

    console.log(orgData);

    let panels: JSX.Element[] = [];
    if (orgData) {
        panels = orgData.map(org => <OrgPanel {...org} key={org.organisation_id} />);
    }
    return(<>
        <h1>Your organisations</h1>
        {panels}
        <h1>Add a new organisation</h1>
        <CreateOrg></CreateOrg>
    </>);
}

export default Organisations;