<script setup lang="ts">
import { Ref, computed, onMounted, ref } from 'vue';
import Button from 'primevue/button';
import Dialog from 'primevue/dialog';
import InputIcon from 'primevue/inputicon';
import InputText from 'primevue/inputtext';
import Tab from 'primevue/tab';
import TabList from 'primevue/tablist';
import TabPanel from 'primevue/tabpanel';
import TabPanels from 'primevue/tabpanels';
import Tabs from 'primevue/tabs';
import { listen } from '@tauri-apps/api/event';
import ModList from './ModList.vue';
import ModStore from './ModStore.vue';
import OptionList from './OptionList.vue';
import ProfileList from './ProfileList.vue';
import StartButton from './StartButton.vue';
import { invoke } from '../invoke';
import {
    useClientStore,
    useGeneralStore,
    usePkgStore,
    usePrfStore,
} from '../stores';
import { Dirs } from '../types';

const pkg = usePkgStore();
const prf = usePrfStore();
const general = useGeneralStore();
const client = useClientStore();

pkg.setupListeners();

const currentTab: Ref<string | number> = ref(3);
const pkgSearchTerm = ref('');

const isProfileDisabled = computed(() => prf.current === null);

onMounted(async () => {
    invoke('list_directories').then((d) => {
        general.dirs = d as Dirs;
        client.load();
    });

    const fetch_promise = pkg.fetch(true);

    await Promise.all([prf.reloadList(), prf.reload()]);

    if (prf.current !== null) {
        currentTab.value = 0;
        await pkg.reloadAll();
    }

    fetch_promise.then(async () => {
        await invoke('install_package', {
            key: 'segatools-mu3hook',
            force: false,
        });
        await invoke('install_package', {
            key: 'segatools-chusanhook',
            force: false,
        });
    });
});

const errorVisible = ref(false);
const errorMessage = ref('No error');
const errorHeader = ref('No header');

listen<{ message: string; header: string }>('invoke-error', (event) => {
    errorVisible.value = true;
    errorMessage.value = event.payload.message;
    errorHeader.value = event.payload.header;
});
</script>

<template>
    <main
        :class="
            client.scaleFactor === 's'
                ? 'main-scale-s'
                : client.scaleFactor === 'm'
                  ? 'main-scale-m'
                  : client.scaleFactor === 'l'
                    ? 'main-scale-l'
                    : 'main-scale-xl'
        "
    >
        <Dialog
            modal
            :visible="errorVisible"
            :closable="false /*this shit doesn't work */"
            :header="errorHeader"
            :style="{ width: '50vw' }"
        >
            <div class="flex flex-col gap-4">
                {{ errorMessage }}
                <Button
                    class="m-auto"
                    label="A sad state of affairs"
                    @click="errorVisible = false"
                />
            </div>
        </Dialog>

        <Tabs
            lazy
            :value="currentTab"
            v-on:update:value="
                (value) => {
                    currentTab = value;
                }
            "
            class="h-screen"
        >
            <div class="fixed w-full flex z-100">
                <TabList class="grow" :show-navigators="false">
                    <Tab :value="3"
                        ><div class="pi pi-users" v-tooltip="'Profiles'"></div
                    ></Tab>
                    <Tab :disabled="isProfileDisabled" :value="0"
                        ><div
                            class="pi pi-box"
                            v-tooltip="'Installed packages'"
                        ></div
                    ></Tab>
                    <Tab v-if="prf.current?.meta.game === 'chunithm'" :value="4"
                        ><div class="pi pi-ticket" v-tooltip="'Patches'"></div
                    ></Tab>
                    <Tab
                        v-if="pkg.networkStatus === 'online'"
                        :disabled="isProfileDisabled"
                        :value="1"
                        ><div
                            class="pi pi-download"
                            v-tooltip="'Package store'"
                        ></div
                    ></Tab>
                    <Tab :disabled="isProfileDisabled" :value="2"
                        ><div class="pi pi-cog" v-tooltip="'Settings'"></div
                    ></Tab>

                    <div class="grow"></div>

                    <div class="flex gap-4">
                        <div class="flex" v-if="currentTab !== 3">
                            <InputIcon class="self-center mr-2">
                                <i class="pi pi-search" />
                            </InputIcon>
                            <InputText
                                v-if="currentTab === 2"
                                style="min-width: 0; width: 25dvw"
                                class="self-center"
                                size="small"
                                placeholder="Search"
                                v-model="general.cfgSearchTerm"
                            />
                            <InputText
                                v-else
                                style="min-width: 0; width: 25dvw"
                                class="self-center"
                                size="small"
                                placeholder="Search"
                                v-model="pkgSearchTerm"
                            />
                        </div>
                        <Button
                            v-if="pkg.networkStatus === 'connecting'"
                            class="shrink self-center"
                            icon="pi pi-sync pi-spin"
                            size="small"
                            :disabled="true"
                        />
                        <Button
                            v-if="
                                pkg.networkStatus === 'offline' &&
                                !client.offlineMode
                            "
                            class="shrink self-center"
                            icon="pi pi-sync"
                            size="small"
                            @click="pkg.fetch(false)"
                        />
                        <Button
                            v-if="
                                pkg.networkStatus === 'online' &&
                                pkg.hasAvailableUpdates
                            "
                            icon="pi pi-download"
                            label="UPDATE ALL"
                            size="small"
                            class="mr-4 m-2.5"
                            @click="pkg.updateAll()"
                        ></Button>
                    </div>
                    <div class="grow"></div>
                    <StartButton />
                </TabList>
            </div>
            <TabPanels class="w-full grow mt-[3rem]">
                <TabPanel :value="0">
                    <ModList :search="pkgSearchTerm" />
                </TabPanel>
                <TabPanel :value="1">
                    <ModStore :search="pkgSearchTerm" />
                </TabPanel>
                <TabPanel :value="2">
                    <OptionList />
                </TabPanel>
                <TabPanel :value="3">
                    <ProfileList />
                    <br /><br /><br />
                    <footer>
                        <Button
                            icon="pi pi-discord"
                            as="a"
                            target="_blank"
                            href="https://discord.gg/jxvzHjjEmc"
                        />
                    </footer>
                </TabPanel>
                <TabPanel :value="4">
                    CHUNITHM patches are not implemented yet.<br />Use
                    <a
                        href="https://patcher.two-torial.xyz/"
                        target="_blank"
                        style="text-decoration: underline"
                        >patcher.two-torial.xyz</a
                    >
                </TabPanel>
            </TabPanels>
            <div v-if="currentTab === 5 || currentTab === 3">
                <img
                    v-if="prf.current?.meta.game === 'ongeki'"
                    src="/sticker-ongeki.svg"
                    class="fixed bottom-0 right-0 z-999"
                />
                <img
                    v-else-if="prf.current?.meta.game === 'chunithm'"
                    src="/sticker-chunithm.svg"
                    class="fixed bottom-0 right-0 z-999"
                />
            </div>
        </Tabs>
    </main>
</template>

<style lang="css">
@import 'tailwindcss';
@import 'primeicons/primeicons.css';

.p-tablist-tab-list {
    height: 3rem;
}

html,
body {
    margin: 0;
    padding: 0;
}

.main-scale-s {
    zoom: 1;
}

.main-scale-m {
    zoom: 1.25;
}

.main-scale-l {
    zoom: 1.4;
}

.main-scale-xl {
    zoom: 1.7;
}

.p-tablist {
    background-color: #ffffff !important;
    border-bottom: white 10px !important;
}

.p-tab {
    border-bottom: none !important;
}
.p-tablist-active-bar {
    display: none !important;
}
</style>
