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

// NOTE:  Components
import StatCardComponent from 'src/components/StatCardComponent.vue';
import NoData from 'src/components/NoData.vue';
import PaginationComponent from 'src/components/PaginationComponent.vue';
import PaginationPageSize from 'src/components/PaginationPageSize.vue';
import TableInvoice from './TableInvoice.vue';
import QuotationCard from 'src/components/05_quotation/QuotationCard.vue';

// NOTE: Stores & Type
import { useNavigator } from 'src/stores/navigator';
import { columns, hslaColors } from './constants';
import useFlowStore from 'src/stores/flow';
import { useInvoice } from 'src/stores/payment';
import { Invoice, PaymentDataStatus } from 'src/stores/payment/types';

const $q = useQuasar();
const navigatorStore = useNavigator();
const flowStore = useFlowStore();
const invoiceStore = useInvoice();
const { data, stats, page, pageMax, pageSize } = storeToRefs(invoiceStore);
const refFilter = ref<InstanceType<typeof QSelect>>();

// NOTE: Variable
const pageState = reactive({
  hideStat: false,
  statusFilter: 'None' as 'None' | PaymentDataStatus,
  inputSearch: '',
  fieldSelected: [...columns.map((v) => v.name)],
  gridView: false,
  total: 0,
});

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

async function fetchList(opts?: { rotateFlowId?: boolean }) {
  const ret = await invoiceStore.getInvoiceList({
    page: page.value,
    pageSize: pageSize.value,
    query: pageState.inputSearch,
    pay:
      pageState.statusFilter === PaymentDataStatus.Success
        ? true
        : pageState.statusFilter === PaymentDataStatus.Wait
          ? false
          : undefined,
    quotationOnly: true,
    debitNoteOnly: false,
  });
  if (ret) {
    data.value = $q.screen.xs ? [...data.value, ...ret.result] : 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 invoiceStore.getInvoiceStats({
    quotationOnly: true,
    debitNoteOnly: false,
  });
  if (ret) stats.value = ret;
}

function triggerView(opts: { quotationId: string }) {
  const url = new URL('/quotation/view?tab=invoice', window.location.origin);

  localStorage.setItem(
    'new-quotation',
    JSON.stringify({
      quotationId: opts.quotationId,
      statusDialog: 'info',
    }),
  );

  window.open(url.toString(), '_blank');
}

function viewDocExample(quotationId: string, codeInvoice: string) {
  console.log(codeInvoice);

  localStorage.setItem(
    'quotation-preview',
    JSON.stringify({
      data: {
        id: quotationId,
        codeInvoice,
        fetch: true,
      },
    }),
  );

  const url = new URL('/quotation/document-view', window.location.origin);

  url.searchParams.append('type', 'invoice');

  window.open(url, '_blank');
}

onMounted(async () => {
  pageState.gridView = $q.screen.lt.md ? true : false;

  navigatorStore.current.title = 'invoice.title';
  navigatorStore.current.path = [{ text: 'invoice.caption', i18n: true }];

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

watch(
  [
    () => pageState.inputSearch,
    () => pageState.statusFilter,
    () => pageSize.value,
  ],
  () => {
    page.value = 1;
    data.value = [];
    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));
        "
      >
        {{ 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: 'mdi-timer-sand',
                count: stats[PaymentDataStatus.Wait],
                label: 'invoice.status.PaymentWait',
                color: 'orange',
              },
              {
                icon: 'mdi-check-decagram-outline',
                count: stats[PaymentDataStatus.Success],
                label: 'invoice.status.PaymentSuccess',
                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="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-if="$q.screen.lt.md" v-slot:append>
                <span class="row">
                  <q-separator vertical />
                  <q-btn
                    icon="mdi-filter-variant"
                    unelevated
                    class="q-ml-sm"
                    padding="4px"
                    size="sm"
                    rounded
                    @click="refFilter?.showPopup"
                  />
                </span>
              </template>
            </q-input>

            <div class="row col-md-5" style="white-space: nowrap">
              <q-select
                v-show="$q.screen.gt.sm"
                ref="refFilter"
                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('invoice.status.PaymentWait'),
                    value: PaymentDataStatus.Wait,
                  },
                  {
                    label: $t('invoice.status.PaymentSuccess'),
                    value: PaymentDataStatus.Success,
                  },
                ]"
              />
              <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
            :offset="100"
            @load="
              (_, done) => {
                if ($q.screen.gt.xs || page === pageMax) return;
                page = page + 1;
                fetchList({ rotateFlowId: true }).then(() =>
                  done(page >= pageMax),
                );
              }
            "
          >
            <TableInvoice
              :columns="columns"
              :rows="data"
              :grid="pageState.gridView"
              @view="(quotationId) => triggerView({ quotationId })"
              @preview="(item) => viewDocExample(item.quotation.id, item.code)"
            >
              <template #grid="{ item }">
                <div class="col-md-4 col-sm-6 col-12">
                  <QuotationCard
                    hide-action
                    :code="item.row.code"
                    :title="item.row.quotation.workName"
                    :status="
                      $t(`invoice.status.${item.row.payment.paymentStatus}`)
                    "
                    :badge-color="
                      hslaColors[item.row.payment.paymentStatus] || ''
                    "
                    :custom-data="[
                      {
                        label: $t('general.customer'),
                        value:
                          item.row.quotation.customerBranch.registerName ||
                          `${item.row.quotation.customerBranch?.firstName || '-'} ${item.row.quotation.customerBranch?.lastName || ''}`,
                      },
                      {
                        label: $t('taskOrder.issueDate'),
                        value: new Date(item.row.createdAt).toLocaleString(
                          'th-TH',
                          {
                            hour12: false,
                          },
                        ),
                      },
                      {
                        label: $t('invoice.paymentDueDate'),
                        value: new Date(
                          item.row.quotation.dueDate,
                        ).toLocaleDateString('th-TH', {
                          year: 'numeric',
                          month: '2-digit',
                          day: 'numeric',
                        }),
                      },
                      {
                        label: $t('quotation.payType'),
                        value: $t(
                          `quotation.type.${item.row.quotation.payCondition}`,
                        ),
                      },
                      {
                        label: $t('preview.netValue'),
                        value: item.row.amount,
                      },
                    ]"
                    @view="
                      () => triggerView({ quotationId: item.row.quotation.id })
                    "
                    @preview="
                      () => viewDocExample(item.row.quotation.id, item.row.code)
                    "
                  />
                </div>
              </template>
            </TableInvoice>
            <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>
  </div>
</template>
<style scoped></style>
