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

import useBranchStore from 'stores/branch';

import { dialog } from 'src/stores/utils';
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 BranchCard from 'src/components/01_branch-management/BranchCard.vue';
import FormDialog from 'src/components/FormDialog.vue';
import FormBranchInformation from 'src/components/01_branch-management/FormBranchInformation.vue';
import FormLocation from 'src/components/01_branch-management/FormLocation.vue';
import FormQr from 'src/components/01_branch-management/FormQr.vue';
import FormBranchContact from 'src/components/01_branch-management/FormBranchContact.vue';

import { BranchWithChildren, BranchCreate } from 'stores/branch/types';
import { watch } from 'vue';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const modal = ref<boolean>(false);

const profileFile = ref<File | undefined>(undefined);
const qrCodeimageUrl = ref<string | null>('');

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

  const reader = new FileReader();
  reader.addEventListener('load', () => {
    if (typeof reader.result === 'string') qrCodeimageUrl.value = reader.result;
  });

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

  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 currentHq = ref<{ id: string; code: string }>({
  id: '',
  code: '',
});

const beforeBranch = ref<{ id: string; code: string }>({
  id: '',
  code: '',
});

const inputSearch = ref<string>('');
const fieldBranch = ref(['all', 'branchHQLabel', 'branchLabel']);
const fieldDisplay = ref([
  'branchLabelName',
  'branchLabelTel',
  'branchLabelAddress',
  'branchLabelType',
  'branchLabelStatus',
]);
const fieldSelected = ref<string[]>(fieldDisplay.value);
const fieldSelectedBranch = ref<{
  label: string;
  value: string;
}>({
  label: t('branchHQLabel'),
  value: 'branchHQLabel',
});

const stats = ref<{ count: number; label: string }[]>([]);

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

const formDialogRef = ref();
const formType = ref<'create' | 'edit' | 'delete'>('create');
const formTypeBranch = ref<'headOffice' | 'subBranch'>('headOffice');
const codeHq = ref<{ id: string; code: string }>({ id: '', code: '' });
const formData = ref<Omit<BranchCreate, 'qrCodeImage'>>(
  structuredClone(defaultFormData),
);

function openDialog() {
  modal.value = true;
}

async function fetchBranchById(id: string) {
  const res = await branchStore.fetchById(id);

  if (res) {
    qrCodeimageUrl.value = res.qrCodeImageUrl;
    formData.value = {
      headOfficeId: res.headOfficeId,
      taxNo: res.taxNo,
      nameEN: res.nameEN,
      name: res.name,
      addressEN: res.addressEN,
      address: res.address,
      zipCode: res.zipCode,
      email: res.email,
      contactName: res.contactName,
      contact: '',
      telephoneNo: res.telephoneNo,
      longitude: res.longitude,
      latitude: res.latitude,
      subDistrictId: res.subDistrictId,
      districtId: res.districtId,
      provinceId: res.provinceId,
      lineId: res.lineId,
    };
  }
}

function clearData() {
  formData.value = structuredClone(defaultFormData);
  profileFile.value = undefined;
}

function triggerCreate(type: string, id?: string, code?: string) {
  clearData();

  if (type === 'subBranch' && id && code) {
    formTypeBranch.value = 'subBranch';
    codeHq.value = {
      id: id,
      code: code,
    };
  } else {
    formTypeBranch.value = 'headOffice';
    codeHq.value = { id: '', code: '' };
  }

  formType.value = 'create';
  openDialog();
}

function triggerEdit(type: string, id: string, code?: string) {
  fetchBranchById(id);
  if (id && code) {
    codeHq.value = {
      id: id,
      code: code,
    };
  }
  if (type === 'subBranch' && id && code) {
    formTypeBranch.value = 'subBranch';
  } else {
    formTypeBranch.value = 'headOffice';
  }

  formType.value = 'edit';

  openDialog();
}

function triggerDelete(id: string) {
  fetchBranchById(id);
  if (id) {
    dialog({
      color: 'negative',
      icon: 'mdi-alert',
      title: 'ยืนยังการลบข้อมูล',
      actionText: 'ตกลง',
      persistent: true,
      message: 'ท่านต้องการลบข้อมูลหรือมั้ย',
      action: async () => {
        await branchStore.deleteById(id);
        await branchStore.fetchList({ pageSize: 99999 });
      },
      cancel: () => {},
    });
  }
}

async function onSubmit() {
  if (formType.value === 'edit') {
    if (!profileFile) {
      await branchStore.editById(codeHq.value.id, formData.value);
    } else {
      await branchStore.editById(
        codeHq.value.id,
        formData.value,
        profileFile.value,
      );
    }

    await branchStore.fetchList({ pageSize: 99999 });
    modal.value = false;
  }

  if (formTypeBranch.value === 'headOffice') {
    if (formType.value === 'create' && profileFile.value) {
      await branchStore.create({
        ...formData.value,
        qrCodeImage: profileFile.value,
      });
      await branchStore.fetchList({ pageSize: 99999 });
      modal.value = false;
    }
  }

  if (formTypeBranch.value === 'subBranch') {
    if (formType.value === 'create' && profileFile.value) {
      formData.value.headOfficeId = codeHq.value.id;

      await branchStore.create({
        ...formData.value,
        qrCodeImage: profileFile.value,
      });
      await branchStore.fetchList({ pageSize: 99999 });
      modal.value = false;
    }
  }
}

