<template>
    <div class="space-y-4">
        <form @submit.prevent="() => search()">
            <div class="flex rounded-xl overflow-hidden shadow-md">
                <input type="text" v-model="searchValue" :placeholder="exampleTitles[Math.floor(exampleTitles.length*Math.random())]"
                    class="w-full outline-none p-2 bg-white border border-gray-100 text-gray-800 placeholder-gray-400 disabled:cursor-not-allowed disabled:opacity-50 disabled:bg-gray-50 disabled:border-gray-400">
                <button class="py-3 px-6 bg-indigo-500 text-white" type="submit">Search</button>
            </div>
        </form>
        <div v-if="$route.query['query']" class="text-center">{{ movies.length }} result{{ movies.length != 1 ? 's' : ""}} found</div>
        <movie-list :movies="movies" @onClickMovie="displayMovie"/>
    </div>
    <router-view @onClose="onModalClosed"></router-view>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { IApiMovie, IApiPaginatedResponse } from "@common/api_schema";
import { authFetchApi } from "../routes";
import MovieList from "../components/MovieList.vue";

export default defineComponent({
    components: {
        MovieList
    },
    data() {
        return {
            exampleTitles: ["John Wick", "The Incredibles 2", "Stand by Me", "Shawshank Redemption", "The Dark Knight", "Pulp Fiction", "Forrest Gump"],
            isSubmitting: false,
            movies: <IApiMovie[]>[],
            searchValue: <string>this.$route.query["query"] || "",
            page: -1,
            totalPages: 0,
            totalResults: 0
        }
    },
    methods: {
        displayMovie(movie: IApiMovie) {
            this.$router.push({
                name  : "Lookup",
                params: { tmdbId: movie.tmdbId },
                query : this.$route.query
            });
        },
        onModalClosed() {
            this.$router.push({ name: "Search", query: this.$route.query });
        },
        async search(pushRoute: boolean = true) {
            if (this.isSubmitting || this.searchValue.trim().length == 0) {
                return;
            }
            if (document.activeElement && (<any>document.activeElement).blur) {
                (<any>document.activeElement).blur();
            }
            if (pushRoute) {
                this.$router.push({ name: "Search", query: { query: this.searchValue } });
            }
            this.isSubmitting = true;
            try {
                let response = await authFetchApi<IApiPaginatedResponse<IApiMovie>>(`/api/movie/search?query=${encodeURI(this.searchValue)}`);
                this.movies = response.data.results;
                this.page = response.data.page;
                this.totalPages = response.data.totalPages;
                this.totalResults = response.data.totalResults;
                console.log("Got results", this.totalResults);
            } catch(e) {
                console.log("Error fetching movies:", e);
            }
            this.isSubmitting = false;
        }
    },
    mounted() {
        this.search(false);
    },
});
</script>

<style scoped>

.overlay {
    position: relative;
}

.overlay::before {
    content: "";
    position: absolute;
    left: 0; top: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    filter: grayscale(100%);
    z-index: 0;
}

.overlay > * {
    z-index: 1;
}

.active .body {
    display: block !important;
}
</style>
