<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { useQuasar } from 'quasar';
import { getUserId, getUsername, logout } from 'src/services/keycloak';
import { Icon } from '@iconify/vue';
import { useI18n } from 'vue-i18n';

import useLoader from 'stores/loader';
import DrawerComponent from 'components/DrawerComponent.vue';
import CanvasComponent from 'components/CanvasComponent.vue';
import ProfileMenu from 'components/ProfileMenu.vue';
import useUserStore from 'src/stores/user';
import FormDialog from 'components/FormDialog.vue';
import useOptionStore from 'src/stores/options';
import { dialog } from 'src/stores/utils';
import { setLocale } from 'src/utils/datetime';
import useUtilsStore from 'src/stores/utils';

interface NotificationButton {
  item: string;
  color: string;
  active: boolean;
}

interface Notification {
  id: string;
  title: string;
  content: string;
  read: boolean;
}

const $q = useQuasar();
const loaderStore = useLoader();
const utilsStore = useUtilsStore();
const optionStore = useOptionStore();

const { visible } = storeToRefs(loaderStore);
const { t, locale } = useI18n({ useScope: 'global' });
const userStore = useUserStore();

const rawOption = ref();
const canvasModal = ref(false);
const leftDrawerOpen = ref(true);
const filterUnread = ref(false);
const unread = ref<number>(1);
// const filterRole = ref<string[]>();
const userImage = ref<string>();
const canvasRef = ref();
const currentLanguage = ref<string>('ไทย');
const language: {
  value: string;
  label: string;
  icon: string;
  date: string;
}[] = [
  { value: 'th-th', label: 'ไทย', icon: 'th', date: 'th' },
  { value: 'en-US', label: 'English', icon: 'us', date: 'en-gb' },
];

const notiOpen = ref(false);
const notiMenu = ref<NotificationButton[]>([
  {
    item: 'ทั้งหมด',
    color: 'noti-switch-on',
    active: true,
  },
  {
    item: 'ยังไม่ได้อ่าน',
    color: 'noti-switch-off',
    active: false,
  },
]);
const notification = ref<Notification[]>([
  {
    id: '1',
    title: 'Unread',
    content: 'Unread',
    read: false,
  },
  {
    id: '2',
    title: 'test',
    content: 'test',
    read: false,
  },
  {
    id: '3',
    title: 'Read',
    content: 'Already read',
    read: true,
  },
]);

function setActive(button: NotificationButton) {
  notiMenu.value = notiMenu.value.map((current) => ({
    item: current.item,
    color: current.item !== button.item ? 'noti-switch-off' : 'noti-switch-on',
    active: current.item === button.item,
  }));
  if (button.item === 'ยังไม่ได้อ่าน') {
    // noti.value?.result &&
    filterUnread.value = true;
  }
  if (button.item === 'ทั้งหมด') {
    filterUnread.value = false;
  }
}

function doLogout() {
  dialog({
    icon: 'mdi-logout-variant',
    title: t('confirmLogoutTitle'),
    persistent: true,
    color: 'negative',
    message: t('confirmLogoutMessage'),
    action: async () => {
      logout();
    },
    cancel: () => {},
  });
}

watch(
  () => currentLanguage.value,
  () => {
    localStorage.setItem('currentLanguage', currentLanguage.value);
    if (rawOption.value) {
      if (locale.value === 'en-US')
        optionStore.globalOption = rawOption.value.eng;
      if (locale.value === 'th-th')
        optionStore.globalOption = rawOption.value.tha;
    }
  },
);

onMounted(async () => {
  const getCurLang = localStorage.getItem('currentLanguage');
  if (getCurLang) currentLanguage.value = getCurLang;
  if (currentLanguage.value === 'English') {
    locale.value = 'en-US';
    setLocale('en-gb');
  }
  if (currentLanguage.value === 'ไทย') {
    locale.value = 'th-th';
    setLocale('th');
  }

  const resultOption = await fetch('/option/option.json');
  rawOption.value = await resultOption.json();
  if (locale.value === 'en-US') optionStore.globalOption = rawOption.value.eng;
  if (locale.value === 'th-th') optionStore.globalOption = rawOption.value.tha;

  const user = getUsername();
  const uid = getUserId();

  userStore.userOption.roleOpts.length === 0
    ? await userStore.fetchRoleOption()
    : '';

  if (user === 'admin') return;
  if (uid) {
    const res = await userStore.fetchById(uid);

    if (res && res.profileImageUrl) userImage.value = res.profileImageUrl;
  }
});
</script>

