<!-- eslint-disable @typescript-eslint/no-explicit-any -->
<template>
  <q-layout class="bg-grey-1">
    <q-header
      elevated
      class="text-white fixed-top absolute-top"
      style="background: #24292e"
      height-hint="61.59"
    >
      <q-toolbar class="q-py-sm q-px-md">
        <q-btn
          round
          dense
          flat
          :ripple="false"
          size="19px"
          color="white"
          class="q-mr-md"
          no-caps
          @click="gotoHome()"
        >
          <img src="/icons/logos/LACA_transparent2.png" style="width: 75px" />
        </q-btn>
        <q-input
          ref="search"
          :label="$t('header.searchBook')"
          color="black"
          dark
          dense
          standout
          v-model="text"
          style="width: 300px"
          @keydown.enter.prevent="goListSlot"
        />
        <div
          v-if="$q.screen.gt.sm"
          class="GL__toolbar-link gt-sm q-ml-xs q-gutter-md text-body2 text-weight-bold row items-center no-wrap"
        >
          <q-btn
            size="sm"
            flat
            class="text-white"
            @click="$router.push({ name: 'parking' })"
            :disable="getRoute == 'parking'"
            :label="$t('header.parking')"
          />
          <q-btn
            v-if="getUser"
            size="sm"
            flat
            class="text-white"
            @click="$router.push({ name: 'history' })"
            :disable="getRoute == 'history'"
            :label="$t('header.myparking')"
          />
          <q-btn
            size="sm"
            flat
            class="text-white"
            @click="$router.push({ name: 'about' })"
            :disable="getRoute == 'about'"
            :label="$t('header.aboutUs')"
          />
          <q-btn
            size="sm"
            flat
            class="text-white"
            @click="$router.push({ name: 'contact' })"
            :disable="getRoute == 'contact'"
            :label="$t('header.contactUs')"
          />
          <q-btn
            size="sm"
            flat
            class="text-white"
            @click="$router.push({ name: 'event' })"
            :disable="getRoute == 'event'"
            :label="$t('header.event')"
          />
        </div>

        <q-space />

        <div class="q-pl-sm q-gutter-sm row items-center no-wrap">
          <!-- <q-btn
            v-if="$q.screen.gt.xs"
            dense
            flat
            round
            size="sm"
            icon="notifications"
          /> -->
          <!-- <q-select
            v-model="locale"
            :options="localeOptions"
            label="Quasar Language"
            dense
            borderless
            emit-value
            map-options
            options-dense
            style="min-width: 150px"
          /> -->
          <q-btn round dense flat>
            <q-avatar size="26px">
              <img :src="locale == 'vi' ? 'vi.svg' : 'en.svg'">
            </q-avatar>
            <q-menu anchor="bottom left" self="top middle" >
              <q-list style="min-width: 150px">
                <q-item
                  clickable
                  @click="locale = 'vi'"
                  v-close-popup
                  v-ripple>
                  <q-item-section avatar>
                    <q-avatar size="26px">
                      <img src="vi.svg">
                    </q-avatar>
                  </q-item-section>

                  <q-item-section>Tiếng Việt</q-item-section>
                </q-item>

                <q-item
                  clickable
                  @click="locale = 'en-US'"
                  v-ripple
                  v-close-popup
                  >
                  <q-item-section avatar>
                    <q-avatar size="26px">
                      <img src="en.svg">
                    </q-avatar>
                  </q-item-section>

                  <q-item-section>English</q-item-section>
                </q-item>

              </q-list>
            </q-menu>
          </q-btn>
          <q-btn
            class="lt-md"
            size="sm"
            flat
            no-wrap
            icon="menu"
            @click="drawer = !drawer"
          />
          <q-btn
            dense
            size="sm"
            v-if="!getUser"
            style="min-width: 100px"
            flat
            no-wrap
            icon="fa-regular fa-user"
            @click="onLoginClick"
          >
            {{$t('header.login')}}
          </q-btn>

          <q-btn
            v-else
            dense
            size="sm"
            flat
            no-wrap
            round
            icon="fa-solid fa-user"
          >
            <q-menu transition-show="flip-right" transition-hide="flip-left">
              <q-list style="min-width: 150px">
                <q-item
                  clickable
                  v-close-popup
                  @click="$router.push({ name: 'register-parking' })"
                >
                  <q-item-section>{{$t('header.menu.addNewParking')}}</q-item-section>
                </q-item>

                <!-- <q-separator /> -->

                <!-- <q-item
                  clickable
                  v-close-popup
                  @click="$router.push({ name: 'history' })"
                >
                  <q-item-section>Lịch Sử Đặt Chỗ</q-item-section>
                </q-item> -->
                <q-separator />
                <q-item
                  @click="changPassword"
                  clickable
                  v-close-popup
                  v-if="getUser?.containsPassword"
                >
                  <q-item-section>{{$t('header.menu.changePassword')}}</q-item-section>
                </q-item>
                <q-separator />
                <q-item @click="signOut" clickable v-close-popup>
                  <q-item-section>{{$t('header.logout')}}</q-item-section>
                </q-item>
              </q-list>
            </q-menu>
          </q-btn>
        </div>
      </q-toolbar>
    </q-header>
    <q-drawer
      v-if="$q.screen.lt.md"
      v-model="drawer"
      bordered
      side="right"
      content-class="bg-grey-2"
    >
      <q-scroll-area class="fit">
        <q-list padding class="menu-list">
          <!-- <q-item
            clickable
            v-ripple
            :active="getRoute == 'map'"
            @click="
              $router.push({ name: 'map' });
              drawer = false;
            "
          >
            <q-item-section> Bản Đồ </q-item-section>
          </q-item> -->
          <q-item
            clickable
            v-ripple
            :active="getRoute == 'parking'"
            @click="
              $router.push({ name: 'parking' });
              drawer = false;
            "
          >
            <q-item-section> {{ $t('header.parking') }} </q-item-section>
          </q-item>
          <q-item
            v-if="getUser"
            clickable
            v-ripple
            :active="getRoute == 'history'"
            @click="
              $router.push({ name: 'history' });
              drawer = false;
            "
          >
            <q-item-section> {{ $t('header.myparking') }} </q-item-section>
          </q-item>

          <q-item
            clickable
            :active="getRoute == 'about'"
            v-ripple
            @click="
              $router.push({ name: 'about' });
              drawer = false;
            "
          >
            <q-item-section> {{ $t('header.aboutUs') }} </q-item-section>
          </q-item>

          <q-item
            clickable
            v-ripple
            :active="getRoute == 'contact'"
            @click="
              $router.push({ name: 'contact' });
              drawer = false;
            "
          >
            <q-item-section>{{ $t('header.contactUs') }}</q-item-section>
          </q-item>

          <q-item
            clickable
            v-ripple
            :active="getRoute == 'event'"
            @click="
              $router.push({ name: 'event' });
              drawer = false;
            "
          >
            <q-item-section>{{ $t('header.event') }}</q-item-section>
           </q-item>
        </q-list>
      </q-scroll-area>
    </q-drawer>
    <q-page-container>
      <router-view />
    </q-page-container>
  </q-layout>

  <q-dialog v-model="reserveDialog" position="top">
    <q-card style="width: 100%; max-width: 500px" class="bg-dark text-white">
      <q-card-section>
        <div class="text-h6">{{$t('dialog.bookingInfo')}}</div>
      </q-card-section>
      <q-card-section class="row items-center">
        <div class="col-12 q-py-xs">
          <q-input
            color="white"
            dark
            dense
            v-model="reserveData.name"
            :label="$t('dialog.ownerName')"
          />
        </div>
        <div class="col-12 q-py-xs">
          <q-input
            color="white"
            dark
            dense
            v-model="reserveData.licensePlates"
            :label="$t('dialog.licensePlates')"
          />
        </div>
        <div class="col-12 q-py-xs">
          <q-select
            color="white"
            dark
            dense
            :options="options"
            v-model="reserveData.carType"
            :label="$t('dialog.carType')"
          />
        </div>
        <div class="col-12 q-py-xs">
          <q-input
            color="white"
            dark
            dense
            v-model="reserveData.contact"
            :label="$t('dialog.contact')"
          />
        </div>
        <div class="col-12 q-py-xs row q-col-gutter-md">
          <q-input
            class="col-6"
            color="white"
            dark
            dense
            :label="$t('dialog.reserveData.start')"
            v-model="reserveData.start"
          >
            <template v-slot:prepend>
              <q-icon name="event" class="cursor-pointer">
                <q-popup-proxy
                  cover
                  transition-show="scale"
                  transition-hide="scale"
                >
                  <q-date v-model="reserveData.start" mask="YYYY-MM-DD HH:mm">
                    <div class="row items-center justify-end">
                      <q-btn v-close-popup label="Close" color="primary" flat />
                    </div>
                  </q-date>
                </q-popup-proxy>
              </q-icon>
            </template>

            <template v-slot:append>
              <q-icon name="access_time" class="cursor-pointer">
                <q-popup-proxy
                  cover
                  transition-show="scale"
                  transition-hide="scale"
                >
                  <q-time
                    v-model="reserveData.start"
                    mask="YYYY-MM-DD HH:mm"
                    format24h
                  >
                    <div class="row items-center justify-end">
                      <q-btn v-close-popup label="Close" color="primary" flat />
                    </div>
                  </q-time>
                </q-popup-proxy>
              </q-icon>
            </template>
          </q-input>
          <q-input
            class="col-6"
            color="white"
            dark
            dense
           :label="$t('dialog.reserveData.end')"
            v-model="reserveData.end"
          >
            <template v-slot:prepend>
              <q-icon name="event" class="cursor-pointer">
                <q-popup-proxy
                  cover
                  transition-show="scale"
                  transition-hide="scale"
                >
                  <q-date v-model="reserveData.end" mask="YYYY-MM-DD HH:mm">
                    <div class="row items-center justify-end">
                      <q-btn v-close-popup label="Close" color="primary" flat />
                    </div>
                  </q-date>
                </q-popup-proxy>
              </q-icon>
            </template>

            <template v-slot:append>
              <q-icon name="access_time" class="cursor-pointer">
                <q-popup-proxy
                  cover
                  transition-show="scale"
                  transition-hide="scale"
                >
                  <q-time
                    v-model="reserveData.end"
                    mask="YYYY-MM-DD HH:mm"
                    format24h
                  >
                    <div class="row items-center justify-end">
                      <q-btn v-close-popup label="Close" color="primary" flat />
                    </div>
                  </q-time>
                </q-popup-proxy>
              </q-icon>
            </template>
          </q-input>
        </div>
      </q-card-section>
      <q-card-actions align="right">
        <q-btn color="warning" @click="changeReserveDialog">{{ $t('dialog.cancel') }}</q-btn>
        <q-btn color="secondary" @click="bookingHandle">{{ $t('dialog.reservation') }}</q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>

  <!--  -->
  <q-dialog
    v-model="changePassDialog"
    v-if="getUser?.containsPassword"
    position="top"
    style="z-index: 9999"
  >
    <q-card style="width: 100%; max-width: 500px" class="bg-dark text-white">
      <q-card-section>
        <div class="text-h6">{{ $t('dialog.changePassword') }}</div>
      </q-card-section>
      <q-card-section class="row items-center">
        <div class="col-12 q-py-xs">
          <q-input
            color="white"
            dark
            dense
            v-model="changePassData.old_password"
            :label="$t('dialog.oldPassword')"
            :type="isOldPwd ? 'password' : 'text'"
            :rules="[
              (val) =>
                (val && val.length <= 32 && val.length >= 8) ||
                $t('dialog.ruleLenght'),
            ]"
          >
            <template v-slot:append>
              <q-icon
                :name="isOldPwd ? 'visibility_off' : 'visibility'"
                class="cursor-pointer"
                @click="isOldPwd = !isOldPwd"
              />
            </template>
          </q-input>
        </div>
        <div class="col-12 q-py-xs">
          <q-input
            color="white"
            dark
            dense
            v-model="changePassData.password"
            :label="$t('dialog.newPassword')"
            :type="isPwd ? 'password' : 'text'"
            :rules="[
              (val) =>
                (val && val.length <= 32 && val.length >= 8) ||
                $t('dialog.ruleLenght'),
            ]"
          >
            <template v-slot:append>
              <q-icon
                :name="isPwd ? 'visibility_off' : 'visibility'"
                class="cursor-pointer"
                @click="isPwd = !isPwd"
              />
            </template>
          </q-input>
        </div>
        <div class="col-12 q-py-xs">
          <q-input
            color="white"
            dark
            dense
            v-model="changePassData.password_confirmation"
            :label="$t('dialog.confirmPassword')"
            :type="isConfirmationPwd ? 'password' : 'text'"
            :rules="[
              (val) =>
                (val && val.length <= 32 && val.length >= 8) ||
                $t('dialog.ruleLenght'),
              (val) =>
                (val && val == changePassData.password) ||
                $t('dialog.ruleConfirmPass'),
            ]"
          >
            <template v-slot:append>
              <q-icon
                :name="isConfirmationPwd ? 'visibility_off' : 'visibility'"
                class="cursor-pointer"
                @click="isConfirmationPwd = !isConfirmationPwd"
              />
            </template>
          </q-input>
        </div>
      </q-card-section>
      <q-card-actions align="right">
        <q-btn color="warning" @click="changePassDialog = false">{{ $t('dialog.cancelUpdate') }}</q-btn>
        <q-btn color="secondary" @click="changPasswordHandle">{{ $t('dialog.ruleConficonfirmmPass') }}</q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { mapGetters, mapActions } from 'vuex';
