<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { ref, onMounted, computed } from 'vue';

import useBranchStore from 'stores/branch';

import AppBox from 'components/app/AppBox.vue';
import AddButton from 'components/AddButton.vue';
import TooltipComponent from 'components/TooltipComponent.vue';
import StatCard from 'components/StatCardComponent.vue';

import { BranchContactCreate } from 'stores/branch-contact/types';
import { BranchWithChildren, BranchCreate } from 'stores/branch/types';
import { watch } from 'vue';
import { useI18n } from 'vue-i18n';
import BranchCard from 'src/components/01_branch-management/BranchCard.vue';

const profileFile = ref<File | undefined>(undefined);

const inputFile = (() => {
  const element = document.createElement('input');
  element.type = 'file';
  element.accept = 'image/*';

  element.addEventListener('change', () => {
    profileFile.value = element.files?.[0];
  });

  return element;
})();

const branchStore = useBranchStore();
const { locale } = useI18n();

const { data: branchData } = storeToRefs(branchStore);

const treeData = computed(() => {
  const arr: BranchWithChildren[] = [];

  branchData.value?.result.forEach((a) => {
    if (a.isHeadOffice) arr.push(Object.assign(a, { branch: [] }));
    else arr.find((b) => b.id === a.headOfficeId)?.branch.push(a);
  });

  return arr;
});

onMounted(async () => {
  await branchStore.fetchList({ pageSize: 99999 });
  const _stats = await branchStore.stats();

  if (_stats) {
    stats.value.push(
      { count: _stats.hq, label: 'branchHQLabel' },
      { count: _stats.br, label: 'branchLabel' },
    );
  }
});

watch(locale, () => {
  console.log(locale.value);
});

const fieldDisplay = ref([
  'branchLabelName',
  'branchLabelTel',
  'branchLabelAddress',
  'branchLabelType',
  'branchLabelStatus',
]);
const fieldSelected = ref<string[]>(fieldDisplay.value);
const stats = ref<{ count: number; label: string }[]>([]);

const defaultFormData = {
  headOfficeId: null,
  taxNo: '',
  nameEN: '',
  name: '',
  addressEN: '',
  address: '',
  zipCode: '',
  email: '',
  telephoneNo: '',
  longitude: '',
  latitude: '',
  subDistrictId: '',
  districtId: '',
  provinceId: '',
  contact: [{ lineId: '', telephoneNo: '' }],
};

const formData = ref<BranchCreate & { contact: BranchContactCreate[] }>(
  structuredClone(defaultFormData),
);

function clearData() {
  formData.value = structuredClone(defaultFormData);
  profileFile.value = undefined;
}
</script>

<template>
  <div class="column">
    <div class="row text-h6 text-weight-bold q-mb-md">
      {{ $t('branchManagement') }}
    </div>

    <AppBox bordered class="q-mb-md">
      <StatCard :branch="stats" :dark="$q.dark.isActive" />
    </AppBox>

    <AppBox class="column" no-padding bordered style="min-height: 70vh">
      <template v-if="!branchData.total">
        <TooltipComponent
          class="self-end"
          title="branchNoMainOfficeYet"
          caption="branchClickToCreateMainOffice"
          imgSrc="personnel-table-"
        />

        <div class="row items-center justify-center" style="flex-grow: 1">
          <AddButton label="branchAdd" @trigger="() => {}" />
        </div>
      </template>
      <template v-else>
        <div
          class="row bordered-b q-pa-md"
          :style="{
            color: 'var(--brand-1)',
            backgroundColor: 'hsla(var(--info-bg) / .1)',
          }"
        >
          <div class="text-h5"><q-icon name="mdi-home"></q-icon></div>
        </div>
        <div class="row" style="flex-grow: 1; flex-wrap: nowrap">
          <div class="tree-container q-pa-md bordered-r">
            <q-tree
              :nodes="treeData"
              node-key="id"
              label-key="name"
              children-key="branch"
            >
              <template #default-header="{ node }">
                <div class="row items-center justify-between full-width">
                  <span>{{ node.name }}</span>
                  <div class="q-gutter-xs" @click.stop>
                    <q-btn icon="mdi-file-plus-outline" fab-mini unelevated />
                    <q-btn icon="mdi-dots-vertical" fab-mini unelevated />
                  </div>
                </div>
              </template>
            </q-tree>
          </div>
          <div class="branch-wrapper q-pa-md">
            <div class="q-mb-md flex" style="gap: var(--size-4)">
              <div style="flex-grow: 1">
                <q-select
                  :options="
                    fieldDisplay.map((v) => ({ label: $t(v), value: v }))
                  "
                  v-model="fieldSelected"
                  option-label="label"
                  option-value="value"
                  map-options
                  emit-value
                  outlined
                  multiple
                  dense
                />
              </div>
              <div style="flex-grow: 1">
                <q-select
                  :options="
                    fieldDisplay.map((v) => ({ label: $t(v), value: v }))
                  "
                  v-model="fieldSelected"
                  option-label="label"
                  option-value="value"
                  map-options
                  emit-value
                  outlined
                  multiple
                  dense
                />
              </div>
            </div>
            <div class="branch-container">
              <BranchCard
                v-for="item in branchData.result.map((v) => ({
                  id: v.id,
                  hq: v.isHeadOffice,
                  branchLabelCode: v.code,
                  branchLabelName: $i18n.locale === 'en-US' ? v.nameEN : v.name,
                  branchLabelTel: v.telephoneNo,
                  branchLabelAddress:
                    $i18n.locale === 'en-US'
                      ? `${v.addressEN || ''} ${v.subDistrict?.nameEN || ''} ${v.district?.nameEN || ''} ${v.province?.nameEN || ''}`
                      : `${v.address || ''} ${v.subDistrict?.name || ''} ${v.district?.name || ''} ${v.province?.name || ''}`,
                  branchLabelType: $t(
                    v.isHeadOffice ? 'branchHQLabel' : 'branchLabel',
                  ),
                  branchLabelStatus: v.status,
                }))"
                :key="item.id"
                :data="item"
                :field-selected="fieldSelected"
                @view-detail="(b) => console.log(b)"
              />
            </div>
          </div>
        </div>
      </template>
    </AppBox>
  </div>
</template>

<style scoped>
.tree-container {
  width: 100%;
  min-width: 300px;
  max-width: 25%;
  max-height: 100%;
}

.branch-wrapper {
  flex-grow: 1;

  & > .branch-container {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: unset;
    gap: var(--size-4);
  }
}
</style>
