<script setup lang="ts">
import "moment/dist/locale/th";
import moment from "moment";
import DialogStatus from "@/modules/00_support/components/DialogStatus.vue";
import { ref, onMounted } from "vue";
import { storeToRefs } from "pinia";
import { useSupportStore } from "@/modules/00_support/store/Main";
import type { QInfiniteScroll, QInfiniteScrollProps } from "quasar";

const store = useSupportStore();
const content = ref<string>("");
const searchInput = ref<string>("");
const currentIssuePage = ref<number>(1);
const totalPageIssue = ref<number>();
const { scrollContainer } = storeToRefs(store);

onMounted(async () => {
  await store.fetchIssue();
  totalPageIssue.value = Math.ceil((store.currentTotalIssue || 0) / 6);
});

const onLoad = (async (_: any, done: any) => {
  const totalPages = Math.ceil((store.currentTotalMessage || 1) / 30);
  if (store.currentPage && totalPages > store.currentPage) {
    await store.loadMessage(store.currentPage + 1);
    done();
  }
}) satisfies QInfiniteScrollProps["onLoad"];
</script>

<template>
  <div class="flex q-mt-md">
    <p class="text-h6 text-weight-medium align-center">ถาม - ตอบ</p>
    <q-space />
    <p>
      <q-btn dense size="16px" flat text-color="teal">
        <router-link to="/support/category"> จัดการประเภทของปัญหา </router-link>
      </q-btn>
    </p>
  </div>

  <div class="container">
    <div class="i1 bg-white align-center">
      <q-toolbar>
        <q-item-section>
          <q-input
            dense
            rounded
            outlined
            label="ค้นหาข้อความ..."
            v-model="searchInput"
          >
            <template v-slot:prepend>
              <q-icon name="search" />
            </template>
          </q-input>
        </q-item-section>
      </q-toolbar>
    </div>

    <div class="i2 bg-white align-center">
      <q-toolbar>
        <q-avatar>
          <img src="https://cdn.quasar.dev/img/avatar3.jpg" />
        </q-avatar>
        <q-item-section v-if="store.currentIssue" class="q-pl-sm">
          <q-item-label
            >{{ store.currentTitle }}
            <q-badge color="blue">
              {{ store.currentCategory }}
            </q-badge></q-item-label
          >
        </q-item-section>

        <q-space />

        <div v-if="store.currentIssue">
          <q-badge
            color="white"
            text-color="black"
            :label="
              store.correntStatusIssue == 'new'
                ? 'ปัญหาใหม่'
                : store.correntStatusIssue == 'ongoing'
                ? 'กำลังดำเนินการ'
                : 'เสร็จสิ้น'
            "
          />
          <dialog-status />
        </div>

        <!-- <q-btn-dropdown
          v-if="store.currentIssue"
          :label="
            store.correntStatusIssue == 'new'
              ? 'ปัญหาใหม่'
              : store.correntStatusIssue == 'ongoing'
              ? 'กำลังดำเนินการ'
              : 'เสร็จสิ้น'
          "
          dense
          flat
          color="positive"
          @click.stop
        >
          
          <q-list v-for="itemStatusIssue in statusIssue">
            <q-item
              clickable
              v-close-popup
              @click="
                () => {
                  store.ChangeStatusIssue(
                    store.currentIssue,
                    store.currentTitle,
                    store.currentCategoryId,
                    itemStatusIssue
                  );
                }
              "
            >
              <q-item-section>
                <q-item-label>{{
                  itemStatusIssue == "new"
                    ? "ปัญหาใหม่"
                    : itemStatusIssue == "ongoing"
                    ? "กำลังดำเนินการ"
                    : "เสร็จสิ้น"
                }}</q-item-label>
              </q-item-section>
            </q-item>
          </q-list>
        </q-btn-dropdown> -->

        <q-btn flat round dense icon="o_info" text-color="grey" />
      </q-toolbar>
    </div>

    <div class="i3 bg-white">
      <div v-for="(item, index) in store.issue?.result" :key="index">
        <div
          @click="
            async () => {
              store.currentIssue = item.id;
              store.currentTitle = item.title;
              store.correntStatusIssue = item.status;
              store.currentCategory = item.category.name;
              store.issue
                ? (store.issue.result = store.issue.result.map((v) => {
                    if (v.id === item.id) {
                      v.unreadCount = 0;
                    }
                    return v;
                  }))
                : '';
              await store.fetchMessageStatus(item.id);
              await store.fetchMessage(item.id);
            }
          "
          :class="{ active: store.currentIssue === item.id }"
          class="noactive row q-py-sm justify-between items-center q-px-md"
        >
          <div class="col-10 row items-center">
            <div class="noactive-avatar">
              <q-avatar color="grey-2" text-color="white" size="40px">
                <img src="https://cdn.quasar.dev/img/avatar1.jpg" />
              </q-avatar>
            </div>
            <div class="col column q-ml-md">
              <span class="text-long col text-weight-bold line-ellipsis">
                {{ item.title }}
              </span>

              <span
                class="col text-caption line-ellipsis"
                :class="{
                  'text-weight-bold': item.unreadCount > 0,
                  'text-grey-8': item.unreadCount > 0,
                  'text-grey': item.unreadCount === 0,
                }"
                >{{ item.lastMessage }}</span
              >
            </div>
            <div></div>
          </div>

          <div class="col-2 items-center text-right">
            <q-icon
              v-if="item.lastMessage?.length === 0"
              name="mdi-send"
              size="xs"
              color="primary"
            />

            <div v-else class="column">
              <span class="col text-caption text-grey">20 s</span>

              <div class="col">
                <q-badge
                  v-if="item.unreadCount > 0"
                  rounded
                  color="negative"
                  text-color="white"
                  :label="item.unreadCount"
                />
                <q-icon v-else name="mdi-check-all" size="xs" color="grey" />
              </div>
            </div>
          </div>
        </div>

        <q-separator inset />
      </div>
    </div>

    <div class="i4 bg-grey-3" v-if="store.currentIssue">
      <q-scroll-area
        ref="scrollContainer"
        style="width: 100%; height: 100%"
        v-if="store.message?.result.message.length || 0 > 0"
      >
        <q-infinite-scroll @load="onLoad" :offset="250" reverse>
          <div
            v-for="(item, index) in store.message?.result.message"
            :key="index"
            class="caption"
          >
            <q-item-section class="q-pr-md">
              <q-item-label>
                <q-chat-message
                  :key="index"
                  :id="item.id"
                  avatar="https://cdn.quasar.dev/img/avatar4.jpg"
                  :text="[item.content]"
                  :bg-color="
                    item.fromUserId === store.userId ? 'primary' : 'white'
                  "
                  :text-color="
                    item.fromUserId === store.userId ? 'white' : 'black'
                  "
                  :sent="item.fromUserId === store.userId"
                  :stamp="moment(item.createdAt).fromNow()"
                />
              </q-item-label>

              <q-item-label
                v-if="item.fromUserId === store.userId"
                class="flex"
                caption
              >
                <q-space />
                <div
                  v-if="
                    store.messageStatus?.result.some(
                      (v) =>
                        new Date(v.lastAccessDate).getTime() >=
                          new Date(item.createdAt).getTime() &&
                        index + 1 === store.message?.result.message.length
                    )
                  "
                >
                  อ่านเเล้ว
                </div>
              </q-item-label>
            </q-item-section>
          </div>
          <template v-slot:loading>
            <div class="row justify-center q-my-md">
              <q-spinner-dots color="primary" size="40px" />
            </div>
          </template>
        </q-infinite-scroll>
      </q-scroll-area>
    </div>

    <div class="grid-manage bg-white align-center">
      <q-pagination
        v-model="currentIssuePage"
        :max="totalPageIssue || 1"
        :max-pages="6"
        boundary-numbers
        @update:model-value="
          (value) => {
            store.fetchIssue(value);
          }
        "
      />
    </div>

    <div class="i5 bg-white container-input align-center">
      <!-- <div class="input-file">
        <q-btn flat>
          <q-icon name="attach_file" style="transform: rotate(-125deg)" />
        </q-btn>
      </div> -->
      <div class="input-chat">
        <q-input
          @keydown.enter.prevent="
            () => {
              if (store.currentIssue) {
                store.sendMessage(content, store.currentIssue);
                content = '';
              }
            }
          "
          outlined
          dense
          placeholder="Aa"
          v-model="content"
          id="message"
        >
        </q-input>
      </div>
      <div class="btn-chat">
        <q-btn
          @click="
            () => {
              if (store.currentIssue) {
                store.sendMessage(content, store.currentIssue);
                content = '';
              }
            }
          "
          flat
          class="col-2"
          style="color: #009789"
          label="ส่งข้อความ"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.text-long {
  width: 100px;
  display: inline-block;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.active {
  background: #ebf9f7;
  border-left: 5px solid #03a898;
  & {
    .noactive-avatar {
      border-radius: 50%;
      border: 1px solid #03a898;
    }
  }
}

.align-center {
  display: flex;
  align-items: center;
  justify-content: center;
}
.container {
  display: grid;
  grid-template-areas:
    "search toolbar"
    "menu chat"
    "manage input";
  grid-template-rows: 60px 400px 60px;
  grid-template-columns: 400px 1fr;
}

.container-input {
  display: grid;
  grid-template-areas: "input-chat btn";
  /* grid-template-areas: "file input-chat btn"; */
  grid-template-rows: 1fr;
  /* grid-template-columns: 60px 1fr 100px; */
  grid-template-columns: 1fr 100px;
}

.input-file {
  grid-area: file;
}

.input-chat {
  grid-area: input-chat;
}

.btn-chat {
  grid-area: btn;
}

.i1 {
  grid-area: search;
}

.i2 {
  grid-area: toolbar;
}
.i3 {
  grid-area: menu;
}
.i4 {
  grid-area: chat;
}
.i5 {
  grid-area: input;
}

.grid-manage {
  grid-area: manage;
}
.container-1 {
  display: grid;
  /* grid-template-columns: 1fr 2fr; */
  grid: 50px 450px / 1fr 2fr;
}

.container-2 {
  display: grid;
  /* grid-template-columns: 1fr 2fr; */
  grid: 50px 450px / 1fr 2fr;
}
</style>
