"use client"
import { useParams, useRouter } from "next/navigation"
import { FormEvent, useContext, useEffect, useState } from "react";
import { BoardContext, BoardContextProps } from "../BoardContext";
import { Card, useMutation, useStorage, useThreads } from "@/app/liveblocks.config";
import { shallow } from "@liveblocks/client";
import { BsThreeDots } from "react-icons/bs";
import DeleteConfirmation from "../DeleteConfirmation";
import { IoDocumentTextOutline } from "react-icons/io5";
import { FaRegCommentDots } from "react-icons/fa6";
import CardDesc from "../CardDesc";
import { Composer, Thread } from "@liveblocks/react-comments";
import "@liveblocks/react-comments/styles.css";




const CardModal = () => {
    const router = useRouter();
    const params = useParams();
    const {threads} = useThreads({
        query:{
            metadata:{
                cardId:params.cardId?.toString(),
            }
        }
    });
        
    const {setOpenCard} = useContext<BoardContextProps>(BoardContext);
    const [editCard, setEditCard] = useState(false);

    const card = useStorage(root => {
       return root.cards.find(c => c.id === params.cardId) 
    }, shallow)

    useEffect(() => {
        if(params.cardId && setOpenCard){
            setOpenCard(params.cardId.toString());
        }
    }, [params])

    function handleBackdrop(){
            router.back();
    }

    const updateCard = useMutation(({storage}, cardId, updateData) => {
        const cards = storage.get('cards').map(c => c.toObject());
        const index = cards.findIndex(c => c.id === cardId);
        const card = storage.get('cards').get(index);
        for (let updateKey in updateData){
            card?.set(updateKey as keyof Card, updateData[updateKey]);
        }
    }, [])

    const deleteCard = useMutation(({storage}, id) => {
        const cards = storage.get('cards');
        const cardIndex = cards.findIndex(c => c.toObject().id === id);
        cards.delete(cardIndex); 
    }, [])

    function handleCardNamechange(ev: FormEvent){
        ev.preventDefault();
        const input = (ev.target as HTMLFormElement).querySelector('input');
        if(input){
            const newName = input.value;
            updateCard(params.cardId, {name: newName});
            setEditCard(false)
        }
    }

    function handleDelete(){
        deleteCard(params.cardId)
        if(setOpenCard){
            setOpenCard(null)
        }
        router.back();
    }


  return (
    <div onClick={handleBackdrop} className='fixed inset-0 bg-black/80'>
        <div onClick={ev => ev.stopPropagation()} className='bg-white p-4 mt-8 max-w-sm mx-auto overflow-scroll' style={{maxHeight:"calc(100vh - 2rem)"}}>
            {!editCard && (
                <div className="flex justify-between">
                    <p className="mb-6 uppercase text-sm font-semibold">{card?.name}</p>
                    <button onClick={() => setEditCard(true)} className="text-gray-500"><BsThreeDots/></button>
                </div>
            )}
            {editCard && (
                <div>
                    <form onSubmit={handleCardNamechange} className="flex flex-col">
                        <input type="text" defaultValue={card?.name} className="mb-4 border p-2 rounded-md"/>
                        <button type="submit" className="uppercase w-full flex text-center justify-center itemc">save</button>
                    </form>
                    <div>
                        <DeleteConfirmation onDelete={() => handleDelete()}/>
                    </div>
                </div>
            )}
            {!editCard && (
                <div>
                    <h3 className="flex items-center"><IoDocumentTextOutline/> Description</h3>
                    <CardDesc/>
                    <h3 className="flex items-center mt-4"><FaRegCommentDots/> Comments</h3>
                    <div className="mt-4">
                        {threads && threads.map(thread => (
                            <div key={thread.id}>
                                <Thread thread={thread} id={thread.id}/>
                            </div>
                        ))}
                        {threads?.length === 0 && (
                            <div>
                                <Composer metadata={{cardId:params.cardId.toString()}}/>
                            </div>
                        )}
                    </div>
                    
                </div>
            )}
        </div>
    </div>
  )
}

export default CardModal