<template>
  <q-layout view="lHh Lpr lFf">
    <drawer-component :mini="!leftDrawerOpen" />

    <q-page-container>
      <!-- drawer control -->
      <div
        style="position: relative; z-index: 1000"
        :hidden="$q.screen.lt.md && leftDrawerOpen"
      >
        <div
          size="36px"
          style="
            position: absolute;
            border-radius: 50%;
            top: 28px;
            left: -22px;
            background-color: var(--surface-1);
            border: 4px solid var(--surface-1);
          "
          class="flex items-center justify-center"
        >
          <q-btn
            flat
            dense
            round
            size="12px"
            aria-label="Menu"
            id="btn-open-drawer"
            style="
              background-color: hsl(var(--negative-bg) / 0.1);
              overflow: hidden;
            "
            @click="leftDrawerOpen = !leftDrawerOpen"
          >
            <q-icon
              :name="leftDrawerOpen ? 'mdi-backburger' : 'mdi-forwardburger'"
              size="16px"
              style="color: hsl(var(--negative-bg))"
            />
          </q-btn>
        </div>
      </div>

      <div
        class="surface-0 q-pb-lg scroll column"
        style="height: 100vh; flex-wrap: nowrap"
      >
        <!-- header -->
        <div
          class="q-px-lg surface-0 row items-center justify-between q-pb-md q-pt-lg"
          style="position: sticky; top: 0; z-index: 8"
        >
          <div class="column">
            <span
              class="title-gradient text-weight-bold"
              :class="{ 'text-h6': $q.screen.gt.xs }"
              :style="{
                filter: `brightness(${$q.dark.isActive ? '2' : '1'})`,
              }"
            >
              {{
                utilsStore.currentTitle?.title
                  ? $t(utilsStore.currentTitle?.title)
                  : $q.screen.gt.xs
                    ? 'Welcome to Jobs Worker Service'
                    : 'Jobs Worker Service'
              }}
            </span>
            <span class="text-caption">
              {{
                utilsStore.currentTitle?.caption
                  ? $t(utilsStore.currentTitle?.caption)
                  : ''
              }}
            </span>
          </div>

          <div class="row q-gutter-x-md items-center">
            <!-- notification -->
            <q-btn
              round
              dense
              flat
              class="noti-circle"
              :size="$q.screen.lt.sm ? 'sm' : ''"
              :class="{ bordered: $q.dark.isActive, dark: $q.dark.isActive }"
              style="color: var(--surface-1)"
              @click="notiOpen = !notiOpen"
            >
              <q-icon name="mdi-bell" size="20px" />
              <q-badge v-if="unread !== 0" rounded floating color="negative">
                {{ unread }}
              </q-badge>

              <q-menu
                :offset="[0, 10]"
                anchor="bottom middle"
                self="top middle"
                @before-hide="notiOpen = false"
              >
                <div class="q-px-md q-py-sm row col-12 items-center">
                  <div class="text-subtitle1 text-weight-bold">แจ้งเตือน</div>
                  <q-space />
                </div>
                <div class="q-px-md q-pb-md q-gutter-x-md">
                  <q-btn
                    rounded
                    padding="0px 10px"
                    class="text-weight-medium"
                    v-for="(btn, index) in notiMenu"
                    :flat="!btn.active"
                    :unelevated="btn.active"
                    :key="index"
                    :label="btn.item"
                    :class="btn.color"
                    @click="setActive(btn)"
                  />
                </div>
                <q-infinite-scroll :offset="250">
                  <div class="caption cursor-pointer">
                    <q-item
                      dense
                      clickable
                      class="q-py-sm"
                      v-ripple
                      v-for="item in !filterUnread
                        ? notification
                        : notification.filter((v) => !v.read)"
                      :key="item.id"
                    >
                      <q-avatar
                        color="positive"
                        style="height: 30px; width: 30px"
                      >
                        <q-icon color="white" name="mdi-check" />
                      </q-avatar>

                      <div class="col-6 column text-caption q-pl-md ellipsis">
                        <span
                          class="block ellipsis full-width text-weight-bold"
                        >
                          {{ item.title }}
                        </span>
                        <span class="block ellipsis full-width text-stone">
                          {{ item.content }}
                        </span>
                      </div>
                      <span align="right" class="col text-caption text-stone">
                        <!-- {{ moment(item.createdAt).fromNow() }} -->
                        5 s
                      </span>
                      <q-tooltip
                        anchor="top middle"
                        self="bottom middle"
                        :delay="1000"
                        :offset="[10, 10]"
                      >
                        {{ item.content }}
                      </q-tooltip>
                    </q-item>
                  </div>
                  <!-- <template v-slot:loading>
                  <div
                    class="text-center q-my-md"
                    v-if="noti && noti?.result.length < noti?.total"
                  >
                    <q-spinner-dots color="primary" size="40px" />
                  </div>
                </template> -->
                </q-infinite-scroll>
              </q-menu>
            </q-btn>

            <!-- เปลี่นนภาษา -->
            <q-btn
              round
              unelevated
              :size="$q.screen.lt.sm ? 'sm' : ''"
              v-model="currentLanguage"
              class="no-uppercase"
            >
              <Icon
                v-if="currentLanguage === 'English'"
                icon="circle-flags:us"
                :width="$q.screen.lt.sm ? '28px' : '36px'"
              />
              <Icon
                v-else
                icon="circle-flags:th"
                :width="$q.screen.lt.sm ? '28px' : '36px'"
              />

              <q-menu
                :offset="[0, 10]"
                fit
                anchor="bottom left"
                self="top left"
                auto-close
              >
                <q-list v-for="v in language" :key="v.value">
                  <q-item
                    v-if="!v.label.includes(currentLanguage)"
                    clickable
                    @click="
                      locale = v.value;
                      currentLanguage = v.label;
                      setLocale(v.date);
                    "
                  >
                    <q-item-section>
                      <div class="row items-center">
                        <Icon
                          :icon="`circle-flags:${v.icon}`"
                          class="q-mr-md"
                        />
                        {{ v.label }}
                      </div>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-menu>
            </q-btn>

            <!-- User -->
            <ProfileMenu
              @logout="doLogout"
              @edit-personal-info="console.log('edit')"
              @signature="
                () => {
                  canvasModal = true;
                }
              "
            />
          </div>
        </div>

        <q-page class="col q-px-lg">
          <router-view />
        </q-page>
      </div>
    </q-page-container>

    <FormDialog
      width="800px"
      height="550px"
      v-model:modal="canvasModal"
      no-app-box
      :title="$t('addSignature')"
      :close="() => (canvasModal = false)"
    >
      <CanvasComponent ref="canvasRef" v-model:modal="canvasModal" />
      <template #footer>
        <q-btn
          flat
          dense
          :label="$t('clear')"
          @click="
            () => {
              canvasRef.clearCanvas(), canvasRef.clearUpload();
            }
          "
          style="color: hsl(var(--text-mute))"
        />
      </template>
    </FormDialog>

    <global-loading :visibility="visible" />
  </q-layout>
