"use client"
import { RoomProvider } from '@/app/liveblocks.config';
import { LiveList } from '@liveblocks/client';
import { ClientSideSuspense } from '@liveblocks/react';
import Columns from './Columns';
import Link from 'next/link';
import { IoMdSettings } from "react-icons/io";
import { FormEvent, useState } from 'react';
import { updateBoard } from '@/app/actions/boardActions';
import { useRouter } from 'next/navigation';
import { BoardContextProvider } from './BoardContext';


const Board = ({id, name}: {id:string, name:string}) => {
    const [renameBoard, setRenameBoard] = useState(false);
    const router = useRouter();

    async function handleRenameSubmit(ev:FormEvent){
        ev.preventDefault();
        const input = (ev.target as HTMLFormElement).querySelector('input');
        if(input){
            const newBoardName = input?.value;
            await updateBoard(id, {metadata: {boardName: newBoardName}});
            input.value = '';
            setRenameBoard(false);
            router.refresh();
        }
        
    }



  return (
    <BoardContextProvider>
        <RoomProvider id={id} initialPresence={{}} initialStorage={
            {
                columns: new LiveList(),
                cards: new LiveList(),
            }}>
            <ClientSideSuspense fallback={(<div>Loading...</div>)}>{() => (
                <>
                    <div className='flex justify-between gap-2 items-center mb-4'>
                        <div>
                            {!renameBoard && (
                                <h1 onClick={() => setRenameBoard(true)} className='text-2xl'>Board: {name}</h1>
                            )}
                            {renameBoard && (
                                <form onSubmit={handleRenameSubmit}>
                                    <input type="text" defaultValue={name} className='border p-2'/>
                                </form>
                            )}
                        </div>
                        <Link href={`/boards/${id}/settings`} className='flex items-center gap-1 bg-[#427D9D] p-2 rounded-full'>
                            <IoMdSettings className='text-white text-[18px]'/>
                        </Link>
                    </div>
                    <Columns/>
                </>
                )}
            </ClientSideSuspense>  
        </RoomProvider>
    </BoardContextProvider>
  )
}

export default Board