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

// 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 FloatingActionButton from 'components/FloatingActionButton.vue';
import DialogFormContainer from 'src/components/dialog/DialogFormContainer.vue';
import DialogHeader from 'src/components/dialog/DialogHeader.vue';
import { CancelButton, SaveButton } from 'src/components/button';
import QuotationCard from 'src/components/05_quotation/QuotationCard.vue';
import FormDebit from 'src/components/12_debit-note/FormDebit.vue';
import TableDebitNote from './TableDebitNote.vue';

// NOTE: Stores & Type
import { useNavigator } from 'src/stores/navigator';
import useFlowStore from 'src/stores/flow';
import { pageTabs, columns, hslaColors } from './constants';
import { DebitNoteStatus, useDebitNote } from 'src/stores/debit-note';
import { canAccess, dialogWarningClose } from 'src/stores/utils';
import { useQuasar } from 'quasar';
import AdvanceSearch from 'src/components/shared/AdvanceSearch.vue';

const $q = useQuasar();
const { t } = useI18n();
const flow = useFlowStore();
const navigator = useNavigator();
const debitNote = useDebitNote();
const { stats, pageMax, page, data, pageSize } = storeToRefs(debitNote);

// NOTE: Variable
const pageState = reactive({
  quotationId: '',
  currentTab: DebitNoteStatus.Issued,
  hideStat: false,
  statusFilter: 'None',
  inputSearch: '',
  fieldSelected: columns
    .filter((v) => !v.name.startsWith('#'))
    .map((v) => v.name),
  gridView: false,
  total: 0,

  debitDialog: false,
  searchDate: [],
});

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

// NOTE: Function

async function getList(opts?: { page?: number; pageSize?: number }) {
  const res = await debitNote.getDebitNoteList({
    page: opts?.page || page.value,
    pageSize: opts?.pageSize || pageSize.value,
    query: pageState.inputSearch === '' ? undefined : pageState.inputSearch,
    status: pageState.currentTab,
    includeRegisteredBranch: true,
    startDate: pageState.searchDate[0],
    endDate: pageState.searchDate[1],
  });

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

async function triggerDelete(id: string) {
  dialogWarningClose(t, {
    message: t('dialog.message.confirmDelete'),
    actionText: t('dialog.action.ok'),
    action: async () => {
      const res = await debitNote.deleteDebitNote(id);
      if (!!res) {
        getList();
      }
    },
    cancel: () => {},
  });
}

async function triggerCreateDebitNote() {
  pageState.quotationId = '';
  pageState.debitDialog = true;
}

function navigateTo(opts: {
  statusDialog: 'info' | 'edit' | 'create';
  quotationId?: string;
  debitId?: string;
}) {
  const url = new URL(
    `/debit-note/${opts.statusDialog === 'create' ? 'add' : opts.debitId}`,
    window.location.origin,
  );

  if (opts.statusDialog === 'create') {
    url.searchParams.append('quotationId', opts.quotationId || '');
  }

  url.searchParams.append('mode', opts.statusDialog);

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

async function submit() {
  navigateTo({ statusDialog: 'create', quotationId: pageState.quotationId });
  close();
}

function close() {
  pageState.debitDialog = false;
}

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

  await debitNote.getDebitNoteStats().then((res) => {
    if (res) {
      stats.value = res;

      // stats.value['issued'] = Object.values(res).reduce(
      //   (sum, value) => sum + value,
      //   0,
      // );
    }
  });

  getList();
});

