import { FC, useEffect, useState } from 'react'
import { Star1 } from 'iconsax-react'
import { useMoveToFavorite, useUnFavoriteMessage } from '../hooks/useEmailData';

const Favorite: FC<{ flagged: boolean, id: string, mailbox: string }> = ({ flagged, id, mailbox }) => {

    const [isFavorite, setIsFavorite] = useState<boolean>(flagged)
    const { mutate: moveToFavorite } = useMoveToFavorite()
    const { mutate: unFavoriteMessage } = useUnFavoriteMessage()

    const handleFavoriteClick = (e: React.MouseEvent) => {
        e.preventDefault()
        e.stopPropagation()

        if (isFavorite) {
            unFavoriteMessage({ messageId: id || '', mailbox: mailbox || '' })
        } else {
            moveToFavorite({ messageId: id || '', mailbox: mailbox || '' })
        }
        setIsFavorite(!isFavorite)
    }

    useEffect(() => {
        setIsFavorite(flagged)
    }, [flagged])

    return (
        <div onClick={handleFavoriteClick}>
            <Star1
                variant={isFavorite ? 'Bold' : 'Outline'}
                size={19}
                color={isFavorite ? '#FFC107' : '#8C90A3'}
                className='cursor-pointer select-none'
            />
        </div>
    )
};

export default Favorite;