<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import AppBox from 'components/app/AppBox.vue';

import { Province, District, SubDistrict } from 'stores/address';
import useAddressStore from 'stores/address';

defineProps<{
  title: string;
  addressTitle: string;
  addressENTitle: string;
  submit?: (...args: unknown[]) => void;
  close?: (...args: unknown[]) => void;
}>();

const adrressStore = useAddressStore();
const modal = defineModel('modal', { default: false });
const address = defineModel('address', { default: '' });
const addressEN = defineModel('addressEN', { default: '' });
const provinceId = defineModel<string>('provinceId');
const districtId = defineModel<string>('districtId');
const subDistrictId = defineModel<string>('subDistrictId');
const zipCode = defineModel<string>('zipCode', { default: '' });

const addrOptions = ref<{
  provinceOps?: Province[];
  districtOps?: District[];
  subDistrictOps?: SubDistrict[];
}>({});

async function fetchProvince() {
  const result = await adrressStore.fetchProvince();
  if (result) {
    addrOptions.value.provinceOps = result;
  }
}

async function fetchDistrict(id: string | undefined) {
  if (id) {
    const result = await adrressStore.fetchDistrictByProvinceId(id);
    if (result) {
      addrOptions.value.districtOps = result;
    }
  }
}

async function fetchSubDistrict(id: string | undefined) {
  if (id) {
    const result = await adrressStore.fetchSubDistrictByProvinceId(id);
    if (result) {
      console.log(addrOptions.value.subDistrictOps);
      addrOptions.value.subDistrictOps = result;
    }
  }
}

onMounted(async () => {
  await fetchProvince();
});

watch(provinceId, async (v) => {
  await fetchDistrict(v);
});

watch(districtId, async (v) => {
  subDistrictId.value = undefined;
  await fetchSubDistrict(v);
});

watch(subDistrictId, async (v) => {
  zipCode.value =
    addrOptions.value.subDistrictOps
      ?.filter((x) => x.id === v)
      .map((x) => x.zipCode)[0] ?? '';
});

watch(provinceId, (v) => {
  if (v) {
    addrOptions.value.districtOps = [];
    addrOptions.value.subDistrictOps = [];
    districtId.value = undefined;
    subDistrictId.value = undefined;
  }
});
</script>
<template>
  <q-dialog full-width v-model="modal">
    <AppBox style="padding: 0; border-radius: var(--radius-2)">
      <q-form greedy @submit.prevent @validation-success="submit">
        <!-- header -->
        <q-card-section class="form-header">
          <div class="row items-center justity-between">
            <div
              class="col text-subtitle1 text-weight-bold"
              style="color: hsl(var(--info-bg))"
            >
              {{ title }}
            </div>
            <q-btn
              round
              flat
              id="closeDialog"
              icon="mdi-close"
              padding="xs"
              class="close-btn"
              :class="{ dark: $q.dark.isActive }"
              v-close-popup
              @click="close"
            />
          </div>
        </q-card-section>

        <!-- form-top -->
        <div class="form-body-top" :class="{ dark: $q.dark.isActive }">
          <q-card-section class="column col-12">
            <div class="row q-col-gutter-x-md" style="row-gap: 16px">
              <slot name="top"></slot>
            </div>
          </q-card-section>
        </div>

        <!-- form-mid -->
        <div class="row" style="overflow-y: auto; max-height: 50vh">
          <!-- prepend -->
          <q-card-section
            class="column col-4"
            v-if="$slots.prepend && !$slots.append"
          >
            <slot name="prepend"></slot>
          </q-card-section>
          <!-- center -->
          <q-card-section
            class="column"
            :class="`${$slots.prepend ? 'col-8' : $slots.append ? 'col-6' : 'col-12'}`"
          >
            <div
              class="row inline col-12 q-col-gutter-x-md"
              style="row-gap: 16px"
            >
              <slot name="midTop"></slot>
              <div class="col-12">
                {{ addressTitle }}
              </div>
              <q-input
                dense
                outlined
                id="AddrL"
                label="ที่อยู่"
                class="col-12"
                v-model="address"
              />
              <q-select
                dense
                outlined
                emit-value
                map-options
                id="selectProvinceL"
                v-model="provinceId"
                option-value="id"
                option-label="name"
                label="จังหวัด"
                class="col-3"
                :options="addrOptions.provinceOps"
              />
              <q-select
                dense
                outlined
                emit-value
                map-options
                id="selectDistrictL"
                v-model="districtId"
                option-value="id"
                option-label="name"
                label="อำเภอ"
                class="col-3"
                :options="addrOptions.districtOps"
              />
              <q-select
                dense
                outlined
                emit-value
                map-options
                id="SelectSubDistrictEN"
                v-model="subDistrictId"
                option-value="id"
                option-label="name"
                label="ตำบล"
                class="col-3"
                :options="addrOptions.subDistrictOps"
              />
              <q-input
                dense
                readonly
                outlined
                id="zipL"
                label="รหัสไปรษณีย์"
                class="col-3"
                v-model="zipCode"
              />
              <span class="col-12">
                {{ addressENTitle }}
              </span>
              <q-input
                dense
                outlined
                id="addressEN"
                label="ที่อยู่"
                class="col-12"
                v-model="addressEN"
              />
              <q-select
                dense
                outlined
                emit-value
                map-options
                id="selectProvinceEN"
                v-model="provinceId"
                option-value="id"
                option-label="nameEN"
                label="จังหวัด"
                class="col-3"
                :options="addrOptions.provinceOps"
              />
              <q-select
                dense
                outlined
                emit-value
                map-options
                id="selectDistrictEN"
                v-model="districtId"
                option-value="id"
                option-label="nameEN"
                label="อำเภอ"
                class="col-3"
                :options="addrOptions.districtOps"
              />
              <q-select
                dense
                outlined
                emit-value
                map-options
                id="SelectSubDistrictEN"
                v-model="subDistrictId"
                option-value="id"
                option-label="nameEN"
                label="ตำบล"
                class="col-3"
                :options="addrOptions.subDistrictOps"
              />
              <q-input
                dense
                readonly
                outlined
                zip="zipEN"
                label="รหัสไปรษณีย์"
                class="col-3"
                v-model="zipCode"
              />
              <div class="col-12" v-if="$slots.midBottom">
                <q-separator size="1px" />
              </div>
              <slot name="midBottom"></slot>
            </div>
          </q-card-section>
          <!-- append -->
          <q-card-section
            class="column col-6"
            v-if="$slots.append && !$slots.prepend"
          >
            <slot name="append"></slot>
          </q-card-section>
        </div>

        <!-- footer -->
        <q-card-section class="form-footer">
          <div class="text-right">
            <q-btn
              dense
              unelevated
              id="submitBtn"
              type="submit"
              color="primary"
              class="q-px-sm"
              :label="$t('save')"
            />
          </div>
        </q-card-section>
      </q-form>
    </AppBox>
  </q-dialog>
</template>

<style scoped lang="scss">
.close-btn {
  color: hsl(var(--negative));
  background-color: hsla(var(--negative) / 0.1);

  &.dark {
    background-color: transparent;
    border: 1px solid hsl(var(--negative));
  }
}

.form-header {
  border-bottom: 1px solid var(--border-color);
}

.form-body-top {
  --_body-bg: var(--sand-0);
  background-color: var(--_body-bg);

  &.dark {
    --_body-bg: var(--gray-10);
  }
}

.form-footer {
  border-top: 1px solid var(--border-color);
}
</style>