function changeTitle(
  formType: 'edit' | 'create' | 'delete',
  typeBranch: 'headOffice' | 'subBranch',
) {
  if (typeBranch === 'headOffice') {
    return formType === 'create' ? 'เพิ่มสำนักงานใหญ่' : 'แก้ไขสำนักงานใหญ่';
  }
  if (typeBranch === 'subBranch') {
    return formType === 'create' ? 'เพิ่มสาขา' : 'แก้ไขสาขา';
  }
  return '';
}
</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" style="flex-grow: 1; flex-wrap: nowrap">
          <div class="tree-container q-pa-md bordered-r">
            <div class="row">
              <Icon
                icon="ep:arrow-left-bold"
                width="21px"
                class="q-mr-sm"
                :class="{
                  'color-icon-arrow ': !currentHq.id,
                  'cursor-pointer': currentHq.id,
                }"
                @click="
                  () => {
                    if (currentHq.id) {
                      beforeBranch = currentHq;
                      currentHq = { id: '', code: '' };
                      fieldSelectedBranch = {
                        label: $t('branchHQLabel'),
                        value: 'branchHQLabel',
                      };
                    }
                  }
                "
              />

              <Icon
                icon="ep:arrow-right-bold"
                width="21px"
                class="q-mr-md"
                :class="{
                  'color-icon-arrow ': !beforeBranch.id,
                  'cursor-pointer': beforeBranch.id,
                }"
                @click="
                  () => {
                    if (beforeBranch.id) {
                      currentHq = beforeBranch;
                      beforeBranch = { id: '', code: '' };
                      fieldSelectedBranch = {
                        label: '',
                        value: '',
                      };
                    }
                  }
                "
              />

              <q-space />

              <Icon
                icon="pixelarticons:plus"
                height="26"
                class="color-icon-plus cursor-pointer"
                @click="triggerCreate('headOffice')"
              />
            </div>

            <div class="bordered rounded q-mt-md">
              <div
                class="bordered-b q-pl-sm text-weight-bold surface-0"
                style="height: 50px; display: flex; align-items: center"
              >
                <Icon icon="flowbite:home-solid" width="24px" class="q-mr-md" />
                ทั้งหมด
              </div>

              <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 no-wrap"
                  >
                    <span>{{ node.name }}</span>
                    <div class="q-gutter-xs flex no-wrap" @click.stop>
                      <q-btn
                        @click.stop="
                          triggerCreate('subBranch', node.id, node.code)
                        "
                        icon="mdi-file-plus-outline"
                        fab-mini
                        unelevated
                      />
                      <q-btn icon="mdi-dots-vertical" fab-mini unelevated flat>
                        <q-menu class="bordered">
                          <q-list v-close-popup>
                            <q-item
                              clickable
                              dense
                              class="row q-py-sm"
                              style="white-space: nowrap"
                            >
                              <q-icon
                                name="mdi-eye-outline"
                                class="col-3"
                                size="xs"
                                style="color: hsl(var(--green-6-hsl))"
                              />
                              <span class="col-9 q-px-md flex items-center">
                                {{ $t('viewDetail') }}
                              </span>
                            </q-item>
                            <q-item
                              clickable
                              dense
                              class="row q-py-sm"
                              style="white-space: nowrap"
                              @click="
                                () => {
                                  if (node.isHeadOffice) {
                                    triggerEdit(
                                      'headOffice',
                                      node.id,
                                      node.code,
                                    );
                                  } else {
                                    triggerEdit(
                                      'subBranch',
                                      node.id,
                                      node.code,
                                    );
                                  }
                                }
                              "
                            >
                              <q-icon
                                name="mdi-pencil-outline"
                                class="col-3"
                                size="xs"
                                style="color: hsl(var(--cyan-6-hsl))"
                              />
                              <span class="col-9 q-px-md flex items-center">
                                {{ $t('edit') }}
                              </span>
                            </q-item>
                            <q-item
                              dense
                              clickable
                              class="row"
                              style="white-space: nowrap"
                              @click="triggerDelete(node.id)"
                            >
                              <q-icon
                                name="mdi-trash-can-outline"
                                size="xs"
                                class="col-3"
                                style="color: hsl(var(--red-6-hsl))"
                              />
                              <span class="col-9 q-px-md flex items-center">
                                {{ $t('delete') }}
                              </span>
                            </q-item>

                            <q-item dense>
                              <q-item-section class="q-py-sm">
                                <div class="q-pa-sm surface-2 rounded">
                                  <q-toggle
                                    dense
                                    size="sm"
                                    :label="
                                      node.status !== 'INACTIVE'
                                        ? $t('switchOnLabel')
                                        : $t('switchOffLabel')
                                    "
                                    @click="
                                      async () => {
                                        const res = await branchStore.editById(
                                          node.id,
                                          {
                                            status:
                                              node.status !== 'INACTIVE'
                                                ? 'INACTIVE'
                                                : 'ACTIVE',
                                          },
                                        );
                                        if (res) node.status = res.status;
                                      }
                                    "
                                    :model-value="
                                      node.status === 'CREATED' ||
                                      node.status === 'ACTIVE'
                                    "
                                  />
                                </div>
                              </q-item-section>
                            </q-item>
                          </q-list>
                        </q-menu>
                      </q-btn>
                    </div>
                  </div>
                </template>
              </q-tree>
            </div>
          </div>
          <div class="branch-wrapper q-pa-md">
            <div class="q-mb-md flex" style="gap: var(--size-4)">
              <div style="flex-grow: 1; display: flex; align-items: center">
                <q-select
                  v-if="!currentHq.id"
                  outlined
                  v-model="fieldSelectedBranch"
                  :options="
                    fieldBranch.map((v) => ({ label: $t(v), value: v }))
                  "
                  :label="$t('select')"
                  dense
                />

                <div v-else class="text-weight-bold text">
                  {{ $t('branchInHQ') }}
                  {{ currentHq.code }}
                </div>
              </div>

              <div
                style="flex-grow: 1; display: flex; justify-content: flex-end"
              >
                <q-input
                  style="width: 250px"
                  outlined
                  dense
                  label="ค้นหา"
                  v-model="inputSearch"
                ></q-input>
              </div>

              <div style="flex-grow: 1">
                <q-select
                  :options="
                    fieldDisplay.map((v) => ({ label: $t(v), value: v }))
                  "
                  :display-value="$t('Fields')"
                  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
                  .filter((v) => {
                    if (!!currentHq.id && currentHq.id === v.headOfficeId) {
                      return true;
                    }
                    if (fieldSelectedBranch.value === 'all') {
                      return true;
                    }
                    if (fieldSelectedBranch.value === 'branchHQLabel') {
                      return v.isHeadOffice;
                    }
                    if (fieldSelectedBranch.value === 'branchLabel') {
                      return !v.isHeadOffice;
                    }
                    return false;
                  })
                  .map((v) => ({
                    id: v.id,
                    hq: v.isHeadOffice,
                    branchLabelCode: v.code,
                    branchLabelName:
                      $i18n.locale === 'en-US' ? v.nameEN : v.name,
                    branchLabelTel: v.contact
                      .map((c) => c.telephoneNo)
                      .join(','),
                    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,
                  }))"
                @click="
                  () => {
                    if (item.hq) {
                      fieldSelectedBranch.value = '';
                      currentHq = {
                        id: item.id,
                        code: item.branchLabelCode,
                      };

                      beforeBranch = {
                        id: '',
                        code: '',
                      };
                    }
                  }
                "
                :key="item.id"
                :data="item"
                :field-selected="fieldSelected"
                :inactive="item.branchLabelStatus === 'INACTIVE'"
                @view-detail="(b) => console.log(b)"
              />
            </div>
          </div>
        </div>
      </template>
    </AppBox>
  </div>

  <FormDialog
    ref="formDialogRef"
    v-model:modal="modal"
    v-model:address="formData.address"
    v-model:addressEN="formData.addressEN"
    v-model:province-id="formData.provinceId"
    v-model:district-id="formData.districtId"
    v-model:sub-district-id="formData.subDistrictId"
    title="เพิ่มสำนักงานใหญ่"
    :titleFormAddress="`ข้อมูลที่อยู่สำนักงานใหญ่`"
    :addressSeparator="true"
    :submit="
      () => {
        onSubmit();
      }
    "
  >
    <template #information>
      <FormBranchInformation
        v-model:code="codeHq.code"
        v-model:taxNo="formData.taxNo"
        v-model:name="formData.name"
        v-model:nameEN="formData.nameEN"
        :separator="true"
        :dense="true"
        :outlined="true"
        title="formDialogTitleInformation"
      />
    </template>

    <template #person>
      <FormBranchContact
        v-model:telephone-no="formData.telephoneNo"
        v-model:contact="formData.contact"
        v-model:email="formData.email"
        v-model:contact-name="formData.contactName"
        v-model:line-id="formData.lineId"
        :separator="true"
        title="formDialogTitleContact"
        :dense="true"
        :outlined="true"
      />
    </template>

    <template #qr-code>
      <FormQr
        title="Qr code"
        :separator="true"
        :qr="qrCodeimageUrl"
        @upload="
          () => {
            inputFile.click();
          }
        "
      />
    </template>

    <template #location>
      <FormLocation
        v-model:latitude="formData.latitude"
        v-model:longitude="formData.longitude"
        title="formDialogTitleLocation"
      />
    </template>
  </FormDialog>
</template>

<style scoped>
.color-icon-arrow {
  color: var(--gray-3);
}

.color-icon-plus {
  color: var(--cyan-6);
}

.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>
