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

import useBranchStore from 'stores/branch';
import AppBox from 'components/app/AppBox.vue';
import BtnAddComponent from 'components/01_branch-management/BtnAddComponent.vue';
import TooltipComponent from 'components/TooltipComponent.vue';
import StatCardComponent from 'components/StatCardComponent.vue';
import CardDetailsComponent from 'src/components/01_branch-management/CardDetailsComponent.vue';
import DeatailsBranchDrawerComponent from 'src/components/01_branch-management/DeatailsBranchDrawerComponent.vue';
import FormDialog from 'src/components/FormDialog.vue';

import { BranchWithChildren, Branch } from 'src/stores/branch/types';

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

const modal = ref<boolean>(false);

const showCurrentBranch = ref<Branch | boolean | null>();

const shape = ref<boolean>(false);
const openBranchDrawer = ref<boolean>(true);

const inputSelectBranch = ref<string>('ทั้งหมด');
const inputFilter = ref<string>('คอลัมน์');
const inputSearch = ref<string>('');
const optionsBranch: string[] = ['ทั้งหมด', 'สำนักงานใหญ่', 'สาขา'];
const optionsFilter: string[] = [
  'ชื่อสาขา',
  'ที่อยู่',
  'เบอร์โทร',
  'สำนักงานใหญ่',
  'ประเภท',
  'สถานะ',
];

const formData = ref({
  hqId: '',
  branchId: '',
  tel: '',
  gender: '',
  email: '',
  addressL: {
    address: '',
    province: '',
    district: '',
    subDistrict: '',
    zip: '',
  },
  addressEng: {
    address: '',
    province: '',
    district: '',
    subDistrict: '',
    zip: '',
  },
});

const selected = ref<string>('');

const headOfficeCode = ref<string>('');
const headOfficeName = ref<string>('');
const taxIDNumber = ref<string>('');
const nameHeadOfficeEN = ref<string>('');
const inputPhone = ref<string>('');
const inputIdLine = ref<string>('');
const inputPhoneHeadOffice = ref<string>('');
const inputEmailHeadOffice = ref<string>('');

const expanded = ref<string[]>([]);

const rows: {
  name: string;
  branchName: string;
  address: string;
  phonNumber: string;
  Headquarters: string;
  type: string;
  status: string;
}[] = [
  {
    name: 'HQ0001',
    branchName: 'จ็อบเวิร์ทเกอร์เซอร์วิส',
    address: '192',
    phonNumber: '0639195701',
    Headquarters: 'HQ0001',
    type: 'สำนักงานใหญ่',
    status: 'เปิดใช้งาน',
  },
  {
    name: 'HQ0002',
    branchName: 'จ็อบเวิร์ทเกอร์เซอร์วิส 2',
    address: '192',
    phonNumber: '0639195701',
    Headquarters: 'HQ0001',
    type: 'สำนักงานใหญ่',
    status: 'เปิดใช้งาน',
  },

  {
    name: 'HQ0002',
    branchName: 'จ็อบเวิร์ทเกอร์เซอร์วิส 2',
    address: '192',
    phonNumber: '0639195701',
    Headquarters: 'HQ0001',
    type: 'สำนักงานใหญ่',
    status: 'เปิดใช้งาน',
  },
];

const branchStat = ref<
  {
    amount: number;
    label: string;
  }[]
>([
  {
    amount: 1,
    label: 'สำนักงานใหญ่ 1',
  },

  {
    amount: 2,
    label: 'สำนักงานใหญ่ 2',
  },
  {
    amount: 3,
    label: 'สำนักงานใหญ่ 3',
  },
  {
    amount: 4,
    label: 'สำนักงานใหญ่ 4',
  },
  {
    amount: 5,
    label: 'สำนักงานใหญ่ 5',
  },
]);

const treeData = ref<BranchWithChildren[]>([]);

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

async function getTree() {
  const result = await branchStore.fetchList<BranchWithChildren>({
    tree: true,
  });
  if (result) treeData.value = result.result;
}

async function fetchBranch(id: string) {
  if (typeof branchStore.fetchById(id) === 'object') {
    showCurrentBranch.value = await branchStore.fetchById(id);
  }
}

