<script lang="ts">
    import { page } from '$app/stores'
    import dayjs from 'dayjs'
    import advancedFormat from 'dayjs/plugin/advancedFormat.js'
    import { getAssetUrlKey } from '$utils/helpers'
    // Components
    import Metas from '$components/Metas.svelte'
    import Image from '$components/atoms/Image.svelte'
    import IconArrow from '$components/atoms/IconArrow.svelte'
    import ButtonCircle from '$components/atoms/ButtonCircle.svelte'

    export let photos: any[]
    export let location: any
    export let currentIndex: number
    export let totalPhotos: number

    dayjs.extend(advancedFormat)

    // Define reactive last and first photos
    $: isLast = currentIndex === totalPhotos - 1
    $: isFirst = currentIndex === 0
    // Define current photo
    // $: currentPhoto = photos.find((photo: any) => photo.slug === $page.params.photo)
    $: currentPhoto = photos[photos.findIndex((photo: any) => photo.slug === $page.params.photo)]
    // Reactive photos showns
    $: shownPhotos = [
        ...photos.filter((photo: any, index: number) => {
            // Grab the 4 prev and next photos depending the index
            console.log(index)
            // console.log(index >= currentIndex - 4 && index < currentIndex + 4)
        })
    ]


    /**
     * Photo navigation
     */
    // Go to next photo
    const goToNext = () => {
        if (!isLast) {
            currentIndex++
        }

        // TODO: Fetch new photos
    }

    // Fo to previous photo
    const goToPrevious = () => {
        if (!isFirst) {
            currentIndex--
        }

        // TODO: Fetch new photos
    }

    // Manage navigation with keyboard
    const handleKeydown = ({ key, defaultPrevented }: KeyboardEvent) => {
        if (defaultPrevented) return
        switch (key) {
            case 'ArrowLeft': goToNext(); break;
            case 'ArrowRight': goToPrevious(); break;
            default: return;
        }
    }


    /**
     * Load photos
     */
    const loadPhotos = (index: number) => {

    }
</script>

<svelte:window on:keydown={handleKeydown} />

{#if currentPhoto}
<Metas
    title="{currentPhoto.title} - Houses Of {location.name}"
    description=""
    image={getAssetUrlKey(currentPhoto.image.id, 'share')}
/>
{/if}


<main class="viewer-photo">
    <div class="container grid">
        <div class="viewer-photo__carousel">
            <div class="viewer-photo__images">
                {#each photos as photo}
                    <Image
                        class="photo {photo.id === currentPhoto.id ? 'is-active' : ''}"
                        id={photo.image.id}
                        alt={photo.title}
                        sizeKey="photo-list"
                        sizes={{
                            small: { width: 500 },
                            medium: { width: 850 },
                            large: { width: 1280 },
                        }}
                        ratio={1.5}
                    />
                {/each}

                <div class="viewer-photo__controls">
                    <ButtonCircle on:click={goToNext} disabled={isLast}>
                        <IconArrow color="pink" flip={true} />
                    </ButtonCircle>
                    <ButtonCircle on:click={goToPrevious} disabled={isFirst}>
                        <IconArrow color="pink" />
                    </ButtonCircle>
                </div>

                <span class="viewer-photo__index title-index">
                    {currentIndex + 1}
                </span>
            </div>

            <div class="viewer-photo__info">
                <h1 class="title-medium">{currentPhoto.title}</h1>

                <div class="detail text-date">
                    <img src="/images/icons/map-pin.svg" width={16} height={18} alt="Map icon"><span>{location.name}, {location.country.name}</span> <span class="sep">&middot;</span> <time datetime={dayjs(currentPhoto.date_taken).format('YYYY-MM-DD')}>{dayjs(currentPhoto.date_taken).format('MMMM, Do YYYY')}</time>
                </div>
            </div>
        </div>
    </div>
</main>


<script context="module" lang="ts">
    import { fetchAPI } from '$utils/api'

    export async function load ({ page, fetch, session, stuff }) {
        const res = await fetchAPI(`
            query {
                photos: photo (
                    filter: { location: { slug: { _eq: "${page.params.location}" }}},
                    sort: "-date_created",
                    limit: 5,
                ) {
                    id
                    title
                    slug
                    date_taken
                    image {
                        id
                        title
                    }
                }

                location (filter: { slug: { _eq: "${page.params.location}" }}) {
                    name
                    slug
                    country { name }
                }
            }
        `)

        const { data } = res
        const location = stuff.locations.find((location: any) => location.slug === page.params.location)
        const totalPhotos = stuff.countTotalPhotosByLocation.find((total: any) => total.group.location === Number(location.id)).count.id

        // Find photo's index
        const currentPhotoIndex = data.photos.findIndex((photo: any) => photo.slug === page.params.photo)
        const currentIndex = (totalPhotos - 1) - currentPhotoIndex

        return {
            props: {
                photos: data.photos,
                location: data.location[0],
                currentIndex,
                totalPhotos,
            }
        }
    }
</script>