import dayjs from 'dayjs';
import { useI18n } from 'vue-i18n'

// const { locale } = useI18n({ useScope: 'global' })


// import LanguageSelect from 'components/Lang/LanguageSelect.vue';
export default defineComponent({
  name: 'MainLayout',
  components: {
    // LanguageSelect,
  },
  data() {
    return {
      locale: useI18n({ useScope: 'global' }).locale,
      localeOptions: [
        { value: 'en-US', label: 'English' },
        { value: 'vi', label: 'Việt Nam ' }
      ],
      isOldPwd: true,
      isPwd: true,
      isConfirmationPwd: true,
      text: '',
      dialog: false,
      reserveDialog: false,
      changePassDialog: false,
      changePassData: {
        old_password: '',
        password: '',
        password_confirmation: '',
      },
      reserveData: {
        licensePlates: '',
        start: dayjs().format('YYYY-MM-DD HH:mm').toString(),
        end: '',
        name: '',
        id: null,
        contact: '',
        carType: '',
      },
      options: ['Car', 'Mortorbike', 'Orther'],
      loginInfo: {
        username: '',
        password: '',
      },
      drawer: false,
    };
  },
  computed: {
    ...mapGetters({
      getLoading: 'userModule/getLoading',
      getUser: 'userModule/getUser',
      getReserveDialog: 'slotModule/getReserveDialog',
      getCurrentId: 'slotModule/getCurrentId',
    }),
    getRoute() {
      return this.$route.name;
    },
    getStateReserveDialog() {
      return this.getReserveDialog;
    },
  },
  created() {
    if (!this.getUser && this.$route.name == 'map') {
      this.$router.push({ name: 'login' });
    }
  },
  watch: {
    getRoute() {
      if (!this.getUser && this.$route.name == 'map') {
        this.$router.push({ name: 'login' });
      }
    },
    getStateReserveDialog() {
      this.reserveDialog = this.getReserveDialog;
    },
  },
  methods: {
    ...mapActions({
      logout: 'userModule/logout',
      setUser: 'userModule/setUser',
      login: 'userModule/login',
      refreshToken: 'userModule/refreshToken',
      bookingSlot: 'slotModule/bookingSlot',
      changeReserveDialog: 'slotModule/changeReserveDialog',
      updatePassword: 'userModule/changePassword',
    }),
    gotoHome() {
      window.location.href = '/';
    },
    goListSlot() {
      this.$router.push({ name: 'parking', query: { name: this.text } });
    },
    onLoginClick() {
      // this.dialog = true;
      this.$router.push({ name: 'login' });
    },
    async loginHandle() {
      await this.login(this.loginInfo);
      this.dialog = false;
      this.$router.go(0);
    },
    async loginGG() {
      if (!this.getUser || !localStorage.getItem('refresh')) {
        const googleUser = await this.$gAuth.signIn();
        await this.setUser({
          google_token: googleUser.getAuthResponse().id_token,
        });
      } else {
        await this.refreshToken({
          refresh_token: localStorage.getItem('refresh'),
        });
      }
      this.dialog = false;
      this.$router.go(0);
    },
    async bookingHandle() {
      if (!this.getUser) {
        this.$q.notify({
          badgeClass: 'hide-badge',
          message: 'Vui lòng đăng nhập để đặt chỗ',
          color: 'negative',
          multiLine: true,
          position: 'top',
          html: true,
          classes: 'notify-error',
          timeout: 1000,
        });
        setTimeout(() => {
          this.$router.push({ name: 'login' });
        }, 2000);
        return;
      }
      this.reserveData.id = this.getCurrentId;
      const params = {
        owner: this.reserveData.name,
        licensePlates: this.reserveData.licensePlates,
        contact: this.reserveData.contact,
        slotId: this.reserveData.id,
        startAt: this.reserveData.start,
        endAt: this.reserveData.end,
        carType: this.reserveData.carType,
      };
      await this.bookingSlot(params);
      this.reserveDialog = false;
      this.reserveData.id = null;
    },
    signOut() {
      localStorage.removeItem('accesstoken');
      localStorage.removeItem('refresh');
      this.logout();
      this.$router.push({ name: 'dashboard' });
    },
    closeDialog() {
      if (!this.getUser && this.$route.name == 'map') {
        this.$router.push({ name: 'dashboard' });
      }
    },
    changPassword() {
      console.log('change password');
      this.changePassDialog = true;
    },
    async changPasswordHandle() {
      try {
        await this.updatePassword(this.changePassData);
        this.$q.notify({
          badgeClass: 'hide-badge',
          message: 'Đổi mật khẩu thành công',
          color: 'positive',
          multiLine: true,
          position: 'top',
          html: true,
          classes: 'notify-error',
          timeout: 1000,
        });
        this.changePassDialog = false;
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
      } catch (e: any) {
        this.$q.notify({
          badgeClass: 'hide-badge',
          message: this.$t(`${e.response.data.message}`),
          color: 'negative',
          multiLine: true,
          position: 'top',
          html: true,
          classes: 'notify-error',
          timeout: 1000,
        });
        console.log(e);
      }
    },
  },
});
</script>
<style lang="scss">
.q-menu {
  z-index: 9999 !important;
}

.disabled,
.disabled *,
[disabled],
[disabled] * {
  cursor: pointer !important;
}
</style>