onMounted(async () => {
  await getTree();

  if (
    typeof branchStore.fetchById('bfff119e-079d-4b56-9699-0466ade4b517') ===
    'object'
  ) {
    showCurrentBranch.value = await branchStore.fetchById(
      'bfff119e-079d-4b56-9699-0466ade4b517',
    );
  }
});
</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"
      :class="{ 'bg-card-branch-title': $q.dark.isActive }"
    >
      <StatCardComponent :branch="branchStat" />
    </AppBox>

    <AppBox
      bordered
      style="width: 100%; height: 500px"
      v-if="!branchData?.total"
    >
      <div class="column" style="height: 100%">
        <div class="col-1 self-end">
          <TooltipComponent
            title="branchNoMainOfficeYet"
            caption="branchClickToCreateMainOffice"
            imgSrc="img-table-"
          />
        </div>
        <div class="col self-center" style="display: flex; align-items: center">
          <BtnAddComponent
            :label="'สร้างสำนักงานใหญ่'"
            @trigger="() => openDialog()"
          />
        </div>
      </div>
    </AppBox>

    <AppBox
      class="bordered branch-container"
      :class="{ dark: $q.dark.isActive }"
      style="width: 100%; height: 500px; padding: 0"
    >
      <AppBox class="bg-card-branch-title" style="border-radius: 0">
        <div class="row items-center">
          <div
            class="col q-pl-md text-h6 text-weight-bold color-card-branch-title"
          >
            {{ $t('headQuarters') }}
          </div>
          <div class="col-3">
            <q-input
              class="bordered rounded q-px-md"
              borderless
              dense
              v-model="inputSearch"
              label="ค้นหา"
            >
              <template #prepend>
                <Icon icon="ic:baseline-search" />
              </template>
            </q-input>
          </div>
        </div>
      </AppBox>

      <AppBox
        class="no-padding row bordered-t"
        style="height: 423px; border-radius: 0"
      >
        <div class="q-pa-md bg-branch-tree-box bordered-r" style="width: 21%">
          <div
            @click="() => console.log('test')"
            class="btn-add col-2 text-weight-bold cursor-pointer color-card-branch-btn"
          >
            <div class="text-h4 q-mr-md">+</div>
            {{ $t('btnCreate') }}
          </div>

          <q-scroll-area
            class="q-pa-sm bg-branch-tree-scroll"
            style="height: 350px; width: 100%; border-radius: 6px"
          >
            <div class="col">
              <q-tree
                :nodes="treeData"
                dense
                node-key="name"
                v-model:expanded="expanded"
                v-model:selected="selected"
                children-key="branch"
              >
                <template #default-header="prop">
                  <div
                    @click="fetchBranch(prop.node.id)"
                    class="q-pa-sm color-brach-tree-text"
                    :class="{
                      'color-tree-active': expanded.includes(prop.node.name),
                      'bg-branch-tree':
                        prop.node.isHeadOffice &&
                        expanded.includes(prop.node.name),
                      'dark-tree': $q.dark.isActive,
                    }"
                    style="border-radius: 6px"
                  >
                    {{ prop.node.name }}
                  </div>

                  <q-space />

                  <q-btn
                    class="color-brach-tree-btn"
                    @click.stop=""
                    size="xl"
                    flat
                    v-if="prop.node.isHeadOffice"
                    dense
                  >
                    <Icon
                      v-if="expanded.includes(prop.node.name)"
                      icon="eva:file-add-fill"
                    />

                    <Icon v-else icon="eva:file-add-outline" />
                  </q-btn>

                  <q-btn
                    class="color-brach-tree-btn"
                    @click.stop=""
                    size="xl"
                    dense
                    flat
                    name="menu"
                  >
                    <Icon icon="ri:more-2-fill" />
                    <q-menu class="bordered" style="width: 150px">
                      <q-list class="q-pa-sm">
                        <q-item clickable v-close-popup class="no-padding">
                          <q-item-section avatar>
                            <q-icon
                              style="color: hsla(var(--cyan-6-hsl) / 1)"
                              ize="22px"
                              name="mdi-pencil-outline"
                            />
                          </q-item-section>

                          <q-item-section>
                            {{ $t('edit') }}
                          </q-item-section>
                        </q-item>

                        <q-item clickable v-close-popup class="no-padding">
                          <q-item-section avatar>
                            <q-icon
                              style="color: hsla(var(--red-6-hsl) / 1)"
                              size="22px"
                              name="mdi-trash-can-outline"
                            />
                          </q-item-section>

                          <q-item-section>{{ $t('delete') }}</q-item-section>
                        </q-item>

                        <q-item clickable v-close-popup class="q-px-sm">
                          <q-item-section>
                            <div
                              class="bg-branch-tree-toggle q-pa-sm"
                              style="border-radius: 6px"
                              :class="{
                                'dark-toggle': $q.dark.isActive,
                              }"
                            >
                              <q-toggle
                                dense
                                :label="$t('closedStatus')"
                                size="sm"
                                v-model="shape"
                                val="md"
                              />
                            </div>
                          </q-item-section>
                        </q-item>
                      </q-list>
                    </q-menu>
                  </q-btn>
                </template>
              </q-tree>
            </div>
          </q-scroll-area>
        </div>

        <div class="col full-height" style="overflow-y: auto">
          <AppBox class="q-pb-none">
            <div class="row">
              <div class="col">
                <q-select
                  style="width: 150px"
                  dense
                  outlined
                  v-model="inputSelectBranch"
                  :options="optionsBranch"
                  label="เลือก"
                />
              </div>
              <div class="col-2 q-pr-md">
                <q-input dense outlined v-model="inputSearch">
                  <template #append>
                    <Icon icon="ic:baseline-search" />
                  </template>
                </q-input>
              </div>
              <div class="col-2">
                <q-select
                  style="width: 150px"
                  dense
                  outlined
                  v-model="inputFilter"
                  :options="optionsFilter"
                />
              </div>
            </div>
          </AppBox>

          <AppBox>
            <TableCardComponent :subBranch="true" :rows="rows" />
          </AppBox>
        </div>

        <div
          v-if="false"
          class="col bordered full-height"
          style="overflow-y: auto"
        >
          <CardDetailsComponent
            :data="showCurrentBranch as Branch"
            class="q-pa-sm"
          />
        </div>
      </AppBox>
    </AppBox>
  </div>

  <DeatailsBranchDrawerComponent
    @open="openBranchDrawer = !openBranchDrawer"
    :open="openBranchDrawer"
    :data="showCurrentBranch as Branch"
  />

  <FormDialog
    v-model:modal="modal"
    v-model:addressL="formData.addressL"
    v-model:addressEng="formData.addressEng"
    title="เพิ่มสำนักงานใหญ่"
    addressLocaleTitle="ที่อยู่พนักงาน"
    addressEngTitle="ที่อยู่พนักงาน ENG"
  >
    <template #top>
      <div class="row full-width">
        <div class="col">
          <q-input
            v-model="headOfficeCode"
            dense
            outlined
            label="รหัสสำนักงานใหญ่"
          />
        </div>

        <div class="col q-pl-md">
          <q-input
            v-model="taxIDNumber"
            dense
            outlined
            label="เลขประจำตัวผู้เสียภาษี"
          />
        </div>
      </div>

      <div class="row full-width">
        <div class="col">
          <q-input
            v-model="headOfficeName"
            dense
            outlined
            label="ชื่อสำนักงานใหญ่"
          />
        </div>

        <div class="col q-pl-md">
          <q-input
            v-model="nameHeadOfficeEN"
            dense
            outlined
            label="ชื่อสำนักงานใหญ่ ภาษาอังกฤษ"
          />
        </div>
      </div>
    </template>

    <template #append>
      <AppBox class="q-mt-md" style="background: var(--gray-1)">
        <div class="row q-mb-md">
          <div class="col">
            <q-input
              v-model="inputPhone"
              dense
              outlined
              label="เบอร์โทรศัพท์"
            />
          </div>
          <div class="col q-pl-md">
            <q-input v-model="inputIdLine" dense outlined label="id line" />
          </div>
        </div>

        <div
          style="
            border: 2px dashed var(--gray-4);
            border-radius: 10px;
            background-image: linear-gradient(
              180deg,
              var(--indigo-0),
              var(--sand-0)
            );
          "
          class="q-pa-md column items-center justify-center full-width"
        >
          <div class="col q-pb-md" style="opacity: 0.3">
            <q-btn
              unelevated
              class="bg-white"
              style="border: 3px solid grey; border-radius: 6px"
            >
              <Icon icon="teenyicons:add-outline" width="20px" height="50px" />
            </q-btn>
          </div>
          <div class="col">
            <q-btn
              style="
                background: var(--blue-5);
                color: var(--blue-0);
                font-size: 12px;
              "
              unelevated
              rounded
              label="อัปโหลด QR Code"
            ></q-btn>
          </div>
        </div>
      </AppBox>
    </template>

    <template #mid-bottom>
      <div>
        <div class="row full-width q-pb-md">
          <div class="col q-pr-md">
            <q-input
              v-model="inputPhoneHeadOffice"
              dense
              outlined
              label="เบอร์โทรศัพท์สำนักงานใหฐ่"
            />
          </div>
          <div class="col">
            <q-input
              v-model="inputEmailHeadOffice"
              dense
              outlined
              label="อีเมลติดต่อสำนักงานใหญ่ "
            />
          </div>
        </div>

        <div
          class="column q-pa-sm full-width bordered"
          style="border-radius: 6px"
        >
          <div class="col">location</div>
          <div class="col self-center bg-image q-pa-md">
            <q-btn
              rounded
              style="
                background: var(--blue-5);
                color: var(--blue-0);
                font-size: 12px;
              "
              class="flex flrx-center"
              label="location"
            ></q-btn>
          </div>
        </div>
      </div>
    </template>
  </FormDialog>
