import React, { useState } from 'react';
import { Data } from "../../models/game";
import { ContextMenu } from 'chakra-ui-contextmenu';
import { MenuItem, MenuList } from '@chakra-ui/menu';
import GameThumbnail from "./GameThumbnail";
import { Box, MenuGroup, useDisclosure } from "@chakra-ui/react";
import GameThumbnailSlide from "./GameThumbnailSlide";
import { playStatusValues } from "../../componentUtils/SelectValues";
import agent from "../../api/agent";
import { Link } from "react-router-dom";

interface Props {
    game: Data
}

const GameThumbnailContextMenu = ({ game }: Props) => {
    const { isOpen, onToggle } = useDisclosure()
    const [playState, setPlayState] = useState(game.accessedBy[0].playStatus)
    const gameLink = game.steamId.length > 1 ? game.steamId : game._id

    const rightClick = async (label: string, playStatus: string) => {
        try {
            setPlayState(playStatus)
            await agent.Games.playStatus(game._id, {
                accessedBy: [{
                    playStatus
                }]
            })
        } catch (err) {
            console.error(`${label}: ${err}`)
        }
    }

    let mql = window.matchMedia('(max-width: 768px)');

    return (
        <ContextMenu<HTMLDivElement> key={game._id} renderMenu={() => (
            <MenuList>
                <MenuItem><Link to={`/games/${gameLink}`} target="_blank" rel="noopener noreferrer">Open in New Tab</Link></MenuItem>
                <MenuGroup title={'Change PlayStatus'}>
                    {playStatusValues.map(value => <MenuItem
                        onClick={() => rightClick(value.label, value.value)}
                    >{value.label}</MenuItem>)}
                </MenuGroup>
            </MenuList>
        )}>
            {ref => <>
                <Box
                    ref={ref}
                    border={'1px'}
                    borderColor={'gray.500'}
                    maxW={'sm'}
                    rounded={'md'}
                    transitionProperty={'box-shadow transform'}
                    transitionDuration={'1'}
                    transitionTimingFunction={'ease-in-out'}
                    _hover={{ boxShadow: '2xl', transform: 'translateY(-3px)' }}
                >
                    <GameThumbnail onToggle={onToggle} game={game} playState={playState} />
                </Box>
                {(!mql.matches) && <GameThumbnailSlide isOpen={isOpen} game={game} />}
            </>
            }
        </ContextMenu>
    );
};

export default GameThumbnailContextMenu;
