<script lang="ts">
    import {
        anilistModal,
        simklWatchList,
        aniListLoggedIn,
        simklLoggedIn,
        malLoggedIn,
        malAnime
    } from "./GlobalVariablesAndHelperFunctions.svelte";
    import {aniListAnime} from "./GlobalVariablesAndHelperFunctions.svelte";
    import {Button} from "flowbite-svelte";
    // @ts-ignore
    import StarRatting from "@ernane/svelte-star-rating"
    import moment from 'moment'
    import { Table, TableBody, TableBodyCell, TableBodyRow, TableHead, TableHeadCell } from 'flowbite-svelte';
    import { writable } from 'svelte/store';
    import type {SimklAnime} from "./simkl/types/simklTypes";
    import { get } from 'svelte/store';
    import {
        AniListUpdateEntry, MyAnimeListUpdate,
        SimklSyncEpisodes,
        SimklSyncRating,
        SimklSyncStatus
    } from "../wailsjs/go/main/App";
    import type {MALAnime, MALUploadStatus, MyListStatus} from "./mal/types/MALTypes";
    import type {AniListUpdateVariables} from "./anilist/types/AniListTypes";

    const simklWatch = get(simklWatchList);
    let isAniListLoggedIn: boolean
    let isMalLoggedIn: boolean
    let isSimklLoggedIn: boolean
    let simklAnimeIndex: number
    let currentMalAnime: MALAnime
    let simklAnime: SimklAnime | undefined = undefined
    let submitting = writable(false)
    let isSubmitting: boolean

    aniListLoggedIn.subscribe((value) => isAniListLoggedIn = value)
    malLoggedIn.subscribe((value) => isMalLoggedIn = value)
    simklLoggedIn.subscribe((value) => isSimklLoggedIn = value)
    malAnime.subscribe((value) => currentMalAnime = value)
    submitting.subscribe((value) => isSubmitting = value)

    for (let i = 0; i < simklWatch.anime.length; i++) {
        if (Number(simklWatch.anime[i].show.ids.mal) === aniListAnime.data.MediaList.media.idMal) {
            simklAnimeIndex = i
            simklAnime = simklWatch.anime[i]
        }
    }

    type statusOption = {
        id: number,
        aniList: string,
        mal: string,
        simkl: string,
    }

    const statusOptions: statusOption[] = [
        { id: 0, aniList: "CURRENT", mal: "watching", simkl: "watching"},
        { id: 1, aniList: "PLANNING", mal: "plan_to_watch", simkl: "plantowatch"},
        { id: 2, aniList: "COMPLETED", mal: "completed", simkl: "completed"},
        { id: 3, aniList: "DROPPED", mal: "dropped", simkl: "dropped"},
        { id: 4, aniList: "PAUSED", mal: "on_hold", simkl: "hold"},
        { id: 5, aniList: "REPEATING", mal: "rewatching", simkl: "watching"}
    ]

    let startingAnilistStatusOption: statusOption

    startingAnilistStatusOption = statusOptions.filter(option => aniListAnime.data.MediaList.status === option.aniList)[0]

    let items = [] as {
        id: number
        service: string
        progress: number
        status: string
        startedAt: string
        completedAt: string
        score: number
        repeat: number
        notes: string
    }[];

    if(isAniListLoggedIn) {
        items.push({
            id: aniListAnime.data.MediaList.id,
            service: "AniList",
            progress: aniListAnime.data.MediaList.progress,
            status: aniListAnime.data.MediaList.status,
            startedAt: `${aniListAnime.data.MediaList.startedAt.month}-${aniListAnime.data.MediaList.startedAt.day}-${aniListAnime.data.MediaList.startedAt.year}`,
            completedAt: `${aniListAnime.data.MediaList.completedAt.month}-${aniListAnime.data.MediaList.completedAt.day}-${aniListAnime.data.MediaList.completedAt.year}`,
            score: aniListAnime.data.MediaList.score,
            repeat: aniListAnime.data.MediaList.repeat,
            notes: aniListAnime.data.MediaList.notes
        })
    }

    if(isMalLoggedIn) {
        items.push({
            id: currentMalAnime.id,
            service: "MyAnimeList",
            progress: currentMalAnime.my_list_status.num_episodes_watched,
            status: currentMalAnime.my_list_status.status,
            startedAt: currentMalAnime.my_list_status.start_date,
            completedAt: currentMalAnime.my_list_status.finish_date,
            score: currentMalAnime.my_list_status.score,
            repeat: currentMalAnime.my_list_status.num_times_rewatched,
            notes: currentMalAnime.my_list_status.comments
        })
    }

    if(isSimklLoggedIn && simklAnime !== undefined) {
        items.push({
            id: simklAnime.show.ids.simkl,
            service: "Simkl",
            progress: simklAnime.watched_episodes_count,
            status: simklAnime.status,
            startedAt: "",
            completedAt: "",
            score: simklAnime.user_rating,
            repeat: 0,
            notes: ""
        })
    }

    const sortKey = writable('service'); // default sort key
    const sortDirection = writable(1); // default sort direction (ascending)
    const sortItems = writable(items.slice()); // make a copy of the items array

    // Define a function to sort the items
    const sortTable = (key: any) => {
        // If the same key is clicked, reverse the sort direction
        if ($sortKey === key) {
            sortDirection.update((val) => -val);
        } else {
            sortKey.set(key);
            sortDirection.set(1);
        }
    };

    $: {
        const key = $sortKey;
        const direction = $sortDirection;
        const sorted = [...$sortItems].sort((a, b) => {
            const aVal = a[key];
            const bVal = b[key];
            if (aVal < bVal) {
                return -direction;
            } else if (aVal > bVal) {
                return direction;
            }
            return 0;
        });
        sortItems.set(sorted);
    }

    const ratingInWords = {
        0: "Not Reviewed",
        1: "Appalling",
        2: "Horrible",
        3: "Very Bad",
        4: "Bad",
        5: "Average",
        6: "Fine",
        7: "Good",
        8: "Very Good",
        9: "Great",
        10: "Masterpiece",
    }

    const hide = (e) => {
        e.preventDefault();
        anilistModal.set(false)
    };

    const title = aniListAnime.data.MediaList.media.title.english !== "" ?
        aniListAnime.data.MediaList.media.title.english :
        aniListAnime.data.MediaList.media.title.romaji

    let config = {
        readOnly: false,
        countStars: 5,
        range: {
            min: 0,
            max: 5,
            step: 0.5
        },
        score: aniListAnime.data.MediaList.score / 2,
        showScore: false,
        scoreFormat: function () {
            return `(${this.score.toFixed(1)}/${this.countStars})`
        },
        name: "",
        starConfig: {
            size: 32,
            fillColor: '#F9ED4F',
            strokeColor: "#e2c714",
            unfilledColor: '#FFF',
            strokeUnfilledColor: '#000'
        }
    }

    let values = {
        progress: aniListAnime.data.MediaList.progress,
        status: startingAnilistStatusOption,
        startedAt: {
            year: aniListAnime.data.MediaList.startedAt.year,
            month: aniListAnime.data.MediaList.startedAt.month,
            day: aniListAnime.data.MediaList.startedAt.day
        },
        completedAt: {
            year: aniListAnime.data.MediaList.completedAt.year,
            month: aniListAnime.data.MediaList.completedAt.month,
            day: aniListAnime.data.MediaList.completedAt.day
        },
        repeat: aniListAnime.data.MediaList.repeat,
        score: aniListAnime.data.MediaList.score,
        notes: aniListAnime.data.MediaList.notes
    }
    let startedAtDate: string
    let completedAtDate: string

    const changeRating = (e) => {
        config.score = e.target.valueAsNumber
        values.score = e.target.valueAsNumber * 2
    }


    if (values.startedAt.year > 0) {
        let startedAtISODate = new Date(values.startedAt.year, values.startedAt.month - 1, values.startedAt.day)
        let startedAtMoment = moment(startedAtISODate)
        startedAtDate = startedAtMoment.format('YYYY-MM-DD')
    }

    const transformStartedAtDate = (e) => {
        const re = /^([0-9]{4})-([0-9]{2})-([0-9]{2})/
        const date = re.exec(e.target.value)
        values.startedAt.year = Number(date[1])
        values.startedAt.month = Number(date[2])
        values.startedAt.day = Number(date[3])
    }

    if (values.completedAt.year > 0) {
        let completedAtISODate = new Date(values.completedAt.year, values.completedAt.month - 1, values.completedAt.day)
        let completedAtMoment = moment(completedAtISODate)
        completedAtDate = completedAtMoment.format('YYYY-MM-DD')
    }

    const transformCompletedAtDate = (e) => {
        const re = /^([0-9]{4})-([0-9]{2})-([0-9]{2})/
        const date = re.exec(e.target.value)
        values.completedAt.year = Number(date[1])
        values.completedAt.month = Number(date[2])
        values.completedAt.day = Number(date[3])
    }

    const submitData = async () => {
        submitting.set(true)
        let body: AniListUpdateVariables = {
            mediaId: aniListAnime.data.MediaList.mediaId,
            progress: values.progress,
            status: values.status.aniList,
            score: values.score,
            repeat: values.repeat,
            notes: values.notes,
            startedAt: {
                year: values.startedAt.year,
                month: values.startedAt.month,
                day: values.startedAt.day
            },
            completedAt: {
                year: values.completedAt.year,
                month: values.completedAt.month,
                day: values.completedAt.day
            }
        }
       await AniListUpdateEntry(body).then((value) => {
           console.log(value)
       })

        if(malLoggedIn) {
            let body: MALUploadStatus = {
                status: values.status.mal,
                is_rewatching: false,
                score: values.score,
                num_watched_episodes: values.progress,
                num_times_rewatched: values.repeat,
                comments: values.notes
            }

            await MyAnimeListUpdate(currentMalAnime, body).then((value: MyListStatus) => {
                currentMalAnime.my_list_status.status = value.status
                currentMalAnime.my_list_status.is_rewatching = value.is_rewatching
                currentMalAnime.my_list_status.score = value.score
                currentMalAnime.my_list_status.num_episodes_watched = value.num_episodes_watched
                currentMalAnime.my_list_status.num_times_rewatched = value.num_times_rewatched
                currentMalAnime.my_list_status.comments = value.comments

            })
        }

        if (simklLoggedIn) {
            if (simklAnime.watched_episodes_count !== values.progress) {
                await SimklSyncEpisodes(simklAnime, values.progress).then(() => {
                    simklAnime.watched_episodes_count = values.progress
                    simklWatch.anime[simklAnimeIndex].watched_episodes_count = values.progress
                })
            }

            if (simklAnime.user_rating !== values.score) {
                await SimklSyncRating(simklAnime, values.score).then(() => {
                    simklAnime.user_rating = values.score
                    simklWatch.anime[simklAnimeIndex].user_rating = values.score
                })
            }

            if (simklAnime.status !== values.status.simkl) {
                await SimklSyncStatus(simklAnime, values.status.simkl).then(() => {
                    simklAnime.status = values.status.simkl
                    simklWatch.anime[simklAnimeIndex].status = values.status.simkl
                })
            }
        }
        submitting.set(false)
    }
