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

// 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';
import DialogFormContainer from 'src/components/dialog/DialogFormContainer.vue';
import DialogHeader from 'src/components/dialog/DialogHeader.vue';
import FormCancel from './FormCancel.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';
import { dialogWarningClose, canAccess } from 'src/stores/utils';
import { CancelButton, SaveButton } from 'src/components/button';
import { getRole } from 'src/services/keycloak';
import FloatingActionButton from 'src/components/FloatingActionButton.vue';
import RequestListAction from './RequestListAction .vue';
import AdvanceSearch from 'src/components/shared/AdvanceSearch.vue';

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

const requestListActionData = ref<RequestData[]>();

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

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,
    startDate: pageState.searchDate[0],
    endDate: pageState.searchDate[1],
    requestDataStatus:
      pageState.statusFilter === 'None' ? undefined : pageState.statusFilter,
    // responsibleOnly: true,
  });

  if (ret) {
    $q.screen.xs ? data.value.push(...ret.result) : (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 triggerCancel(id: string) {
  dialogWarningClose(t, {
    message: t('form.warning.cancel'),
    actionText: t('dialog.action.ok'),
    action: async () => {
      const res = await requestListStore.cancelRequest(id);
      if (res) {
        fetchList();
        fetchStats();
      }
    },
  });
}

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

async function submitRejectCancel() {
  const res = await requestListStore.rejectRequest(pageState.requestId, {
    reason: pageState.rejectCancelReason,
  });

  if (res) {
    const indexRequest = data.value?.findIndex(
      (v) => v.id === pageState.requestId,
    );

    data.value[indexRequest].rejectRequestCancel = true;
    data.value[indexRequest].rejectRequestCancelReason =
      pageState.rejectCancelReason;
    pageState.rejectCancelDialog = false;
  }
}

async function openRequestListDialog() {
  const ret = await requestListStore.getRequestDataList({
    page: 1,
    pageSize: 999,
    incomplete: true,
    responsibleOnly: true,
  });

  if (ret) {
    requestListActionData.value = ret.result;
  }

  pageState.requestListActionDialog = true;
}

async function submitRequestListAction(data: {
  form: { responsibleUserLocal: boolean; responsibleUserId: string };
  selected: RequestData[];
}) {
  const res = await requestListStore.updateMessenger(
    data.selected.map((v) => v.id),
    data.form.responsibleUserId,
  );

  if (res) pageState.requestListActionDialog = false;
}

onMounted(async () => {
  pageState.gridView = $q.screen.lt.md ? true : false;
  navigatorStore.current.title = 'requestList.title';
  navigatorStore.current.path = [{ text: 'requestList.caption', i18n: true }];

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

watch(
  [
    () => pageState.inputSearch,
    () => pageState.statusFilter,
    () => pageState.searchDate,
  ],
  () => {
    page.value = 1;
    data.value = [];
    fetchList({ rotateFlowId: true });
  },
);
</script>
<template>
  <FloatingActionButton
    hide-icon
    style="z-index: 999"
    icon="mdi-account-outline"
    @click.stop="openRequestListDialog"
  ></FloatingActionButton>

  <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));
        "
      >
        {{ Object.values(stats).reduce((a, c) => a + c, 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:tag-check-outline',
                count: stats[RequestDataStatus.Ready],
                label: 'requestList.status.Ready',
                color: 'light-yellow',
              },
              {
                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',
              },
              {
                icon: 'mdi-close-circle-outline',
                count: stats[RequestDataStatus.Canceled],
                label: 'requestList.status.Canceled',
                color: 'red',
              },
            ]"
            :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="col col-md-3"
              :bg-color="$q.dark.isActive ? 'dark' : 'white'"
              v-model="pageState.inputSearch"
              debounce="200"
            >
              <template #prepend>
                <q-icon name="mdi-magnify" />
              </template>
              <template v-slot:append>
                <q-separator vertical inset class="q-mr-xs" />
                <AdvanceSearch
                  v-model="pageState.searchDate"
                  :active="$q.screen.lt.md && pageState.statusFilter !== 'None'"
                >
                  <div
                    v-if="$q.screen.lt.md"
                    class="q-mt-sm text-weight-medium"
                  >
                    {{ $t('general.status') }}
                  </div>
                  <q-select
                    v-if="$q.screen.lt.md"
                    v-model="pageState.statusFilter"
                    outlined
                    dense
                    option-value="value"
                    option-label="label"
                    map-options
                    emit-value
                    :for="'field-select-status'"
                    :options="[
                      {
                        label: $t('general.all'),
                        value: 'None',
                      },
                      {
                        label: $t('requestList.status.Pending'),
                        value: RequestDataStatus.Pending,
                      },
                      {
                        label: $t('requestList.status.Ready'),
                        value: RequestDataStatus.Ready,
                      },
                      {
                        label: $t('requestList.status.InProgress'),
                        value: RequestDataStatus.InProgress,
                      },
                      {
                        label: $t('requestList.status.Completed'),
                        value: RequestDataStatus.Completed,
                      },
                      {
                        label: $t('requestList.status.Canceled'),
                        value: RequestDataStatus.Canceled,
                      },
                    ]"
                  />
                </AdvanceSearch>
              </template>
            </q-input>

            <div class="row col-md-5" style="white-space: nowrap">
              <q-select
                v-if="$q.screen.gt.sm"
                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('general.all'),
                    value: 'None',
                  },
                  {
                    label: $t('requestList.status.Pending'),
                    value: RequestDataStatus.Pending,
                  },
                  {
                    label: $t('requestList.status.Ready'),
                    value: RequestDataStatus.Ready,
                  },
                  {
                    label: $t('requestList.status.InProgress'),
                    value: RequestDataStatus.InProgress,
                  },
                  {
                    label: $t('requestList.status.Completed'),
                    value: RequestDataStatus.Completed,
                  },
                  {
                    label: $t('requestList.status.Canceled'),
                    value: RequestDataStatus.Canceled,
                  },
                ]"
              />
              <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">
          <q-infinite-scroll
            @load="
              (_, done) => {
                if ($q.screen.gt.xs) return;
                page = page + 1;
                fetchList({ rotateFlowId: true }).then(() =>
                  done(page >= pageMax),
                );
              }
            "
          >
            <TableRequestList
              :no-link="!canAccess('customer', 'view')"
              :columns="column"
              :rows="data"
              :grid="pageState.gridView"
              :visible-columns="pageState.fieldSelected"
              :hide-action="!canAccess('requestList', 'edit')"
              @view="(data) => triggerView({ requestData: data })"
              @delete="(data) => triggerCancel(data.id)"
              @reject-cancel="
                (data) => {
                  pageState.rejectCancelDialog = true;
                  pageState.rejectCancelReason = '';
                  pageState.requestId = data.id;
                }
              "
            />
            <template v-slot:loading>
              <div
                v-if="$q.screen.lt.sm && page !== pageMax"
                class="row justify-center"
              >
                <q-spinner-dots color="primary" size="40px" />
              </div>
            </template>
          </q-infinite-scroll>
        </article>

        <!-- SEC: footer content -->
        <footer
          class="row justify-between items-center q-px-md q-py-sm surface-2"
          v-if="pageMax > 0 && $q.screen.gt.xs"
        >
          <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">
            {{
              $q.screen.gt.sm
                ? $t('general.recordsPage', {
                    resultcurrentPage: data.length,
                    total: pageState.inputSearch
                      ? data.length
                      : pageState.total,
                  })
                : $t('general.ofPage', {
                    current: 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>

    <DialogFormContainer
      width="60vw"
      height="40vh"
      v-model="pageState.rejectCancelDialog"
      @submit="() => submitRejectCancel()"
    >
      <template #header>
        <DialogHeader :title="$t('requestList.status.work.RejectCancel')" />
      </template>

      <section class="col q-pa-md scroll">
        <FormCancel v-model:reason="pageState.rejectCancelReason" />
      </section>

      <template #footer>
        <CancelButton
          class="q-ml-auto"
          outlined
          @click="() => (pageState.rejectCancelDialog = false)"
        />
        <SaveButton
          :label="$t('general.confirm')"
          class="q-ml-sm"
          icon="mdi-check"
          solid
          type="submit"
        />
      </template>
    </DialogFormContainer>

    <RequestListAction
      v-if="requestListActionData"
      v-model="pageState.requestListActionDialog"
      :request-list="requestListActionData"
      :no-link="!canAccess('customer', 'view')"
      @submit="submitRequestListAction"
    />
  </div>
</template>
<style></style>
