"use client";

import axios from "axios";
import * as React from 'react';
import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { ConnectionElement, ConnectionAdderElement } from "@/components/elements/connection";
import { ConnectionDefaultElement } from "@/components/elements/connection-default";

const ConnectionsPage = () => {
    const { data: session, status } = useSession();
    const [loading, setLoading] = useState<boolean>(true)
    const [connections, setConnections] = useState<{ name: string, clientId: string, token: string, type: string, scope: string, expiresAt: Date }[]>([])

    useEffect(() => {
        if (status != "authenticated")
            return

        const fetchData = async () => {
            setLoading(true)
            const response = await axios.get("/api/connection")
            const data = response.data
            setConnections(data.data)
        }

        fetchData().catch(console.error).finally(() => setLoading(false))
    }, [session])

    const OnConnectionDelete = async (name: string) => {
        setConnections(connections.filter(c => c.name != name))
    }

    const OnDefaultConnectionUpdate = async (name: string) => {
        if (!connections.some(c => c.name == name))
            return

        axios.put('/api/connection/default', { name: name })
            .then(d => {
                setConnections([...connections])
            })
    }

    return (
        <div>
            <div className="text-2xl text-center pt-[50px]">Connections</div>
            <div className="grid grid-cols-[1fr] xl:grid-cols-[1fr_1fr]">
                {connections.map((connection) =>
                    <ConnectionElement
                        key={connection.name}
                        name={connection.name}
                        type={connection.type}
                        clientId={connection.clientId}
                        expiresAt={connection.expiresAt}
                        scope={connection.scope}
                        remover={OnConnectionDelete}
                    />
                )}

                {!loading &&
                    <ConnectionAdderElement />
                }
            </div>
            {connections.length > 0 &&
                <div>
                    <p className="text-2xl text-center pt-[50px]">Default Connections</p>
                    <ConnectionDefaultElement
                        type={"nightbot"}
                        connections={connections} />
                    <ConnectionDefaultElement
                        type={"twitch"}
                        connections={connections} />
                </div>
            }
        </div>
    );
}

export default ConnectionsPage;