</template>

<style scoped>
.bg-image {
  background-image: url(/map.png);
  background-repeat: no-repeat;
  background-size: auto;
}

.branch-container {
  --_color-branch-tree-text: var(--blue-6-hsl);
  --_color-branch-title: var(--blue-10-hsl);
  --_bg-branch-title: var(--_color-branch-title) / 0.08;
  --_color-branch-btn: var(--cyan-6-hsl);
  --_color-branch-tree-active: var(--blue-6-hsl);
  --_bg-branch-tree-box: var(--gray-0-hsl);
  --_bg-branch-tree-scroll: var(--gray-0-hsl);
  --_color-branch-tree-scroll: var(--gray-0-hsl);

  &.dark {
    --_color-branch-title: var(--blue-0-hsl);
    --_bg-branch-title: var(--gray-9-hsl) / 1;
    --_color-branch-btn: var(--cyan-6-hsl);
    --_color-branch-tree-active: var(--blue-6-hsl);
    --_bg-branch-tree-box: var(--gray-10-hsl);
    --_bg-branch-tree-scroll: var(--gray-11-hsl);
    --_color-branch-tree-scroll: var(--gray-8-hsl);
  }
}

.bg-branch-tree-toggle {
  --_bg-branch-tree-toggle: var(--gray-3-hsl);
  background: hsl(var(--_bg-branch-tree-toggle));

  &.dark-toggle {
    --_bg-branch-tree-toggle: var(--gray-9-hsl);
  }
}

.bg-branch-tree-scroll {
  background: hsl(var(--_bg-branch-tree-scroll));
  color: hsl(var(--_color-branch-tree-scroll));
}

.bg-branch-tree-box {
  background: hsl(var(--_bg-branch-tree-box));
}

.bg-card-branch-title {
  background: hsla(var(--_bg-branch-title));
}

.color-card-branch-title {
  color: hsl(var(--_color-branch-title));
}

.color-card-branch-btn {
  color: hsl(var(--_color-branch-btn));
  display: flex;
  align-items: center;
}

.color-brach-tree-text,
.color-brach-tree-btn {
  color: var(--stone-6);
}

.color-tree-active {
  color: hsl(var(--_color-branch-tree-active));
}

.bg-branch-tree {
  background: hsla(var(--_color-branch-tree-active) / 0.08);

  &.dark-tree {
    background: hsla(var(--_color-branch-tree-active) / 0.01);
    border: 1px solid hsla(var(--_color-branch-tree-active));
  }
}
</style>
