<script setup lang="ts">
// NOTE: Library
import { computed, onMounted, reactive, watch } from 'vue';
import { storeToRefs } from 'pinia';

// NOTE: Components
import StatCardComponent from 'src/components/StatCardComponent.vue';
import NoData from 'src/components/NoData.vue';
import TableRequestList from './TableRequestList.vue';
import PaginationComponent from 'src/components/PaginationComponent.vue';
import PaginationPageSize from 'src/components/PaginationPageSize.vue';

// NOTE: Stores & Type
import { useNavigator } from 'src/stores/navigator';
import { column } from './constants';
import useFlowStore from 'src/stores/flow';
import { useRequestList } from 'src/stores/request-list';
import { RequestData, RequestDataStatus } from 'src/stores/request-list/types';

const navigatorStore = useNavigator();
const flowStore = useFlowStore();
const requestListStore = useRequestList();
const { data, stats, page, pageMax, pageSize } = storeToRefs(requestListStore);

// NOTE: Variable
const pageState = reactive({
  hideStat: false,
  statusFilter: RequestDataStatus.Pending,
  inputSearch: '',
  fieldSelected: [...column.map((v) => v.name)],
  gridView: false,
  total: 0,
});

const fieldSelectedOption = computed(() => {
  return column.map((v) => ({
    label: v.label,
    value: v.name,
  }));
});

// NOTE: Function
async function fetchList(opts?: { rotateFlowId?: boolean }) {
  const ret = await requestListStore.getRequestDataList({
    query: pageState.inputSearch,
    page: page.value,
    pageSize: pageSize.value,
    requestDataStatus: pageState.statusFilter,
  });

  if (ret) {
    data.value = ret.result;
    pageState.total = ret.total;
    pageMax.value = Math.ceil(ret.total / pageSize.value);
  }

  if (opts?.rotateFlowId) flowStore.rotate();
}

async function fetchStats() {
  const ret = await requestListStore.getRequestDataStats();
  if (ret) stats.value = ret;
}

function triggerView(opts: { requestData: RequestData }) {
  const url = new URL(
    `/request-list/${opts.requestData.id}`,
    window.location.origin,
  );
  window.open(url.toString(), '_blank');
}

onMounted(async () => {
  navigatorStore.current.title = 'requestList.title';
  navigatorStore.current.path = [{ text: 'requestList.caption', i18n: true }];

  await fetchStats();
  await fetchList({ rotateFlowId: true });
});

