import { Card, useMutation, useStorage } from '@/app/liveblocks.config';
import { shallow } from '@liveblocks/client';
import { ReactSortable } from 'react-sortablejs';
import NewCardForm from './forms/NewCardForm';
import { FormEvent, useState } from 'react';
import { BsThreeDots } from "react-icons/bs";
import {default as ColumnCard} from './Card';


type ColumnProps = {
    id: string;
    name: string;
}


const Column = ({id, name}: ColumnProps) => {
    const columnCards = useStorage<Card[]>(root => {
        return root.cards.filter(card => card.columnId === id).map(c => ({...c})).sort((a, b) => a.index - b.index);
    }, shallow)

    const updateCard = useMutation(({storage}, index, updateData) => {
        const card = storage.get('cards').get(index);
        if(card){
            for(let key in updateData){
                card?.set(key as keyof Card, updateData[key]);
            }
        }
    }, []);

    const setTasksOrderForColumn = useMutation(({storage}, sortedCards: Card[], newColumnId) => {
        const idsOfSortedCards = sortedCards.map(c => c.id.toString());
        const allCards: Card[] = [...storage.get('cards').map(c => c.toObject())]
        idsOfSortedCards.forEach((sortedCardId, colIndex) => {
            const cardStorageIndex = allCards.findIndex(c => c.id.toString() === sortedCardId);
            updateCard(cardStorageIndex, {
                columnId: newColumnId,
                index: colIndex,
            })
        })

    }, []);
    
    const updateColumn = useMutation(({storage}, id, newName) => {
        const columns = storage.get('columns');
        columns.find(c => c.toObject().id === id)?.set('name', newName)
    }, []);

    const deleteColumn = useMutation(({storage}, id) => {
        const columns = storage.get('columns');
        const columnIndex = columns.findIndex(c => c.toObject().id === id);
        columns.delete(columnIndex); 
    }, [])

    const [renameColumn, setRenameColumn] = useState(false);
    function handleRenameColumn(ev: FormEvent){
        ev.preventDefault();
        const input = (ev.target as HTMLFormElement).querySelector('input')
        if(input){
            const newColumnName = input.value;
            updateColumn(id, newColumnName)
            setRenameColumn(false);
        }
    }



  return (
    <div className=' w-50 shadow-md rounded-md p-2 bg-gray-100'>
        {!renameColumn && (
            <div className='flex justify-between'>
                <h3>{name}</h3>
                <button onClick={() => setRenameColumn(true)}><BsThreeDots className='text-[#164863]'/></button>
            </div>
        )}
        {renameColumn && (
            <div className='mb-8'>
                Edit name:
                <form onSubmit={handleRenameColumn} className='mb-2'>
                    <input type="text" defaultValue={name} className='border p-2 w-full'/>
                    <button type="submit" className='w-full mt-2'>Save</button>
                </form>
                <button onClick={() => deleteColumn(id)} className='w-full p-2 bg-[tomato] text-white rounded-md font-semibold text-sm'> Delete column</button>
                <button onClick={() => setRenameColumn(false)} className='w-full mt-4 text-xs uppercase font-bold text-gray-500 tracking-wider'>Cancel</button>
            </div>
            
        )}
        
        {!renameColumn && columnCards && (
            <>
            <ReactSortable list={columnCards} setList={items => setTasksOrderForColumn(items, id)} group="cards" ghostClass='opacity-40' className='min-h-12'>
                {columnCards.map(card => (
                    <ColumnCard key={card.id} id={card.id} name={card.name} />
                ))}
            </ReactSortable>  
           </> 
        )}
        {!renameColumn && (
            <NewCardForm columnId={id}/>
        )}
        
    </div>

  )
}

export default Column