</script>

<div id="inapp-data">
    <div class="grid grid-cols-1 md:grid-cols-10 grid-flow-col gap-4">
        <div class="md:col-span-2 space-y-3">
            <img class="rounded-lg" src={aniListAnime.data.MediaList.media.coverImage.large} alt="{title} Cover Image">
            <StarRatting bind:config on:change={changeRating}/>
            <p>Rating:  {config.score * 2}</p>
            <p>{ratingInWords[config.score * 2]}</p>
        </div>

        <div class="md:col-span-8 ">
            <div class="flex flex-col md:flex-row md:pl-10 md:pr-10 pt-5 pb-5 justify-center md:gap-x-24 lg:gap-x-56">
                <div>
                    <label for="episodes" class="text-left block mb-2 text-sm font-medium text-gray-900 dark:text-white">Episode
                        Progress</label>
                    <input
                            type="number"
                            name="episodes"
                            min="0"
                            id="episodes"
                            class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600
                            focus:border-primary-600 block w-24 p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400
                            dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500"
                            bind:value={values.progress}
                            required>
                </div>


                <div>
                    <label for="status"
                           class="text-left block mb-2 text-sm font-medium text-gray-900 dark:text-white">Status</label>
                    <select id="status"
                            class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500
                            focus:border-blue-500 block p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400
                            dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
                            bind:value={values.status}
                    >
                        {#each statusOptions as option}
                            <option value={option}>{option.aniList}</option>
                        {/each}
                    </select>
                </div>
            </div>
            <div class="flex flex-col md:flex-row md:pl-10 md:pr-10 pt-5 pb-5 justify-center md:gap-x-16 lg:gap-x-36">

                <div>

                    <label for="startedAt" class="text-left block mb-2 text-sm font-medium text-gray-900 dark:text-white">Date
                        Started</label>
                    <div class="relative max-w-sm">
                        <div class="absolute inset-y-0 start-0 flex items-center ps-3.5 pointer-events-none">
                            <svg class="w-4 h-4 text-gray-500 dark:text-gray-400" aria-hidden="true"
                                 xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 20 20">
                                <path d="M20 4a2 2 0 0 0-2-2h-2V1a1 1 0 0 0-2 0v1h-3V1a1 1 0 0 0-2 0v1H6V1a1 1 0 0 0-2 0v1H2a2 2 0 0 0-2 2v2h20V4ZM0 18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8H0v10Zm5-8h10a1 1 0 0 1 0 2H5a1 1 0 0 1 0-2Z"/>
                            </svg>
                        </div>
                        <input
                                id="startedAt"
                                type="date"
                                name="startedAt"
                                class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500
                            focus:border-blue-500 block w-full ps-10 p-2.5 dark:bg-gray-700 dark:border-gray-600
                            dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
                                value={startedAtDate}
                                placeholder="Date Started"
                                on:change={transformStartedAtDate}
                        >
                    </div>
                </div>
                <div>

                    <label for="completedAt" class="text-left block mb-2 text-sm font-medium text-gray-900 dark:text-white">Date
                        Completed</label>
                    <div class="relative max-w-sm">
                        <div class="absolute inset-y-0 start-0 flex items-center ps-3.5 pointer-events-none">
                            <svg class="w-4 h-4 text-gray-500 dark:text-gray-400" aria-hidden="true"
                                 xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 20 20">
                                <path d="M20 4a2 2 0 0 0-2-2h-2V1a1 1 0 0 0-2 0v1h-3V1a1 1 0 0 0-2 0v1H6V1a1 1 0 0 0-2 0v1H2a2 2 0 0 0-2 2v2h20V4ZM0 18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8H0v10Zm5-8h10a1 1 0 0 1 0 2H5a1 1 0 0 1 0-2Z"/>
                            </svg>
                        </div>
                        <input
                                id="completedAt"
                                type="date"
                                name="completedAt"
                                class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500
                            focus:border-blue-500 block w-full ps-10 p-2.5 dark:bg-gray-700 dark:border-gray-600
                            dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
                                value={completedAtDate}
                                placeholder="Date Completed"
                                on:change={transformCompletedAtDate}
                        >
                    </div>
                </div>
                <div>
                    <label for="repeat"
                           class="text-left block mb-2 text-sm font-medium text-gray-900 dark:text-white">Rewatched</label>
                    <input
                            type="number"
                            name="repeat"
                            min="0"
                            id="repeat"
                            class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600
                            focus:border-primary-600 block w-24 p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400
                            dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500"
                            bind:value={values.repeat}
                            required>
                </div>
            </div>
            <div class="flex flex-col md:flex-row md:pl-10 md:pr-10 pt-5 pb-5 justify-center">
                <div class="w-full">
                    <label for="notes" class="text-left block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your
                        notes</label>
                    <textarea id="notes" rows="3"
                              class="block p-2.5 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
                              placeholder="Write your thoughts here..."
                              bind:value={values.notes}></textarea>
                </div>
            </div>
        </div>
    </div>
    <div id="external-data">
        <div id="anilist-data" class="flex flex-col md:flex-row md:pl-10 md:pr-10 pt-5 pb-5 justify-center md:gap-x-16 lg:gap-x-36 group">
            <h2 class="text-left mb-1 text-base font-semibold text-gray-900 dark:text-white">AniList</h2>
        </div>
    </div>

    <Table hoverable={true}>
        <TableHead>
            <TableHeadCell class="cursor-pointer" on:click={() => sortTable('id')}>ID</TableHeadCell>
            <TableHeadCell class="cursor-pointer" on:click={() => sortTable('service')}>Service</TableHeadCell>
            <TableHeadCell class="cursor-pointer" on:click={() => sortTable('progress')}>Episode Progress</TableHeadCell>
            <TableHeadCell class="cursor-pointer" on:click={() => sortTable('status')}>Status</TableHeadCell>
            <TableHeadCell class="cursor-pointer" on:click={() => sortTable('startedAt')}>Date Started</TableHeadCell>
            <TableHeadCell class="cursor-pointer" on:click={() => sortTable('completedAt')}>Date Completed</TableHeadCell>
            <TableHeadCell class="cursor-pointer" on:click={() => sortTable('score')}>Rating</TableHeadCell>
            <TableHeadCell class="cursor-pointer" on:click={() => sortTable('repeat')}>Rewatches</TableHeadCell>
            <TableHeadCell>Notes</TableHeadCell>
        </TableHead>
        <TableBody tableBodyClass="divide-y">
            {#each $sortItems as item}
                <TableBodyRow>
                    <TableBodyCell class="overflow-x-auto">{item.id}</TableBodyCell>
                    <TableBodyCell class="overflow-x-auto">{item.service}</TableBodyCell>
                    <TableBodyCell class="overflow-x-auto">{item.progress}</TableBodyCell>
                    <TableBodyCell class="overflow-x-auto">{item.status}</TableBodyCell>
                    <TableBodyCell class="overflow-x-auto">{item.startedAt}</TableBodyCell>
                    <TableBodyCell class="overflow-x-auto">{item.completedAt}</TableBodyCell>
                    <TableBodyCell class="overflow-x-auto">{item.score}</TableBodyCell>
                    <TableBodyCell class="overflow-x-auto">{item.repeat}</TableBodyCell>
                    <TableBodyCell class="overflow-x-auto">{item.notes}</TableBodyCell>
                </TableBodyRow>
            {/each}
        </TableBody>
    </Table>


    <div class="bg-white rounded-lg shadow max-w-4-4 dark:bg-gray-800">
        <div class="w-full mx-auto max-w-screen-xl p-4 md:flex md:items-center md:justify-end">
            <Button disabled={isSubmitting}
                    id="sync-button"
                    class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium
                    rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none
                    dark:focus:ring-blue-800"
                    on:click={async () => {
                        let submitLoader = document.querySelector("#submit-loader")
                        let syncButton = document.querySelector("#sync-button")
                        submitLoader.classList.replace("hidden", "inline")
                        await submitData()
                        submitLoader.classList.replace("inline", "hidden")
                        syncButton.classList.replace("bg-blue-700", "bg-green-700")
                        syncButton.classList.replace("dark:bg-blue-600", "dark:bg-green-600")
                        syncButton.classList.replace("hover:bg-blue-600", "hover:bg-green-600")
                        syncButton.classList.replace("hover:dark:bg-blue-700", "hover:dark:bg-green-700")
                        syncButton.classList.replace("focus:ring-blue-300", "focus:ring-green-300")
                        syncButton.classList.replace("dark:focus:ring-blue-800", "dark:focus:ring-green-800")
                        syncButton.innerHTML = "Sync Successful"
                        setTimeout(function(){
                            syncButton.classList.replace("bg-green-700", "bg-blue-700")
                            syncButton.classList.replace("dark:bg-green-600", "dark:bg-blue-600")
                            syncButton.classList.replace("hover:bg-green-600", "hover:bg-blue-600")
                            syncButton.classList.replace("hover:dark:bg-green-700", "hover:dark:bg-blue-700")
                            syncButton.classList.replace("focus:ring-green-300", "focus:ring-blue-300")
                            syncButton.classList.replace("dark:focus:ring-green-800", "dark:focus:ring-blue-800")
                            syncButton.innerHTML = "Sync Changes"
                        }, 2000)
                    }}>
                <svg id="submit-loader" aria-hidden="true" role="status" class="hidden w-4 h-4 me-3 text-white animate-spin" viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z" fill="#E5E7EB"/>
                    <path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z" fill="currentColor"/>
                </svg>
                Sync Changes
            </Button>
            <Button
                    class="text-gray-900 bg-white border border-gray-300 focus:outline-none hover:bg-gray-100 focus:ring-4
                    focus:ring-gray-100 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-gray-800 dark:text-white
                    dark:border-gray-600 dark:hover:bg-gray-700 dark:hover:border-gray-600 dark:focus:ring-gray-700"
                    on:click={hide}>
                Cancel
            </Button>
        </div>
    </div>

    <div>
        <h3 class="text-2xl">
            Summary
        </h3>
        <p>{@html aniListAnime.data.MediaList.media.description}</p>
    </div>
</div>