import { Collapse, Spin } from "antd";

import { ListTcfNetworkItem } from "./networkItem.js";
import { useListTcfVendor } from "../../../contexts/listTcfVendor.js";

import type { ComponentProps, FC } from "react";

const { Panel } = Collapse;

const ListTcfNetworkSelector: FC<{ onCreate: ComponentProps<typeof ListTcfNetworkItem>["onCreate"] }> = ({
    onCreate,
}) => {
    const contextValue = useListTcfVendor();
    const { adNetworks, view } = contextValue;
    const defaultActiveKeyAdNetwork =
        (view === "vendors" ? contextValue.defaultCreateAdNetworkIdentifier : undefined) || adNetworks[0].identifier;

    if (contextValue.rows.length === 0) {
        return <Spin spinning />;
    }

    return (
        <Collapse accordion defaultActiveKey={defaultActiveKeyAdNetwork}>
            {adNetworks.map((adNetwork) => {
                const { name, identifier, logo } = adNetwork;

                return (
                    <Panel key={identifier} header={name} extra={<img src={logo} style={{ height: "1em" }} />}>
                        <ListTcfNetworkItem {...adNetwork} onCreate={onCreate} />
                    </Panel>
                );
            })}
        </Collapse>
    );
};

export { ListTcfNetworkSelector };