watch([() => pageState.inputSearch, () => pageState.statusFilter], () =>
  fetchList({ rotateFlowId: true }),
);
</script>
<template>
  <div class="column full-height no-wrap">
    <!-- SEC: stat -->
    <section class="text-body-2 q-mb-xs flex items-center">
      {{ $t('general.dataSum') }}
      <q-badge
        rounded
        class="q-ml-sm"
        style="
          background-color: hsla(var(--info-bg) / 0.15);
          color: hsl(var(--info-bg));
        "
      >
        {{ 0 }}
      </q-badge>
      <q-btn
        class="q-ml-sm"
        icon="mdi-pin-outline"
        color="primary"
        size="sm"
        flat
        dense
        rounded
        @click="pageState.hideStat = !pageState.hideStat"
        :style="pageState.hideStat ? 'rotate: 90deg' : ''"
        style="transition: 0.1s ease-in-out"
      />
    </section>

    <transition name="slide">
      <div v-if="!pageState.hideStat" class="scroll q-mb-md">
        <div style="display: inline-block">
          <StatCardComponent
            labelI18n
            :branch="[
              {
                icon: 'icon-park-outline:loading-one',
                count: stats[RequestDataStatus.Pending],
                label: 'requestList.status.Pending',
                color: 'orange',
              },
              {
                icon: 'mdi-timer-sand',
                count: stats[RequestDataStatus.InProgress],
                label: 'requestList.status.InProgress',
                color: 'blue',
              },

              {
                icon: 'mdi-check-decagram-outline',
                count: stats[RequestDataStatus.Completed],
                label: 'requestList.status.Completed',
                color: 'light-green',
              },
            ]"
            :dark="$q.dark.isActive"
          />
        </div>
      </div>
    </transition>

    <section class="col surface-1 rounded bordered overflow-hidden">
      <div class="column full-height">
        <!-- SEC: header content -->
        <header
          class="row surface-3 justify-between full-width items-center bordered-b"
          style="z-index: 1"
        >
          <div class="row q-py-sm q-px-md justify-between full-width">
            <q-input
              for="input-search"
              outlined
              dense
              :label="$t('general.search')"
              class="q-mr-md col-12 col-md-3"
              :bg-color="$q.dark.isActive ? 'dark' : 'white'"
              v-model="pageState.inputSearch"
              debounce="200"
            >
              <template #prepend>
                <q-icon name="mdi-magnify" />
              </template>
            </q-input>

            <div
              class="row col-12 col-md-5 justify-end"
              :class="{ 'q-pt-xs': $q.screen.lt.md }"
              style="white-space: nowrap"
            >
              <q-select
                v-model="pageState.statusFilter"
                outlined
                dense
                option-value="value"
                option-label="label"
                class="col"
                :class="{ 'offset-md-5': pageState.gridView }"
                map-options
                emit-value
                :for="'field-select-status'"
                :hide-dropdown-icon="$q.screen.lt.sm"
                :options="[
                  {
                    label: $t('requestList.status.Pending'),
                    value: RequestDataStatus.Pending,
                  },
                  {
                    label: $t('requestList.status.InProgress'),
                    value: RequestDataStatus.InProgress,
                  },
                  {
                    label: $t('requestList.status.Completed'),
                    value: RequestDataStatus.Completed,
                  },
                ]"
              />
              <q-select
                v-if="!pageState.gridView"
                id="select-field"
                for="select-field"
                class="col q-ml-sm"
                :options="
                  fieldSelectedOption.map((v) => ({
                    ...v,
                    label: v.label && $t(v.label),
                  }))
                "
                :display-value="$t('general.displayField')"
                :hide-dropdown-icon="$q.screen.lt.sm"
                v-model="pageState.fieldSelected"
                option-label="label"
                option-value="value"
                map-options
                emit-value
                outlined
                multiple
                dense
              />

              <q-btn-toggle
                id="btn-mode"
                v-model="pageState.gridView"
                dense
                class="no-shadow bordered rounded surface-1 q-ml-sm"
                :toggle-color="$q.dark.isActive ? 'grey-9' : 'grey-2'"
                size="xs"
                :options="[
                  { value: true, slot: 'folder' },
                  { value: false, slot: 'list' },
                ]"
              >
                <template v-slot:folder>
                  <q-icon
                    name="mdi-view-grid-outline"
                    size="16px"
                    class="q-px-sm q-py-xs rounded"
                    :style="{
                      color: $q.dark.isActive
                        ? pageState.gridView
                          ? '#C9D3DB '
                          : '#787B7C'
                        : pageState.gridView
                          ? '#787B7C'
                          : '#C9D3DB',
                    }"
                  />
                </template>
                <template v-slot:list>
                  <q-icon
                    name="mdi-format-list-bulleted"
                    class="q-px-sm q-py-xs rounded"
                    size="16px"
                    :style="{
                      color: $q.dark.isActive
                        ? pageState.gridView === false
                          ? '#C9D3DB'
                          : '#787B7C'
                        : pageState.gridView === false
                          ? '#787B7C'
                          : '#C9D3DB',
                    }"
                  />
                </template>
              </q-btn-toggle>
            </div>
          </div>
        </header>

        <!-- SEC: body content -->
        <article
          v-if="data.length === 0"
          class="col surface-2 flex items-center justify-center"
        >
          <NoData :not-found="!!pageState.inputSearch" />
        </article>
        <article v-else class="col surface-2 full-width scroll q-pa-md">
          <TableRequestList
            :columns="column"
            :rows="data"
            :grid="pageState.gridView"
            :visible-columns="pageState.fieldSelected"
            @view="(data) => triggerView({ requestData: data })"
          />
        </article>

        <!-- SEC: footer content -->
        <footer
          class="row justify-between items-center q-px-md q-py-sm surface-2"
          v-if="pageMax > 0"
        >
          <div class="col-4">
            <div class="row items-center no-wrap">
              <div class="app-text-muted q-mr-sm" v-if="$q.screen.gt.sm">
                {{ $t('general.recordPerPage') }}
              </div>
              <div><PaginationPageSize v-model="pageSize" /></div>
            </div>
          </div>
          <div class="col-4 row justify-center app-text-muted">
            {{
              $t('general.recordsPage', {
                resultcurrentPage: data.length,
                total: pageState.inputSearch ? data.length : pageState.total,
              })
            }}
          </div>
          <nav class="col-4 row justify-end">
            <PaginationComponent
              v-model:current-page="page"
              v-model:max-page="pageMax"
              :fetch-data="() => fetchList({ rotateFlowId: true })"
            />
          </nav>
        </footer>
      </div>
    </section>
  </div>
</template>
<style></style>