</template>

<style scoped>
.text-stone {
  --_color: var(--stone-5);
  color: var(--_color);
}

.noti-circle {
  --_color: var(--stone-5);
  background-color: var(--_color);

  &.dark {
    --_color: var(--stone-9);
  }
}

.noti-switch-on {
  --_color: var(--blue-6-hsl);
  background-color: hsla(var(--_color) / 0.1) !important;
  color: hsl(var(--_color));
}

.noti-switch-off {
  --_color: var(--stone-6);
  color: var(--_color);
}

.account-menu-down {
  & ::before {
    color: var(--foreground);
  }
}

.badge {
  display: inline-block;
  border-radius: var(--radius-6);
  background-color: var(--indigo-0);
  text-wrap: nowrap;

  &.dark {
    background-color: var(--surface-3);
  }
}

.account-cover {
  height: 65px;
  background-color: var(--indigo-0);

  &.dark {
    background-color: var(--surface-3);
  }
}

.avartar-border {
  margin-top: 24px;
  border: 5px solid var(--surface-1);
  border-radius: 50%;
  position: absolute;
}

.logout-btn {
  color: hsl(var(--negative-bg));
  background-color: hsl(var(--stone-3-hsl));

  &.dark {
    background-color: transparent;
    border: 1px solid hsl(var(--negative-bg));
  }
}

.title-gradient {
  background: linear-gradient(to right, var(--brand-1), var(--brand-2));
  background-clip: text; /* Standard property */
  -webkit-background-clip: text; /* WebKit fallback */
  -webkit-text-fill-color: transparent; /* WebKit fallback */
  color: transparent; /* Fallback for browsers not supporting text-clip */
}

:deep(main.q-page) {
  min-height: 0 !important;
}
</style>