watch(
  [
    () => pageState.currentTab,
    () => pageState.inputSearch,
    () => pageSize.value,
    () => pageState.statusFilter,
    () => pageState.searchDate,
  ],
  () => getList(),
);
</script>
<template>
  <!-- #TODO add  trigger dialog add debit  -->
  <FloatingActionButton
    style="z-index: 999"
    hide-icon
    v-if="canAccess('related', 'edit')"
    @click.stop="() => triggerCreateDebitNote()"
  ></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.entries(stats).reduce(
            (sum, [key, value]) => (key === 'canceled' ? sum : sum + value),
            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: 'material-symbols-light:receipt-long',
                count: stats['issued'] || 0,
                label: `debitNote.stats.${DebitNoteStatus.Issued}`,
                color: 'orange',
              },

              {
                icon: 'tabler:cash-register',
                count: stats['paymentPending'] || 0,
                label: `debitNote.stats.${DebitNoteStatus.PaymentPending}`,
                color: 'dark-orange',
              },
              {
                icon: 'fluent:receipt-money-16-regular',
                count: stats['paymentSuccess'] || 0,
                label: `debitNote.stats.${DebitNoteStatus.PaymentSuccess}`,
                color: 'green',
              },

              {
                icon: 'mdi-check-decagram-outline',
                count: stats['processComplete'] || 0,
                label: `debitNote.stats.${DebitNoteStatus.ProcessComplete}`,
                color: 'blue',
              },
            ]"
            :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"
          style="z-index: 1"
        >
          <section
            class="row q-py-sm q-px-md bordered-b 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" />
              </template>
            </q-input>

            <div class="row col-md-5 justify-end" style="white-space: nowrap">
              <q-select
                v-if="!pageState.gridView"
                id="select-field"
                for="select-field"
                class="col-md-5 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>
          </section>

          <nav class="surface-2 bordered-b q-px-md full-width">
            <q-tabs
              inline-label
              mobile-arrows
              dense
              v-model="pageState.currentTab"
              align="left"
              class="full-width"
              active-color="info"
            >
              <q-tab
                v-for="tab in pageTabs"
                :name="tab.value"
                :key="tab.value"
                @click="
                  () => {
                    pageState.currentTab = tab.value;
                    pageState.inputSearch = '';

                    flow.rotate();
                  }
                "
              >
                <div
                  class="row text-capitalize"
                  :class="
                    pageState.currentTab === tab.value
                      ? 'text-bold'
                      : 'app-text-muted'
                  "
                >
                  {{ $t(`debitNote.status.${tab.label}`) }}
                </div>
              </q-tab>
            </q-tabs>
          </nav>
        </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">
          <!-- #TODO change Table   -->
          <TableDebitNote
            :grid="pageState.gridView"
            :visible-columns="pageState.fieldSelected"
            @view="
              (item) => navigateTo({ statusDialog: 'info', debitId: item.id })
            "
            @edit="
              (item) => navigateTo({ statusDialog: 'edit', debitId: item.id })
            "
            @delete="(item) => triggerDelete(item.id)"
          >
            <template #grid="{ item }">
              <div class="col-md-4 col-sm-6 col-12">
                <QuotationCard
                  hide-kebab-edit
                  @view="
                    () =>
                      navigateTo({ statusDialog: 'info', debitId: item.row.id })
                  "
                  @edit="
                    () =>
                      navigateTo({ statusDialog: 'edit', debitId: item.row.id })
                  "
                  @delete="() => triggerDelete(item.row.id)"
                  :title="item.row.debitNoteQuotation?.workName"
                  :code="item.row.code"
                  :status="$t(`quotation.status.${item.row.quotationStatus}`)"
                  :badge-color="hslaColors[item.row.quotationStatus] || ''"
                  :custom-data="[
                    {
                      label: $t('branch.card.branchVirtual'),
                      value:
                        $i18n.locale === 'tha'
                          ? item.row.registeredBranch.name
                          : item.row.registeredBranch.nameEN,
                    },
                    {
                      label: $t('quotation.customer'),
                      value:
                        item.row.customerBranch.customer.customerType === 'CORP'
                          ? item.row.customerBranch.registerName
                          : $i18n.locale === 'tha'
                            ? `${item.row.customerBranch.firstName} ${item.row.customerBranch.lastName}`
                            : `${item.row.customerBranch.firstNameEN} ${item.row.customerBranch.lastNameEN}`,
                    },
                    {
                      label: $t('requestList.quotationCode'),
                      value: item.row.debitNoteQuotation?.code,
                    },
                    {
                      label: $t('debitNote.label.quotationPayment'),
                      value: $t(
                        `quotation.type.${item.row.debitNoteQuotation?.payCondition}`,
                      ),
                    },
                  ]"
                />
              </div>
            </template>
          </TableDebitNote>
        </article>

        <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">
            {{
              $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">
            <!-- #TODO add getList at fectch-data -->
            <PaginationComponent
              v-model:current-page="page"
              v-model:max-page="pageMax"
              :fetch-data="() => getList()"
            />
          </nav>
        </footer>
      </div>
    </section>
  </div>

  <!-- SEC: Dialog -->
  <!-- dialog create -->

  <!-- #TODO add submit at submit -->
  <DialogFormContainer
    width="60vw"
    height="500px"
    v-model="pageState.debitDialog"
    @submit="() => submit()"
  >
    <template #header>
      <DialogHeader
        :title="$t(`general.add`, { text: $t('debitNote.title') })"
      />
    </template>

    <section class="q-pa-md col full-width">
      <div class="surface-1 rounded bordered q-pa-md full-height full-width">
        <FormDebit v-model:quotation-id="pageState.quotationId" />
      </div>
    </section>

    <template #footer>
      <CancelButton class="q-ml-auto" outlined @click="close()" />
      <SaveButton
        :label="$t(`general.add`, { text: $t('debitNote.title') })"
        class="q-ml-sm"
        icon="mdi-check"
        solid
        type="submit"
      />
    </template>
  </DialogFormContainer>
</template>
<style scoped></style>
