import React, { useCallback, useEffect, useState } from 'react'
import Head from 'next/head'
import { useCookies } from 'react-cookie'
import { useRouter } from 'next/router'
import { useTranslation } from 'next-i18next'

import { serverSideTranslations } from 'next-i18next/serverSideTranslations'

import api from '~utils/api'

import GridRep from '~components/GridRep'
import GridRepCollection from '~components/GridRepCollection'
import FilterBar from '~components/FilterBar'

const ProfileRoute: React.FC = () => {
    const router = useRouter()
    const { username } = router.query

    const { t } = useTranslation('common')
    const [cookies] = useCookies(['account'])

    const [found, setFound] = useState(false)
    const [loading, setLoading] = useState(true)
    const [scrolled, setScrolled] = useState(false)

    const [parties, setParties] = useState<Party[]>([])
    const [user, setUser] = useState<User>({
        id: '',
        username: '',
        granblueId: 0,
        picture: {
            picture: '',
            element: ''
        },
        private: false
    })

    // Filter states
    const [element, setElement] = useState<number | null>(null)
    const [raidId, setRaidId] = useState<string | null>(null)
    const [recencyInSeconds, setRecencyInSeconds] = useState<number | null>(null)

    useEffect(() => {
        window.addEventListener("scroll", handleScroll)
        return () => window.removeEventListener("scroll", handleScroll);
    }, [])

    const handleError = useCallback((error: any) => {
        if (error.response != null) {
            console.error(error)
        } else {
            console.error("There was an error.")
        }
    }, [])

    const fetchProfile = useCallback(() => {
        const filters = {
            params: {
                element: element,
                raid: raidId,
                recency: recencyInSeconds
            }
        }

        const headers = (cookies.account) ? {
            headers: {
                'Authorization': `Bearer ${cookies.account.access_token}`
            }
        } : {}

        const params = {...filters, ...headers}

        setLoading(true)

        if (username)
            api.endpoints.users.getOne({ id: username as string, params: params })
                .then(response => {
                    setUser({
                        id: response.data.user.id,
                        username: response.data.user.username,
                        granblueId: response.data.user.granblue_id,
                        picture: response.data.user.picture,
                        private: response.data.user.private
                    })

                    const parties: Party[] = response.data.user.parties
                    setParties(parties.sort((a, b) => (a.created_at > b.created_at) ? -1 : 1))
                })
                .then(() => {
                    setFound(true)
                    setLoading(false)
                })
                .catch(error => handleError(error))
    }, [username, element, raidId, recencyInSeconds, cookies.account, handleError])

    useEffect(() => {
        fetchProfile()            
    }, [fetchProfile])

    function receiveFilters(element?: number, raid?: string, recency?: number) {
        if (element != null && element >= 0)
            setElement(element)
        else
            setElement(null)

        if (raid && raid != '0')
            setRaidId(raid)
        else
            setRaidId(null)

        if (recency && recency > 0)
            setRecencyInSeconds(recency)
        else
            setRecencyInSeconds(null)
    }

    function handleScroll() {
        if (window.pageYOffset > 90)
            setScrolled(true)
        else
            setScrolled(false)
    }

    function goTo(shortcode: string) {
        router.push(`/p/${shortcode}`)
    }

    return (
        <div id="Profile">
            <Head>
                <title>@{user.username}&apos;s Teams</title>

                <meta property="og:title" content={`@${user.username}\'s Teams`} />
                <meta property="og:description" content={`Browse @${user.username}\'s Teams and filter raid, element or recency`} />
                <meta property="og:url" content={`https://app.granblue.team/${user.username}`} />
                <meta property="og:type" content="website" />

                <meta name="twitter:card" content="summary_large_image" />
                <meta property="twitter:domain" content="app.granblue.team" />
                <meta name="twitter:title" content={`@${user.username}\'s Teams`} />
                <meta name="twitter:description" content={`Browse @${user.username}\''s Teams and filter raid, element or recency`} />
            </Head>
            <FilterBar onFilter={receiveFilters} scrolled={scrolled}>
                <div className="UserInfo">
                    <img 
                        alt={user.picture.picture}
                        className={`profile ${user.picture.element}`}
                        srcSet={`/profile/${user.picture.picture}.png,
                                 /profile/${user.picture.picture}@2x.png 2x`}
                        src={`/profile/${user.picture.picture}.png`} 
                    />
                    <h1>{user.username}</h1>
                </div>
            </FilterBar>

            <section>
                <GridRepCollection loading={loading}>
                    {
                        parties.map((party, i) => {
                            return <GridRep 
                                id={party.id}
                                shortcode={party.shortcode} 
                                name={party.name}
                                createdAt={new Date(party.created_at)}
                                raid={party.raid}
                                grid={party.weapons}
                                favorited={party.favorited}
                                key={`party-${i}`}
                                onClick={goTo}
                            />
                        })
                    }
                </GridRepCollection>
                { (parties.length == 0) ?
                    <div id="NotFound">
                        <h2>{ (loading) ? t('teams.loading') : t('teams.not_found') }</h2>
                    </div> 
                : '' }
            </section>
        </div>
    )
}

export async function getStaticPaths() {
    return {
        paths: [
            // Object variant:
            { params: { username: 'string' } },
        ],
        fallback: true,
    }
}

export async function getStaticProps({ locale }: { locale: string }) {
    return {
        props: {
            ...(await serverSideTranslations(locale, ['common'])),
            // Will be passed to the page component as props
        },
    }
}

export default ProfileRoute
