'use client'

import React, { useEffect, useState } from 'react';
import { EditRoomForm } from './EditRoomForm';
import debounce from 'lodash/debounce';
import { createRoom } from '../../../actions/rooms';
import { Loader } from '../../view/Loader';
import { useRouter } from '../../../i18n/routing';
import { RoomsType } from '../../../types/rooms';


export const CreateRoom = ({ locale, jwt }: { locale: string, jwt: string }) => {
    const [roomId, setRoomId] = useState<number>();
    const [loading, setLoading] = useState<boolean>(false);
    const router = useRouter();

    const getRoom = debounce(() => {
        createRoom(locale, jwt)
            .then((data) => {
                setRoomId(data);
            })
            .finally(() => {
                setLoading(false);
            })
    }, 500);

    useEffect(() => {
        setLoading(true);
        getRoom();
    }, []);

    return (
        <Loader isLoading={loading}>
            {roomId && (
                <EditRoomForm
                    roomId={roomId}
                    locale={locale}
                    jwt={jwt}
                    mode="create"
                    afterSubmit={() => router.push(`/account/rooms/${RoomsType.UPCOMING}`)}
                />
            )}
        </Loader>
    )
};
