import React, { useEffect, useState } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
import { useCookies } from 'react-cookie'

import Button from '~components/Button'
import HeaderMenu from '~components/HeaderMenu'

import './index.css'

interface Props {
    navigate: (pathname: string) => void
}

const Header = (props: Props) => {
    const [username, setUsername] = useState(undefined)
    const [cookies, setCookie, removeCookie] = useCookies(['user'])

    let history = useHistory()
    let location = useLocation()
    
    const route = (pathname: string) => props.navigate(pathname)

    useEffect(() => {
        if (cookies.user) {
            setUsername(cookies.user.username)
            console.log(`Logged in as user "${cookies.user.username}"`)
        }
    }, [])

    function copyToClipboard() {
        const el = document.createElement('input')
        el.value = window.location.href
        el.id = 'url-input'
        document.body.appendChild(el)

        el.select()
        document.execCommand('copy')
        el.remove()
    }

    function newParty() {
        props.navigate('/')
    }

    function logout() {
        removeCookie('user')
        window.history.replaceState(null, `Grid Tool`, `/`)
        history.go(0)
    }
        
    return (
        <nav className="Header">
            <div className="left">
                <div className="dropdown">
                    <Button type="menu">Menu</Button>
                    <HeaderMenu username={username} logout={logout} />
                </div>
            </div>
            <div className="push" />
            <div className="right">
                { (location.pathname !== '/') ?
                    <Button type="link" click={copyToClipboard}>Copy link</Button> : ''
                }
                <Button type="new" click={newParty}>New</Button>
            </div>
        </nav>
    )
}

export default Header