<template>
    <MkStickyContainer>
        <template #header>
            <MkPageHeader
                v-model:tab="tab"
                :actions="headerActions"
                :tabs="headerTabs"
                :display-back-button="true"
            />
        </template>
        <div>
            <transition name="fade" mode="out-in">
                <div v-if="user">
                    <XHome
                        v-if="tab === 'home'"
                        :user="user"
                        @refresh="fetchUser()"
                    />
                    <XReactions v-else-if="tab === 'reactions'" :user="user" />
                    <XClips v-else-if="tab === 'clips'" :user="user" />
                </div>
                <MkError v-else-if="error" @retry="fetchUser()" />
                <MkLoading v-else />
            </transition>
        </div>
    </MkStickyContainer>
</template>

<script lang="ts" setup>
import { host as localHost } from "@/config";
import { computed, defineAsyncComponent, watch, ref } from "vue";
import * as os from "@/os";
import { useRouter } from "@/router";
import { definePageMetadata } from "@/scripts/page-metadata";
import { i18n } from "@/i18n";
import { $i } from "@/account";
import { endpoints, MagApiError, packed } from "magnetar-common";
import * as Acct from "calckey-js/built/acct";

const XHome = defineAsyncComponent(() => import("./home.vue"));
const XReactions = defineAsyncComponent(() => import("./reactions.vue"));
const XClips = defineAsyncComponent(() => import("./clips.vue"));

const props = withDefaults(
    defineProps<{
        acct: string;
        page?: string;
    }>(),
    {
        page: "home",
    },
);

const router = useRouter();

let tab = ref(props.page);
let user = ref<null | packed.PackUserSelfMaybeAll>(null);
let error = ref<any>(null);

function fetchUser(refetch: boolean = true, clear: boolean = true): void {
    if (!props.acct) return;

    if (clear) user.value = null;

    os.magApi(
        endpoints.GetUserByAcct,
        { relation: true, detail: true, pins: true, profile: true },
        { user_acct: props.acct },
    )
        .then((u) => {
            user.value = u;

            const dayMs = 86400 * 1000;
            if (
                (!user.value.last_fetched_at ||
                    new Date().getTime() -
                        new Date(user.value.last_fetched_at).getTime() >
                        dayMs) &&
                user.value.host !== null &&
                user.value.host !== localHost &&
                refetch
            ) {
                os.api("users/show", Acct.parse(props.acct))
                    .then(() => {
                        fetchUser(false, false);
                    })
                    .catch((e) => {
                        error.value = e;
                    });
            }
        })
        .catch((err) => {
            const magError = err as MagApiError;
            if (!refetch || magError.status !== 404) {
                error.value = magError;
                return;
            }

            os.api("users/show", Acct.parse(props.acct))
                .then(() => {
                    fetchUser(false);
                })
                .catch((e) => {
                    error.value = e;
                });
        });
}

watch(
    () => props.acct,
    () => fetchUser(),
    {
        immediate: true,
    },
);

const headerActions = computed(() => []);

const headerTabs = computed(() =>
    user.value
        ? [
              {
                  key: "home",
                  title: i18n.ts.overview,
                  icon: "ph-user ph-bold ph-lg",
              },
              ...(($i && $i.id === user.value.id) ||
              user.value.has_public_reactions
                  ? [
                        {
                            key: "reactions",
                            title: i18n.ts.reaction,
                            icon: "ph-smiley ph-bold ph-lg",
                        },
                    ]
                  : []),
              ...(user.value.instance == null
                  ? [
                        {
                            key: "clips",
                            title: i18n.ts.clips,
                            icon: "ph-paperclip ph-bold ph-lg",
                        },
                    ]
                  : []),
          ]
        : null,
);

definePageMetadata(
    computed(() =>
        user.value
            ? {
                  icon: "ph-user ph-bold ph-lg",
                  title: user.value.display_name
                      ? `${user.value.display_name} (@${user.value.username})`
                      : `@${user.value.username}`,
                  subtitle: user.value.acct,
                  userName: user.value,
                  avatar: user.value,
                  path: `/@${user.value.acct}`,
                  share: {
                      title: user.value.display_name,
                  },
              }
            : null,
    ),
);
</script>

<style lang="scss" scoped>
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.125s ease;
}
.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}
</style>
