<template>
  <div class="container is-fullwidth">
    <div class="loading" v-if="loading">
      <Loading />
    </div>
    <div class v-else>
      <!-- Add Child Modal -->
      <AddChildModal
        :isActive="showAddChildModal"
        @onFail="onCreateChildFailed($event)"
        @onCreated="onChildCreated($event)"
        @onClose="showAddChildModal=false"
      />
      <!-- Change Avatar Modal -->
      <ChangeAvatarModal
        @onAvatarSelected="updateAvatar($event)"
        @onClose="showChangeAvatarModal=false"
        :isActive="showChangeAvatarModal"
        :defaultImage="user.avatar"
      />
      <!-- Profile Cover Modal -->
      <Modal
        title="Change Cover"
        :isActive="showCoverModal"
        acceptText="Change"
        rejectText="Cancel"
        @accept="changeCover()"
        @close="showCoverModal=false"
      >
        <ProfileHeader
          :title="user.name"
          :background="childCoverModalImage ? childCoverModalImage : user.profile_cover"
        />
        <file-select v-model="childCoverModalImage" accept="image/*" lable="Select Cover:"></file-select>
      </Modal>

      <!-- Create Call Modal -->
      <ConfigureNewCallModal
        @newCall="makeCall($event)"
        @dismiss="showCreateCallModal=false"
        :isActive="showCreateCallModal"
      />
      <!-- Profile -->
      <ProfileHeader :title="user.name" :background="user.profile_cover" />
      <div class="columns is-fullheight m-t-md">
        <div class="column is-2">
          <div class="card">
            <div class="card-image p-md is-relative">
              <figure
                class="image is-1by1 editable-image is-light"
                @click="showChangeAvatarModal=true"
              >
                <img :src="user.avatar" class="is-rounded is-avatar" />
              </figure>
            </div>
            <div class="card-content">
              <div v-if="!![...user.connections.children, ...user.connections.connections].length">
                <p class="card-header-title">Connections</p>
                <ChildCard
                  v-for="child in [...user.connections.children, ...user.connections.connections]"
                  :key="child.id"
                  :child="child"
                ></ChildCard>
                <br />
              </div>
              <div v-else>
                <p class="card-header-title">No Connections yet...</p>
              </div>
            </div>
          </div>
        </div>
        <div class="column">
          <div class="card">
            <div class="card-content">
              <nav class="level">
                <!-- Left side -->
                <div class="level-left">
                  <div class="level-item">
                    <h1 class="title">{{`${user.name.split(' ')[0]}'s Room`}}</h1>
                  </div>
                </div>

                <!-- Right side -->
                <div class="level-right">
                  <div class="level-item">
                    <!-- Dropdown -->
                    <div :class="`dropdown ${addMenuOpen ? 'is-active' : ''}`">
                      <div class="dropdown-trigger">
                        <button
                          class="button"
                          aria-haspopup="true"
                          aria-controls="dropdown-menu"
                          @click="addMenuOpen=!addMenuOpen"
                        >
                          <span>Add</span>
                          <span class="icon is-small">
                            <i
                              :class="`fa fa-angle-${addMenuOpen ? 'up' : 'down'}`"
                              aria-hidden="true"
                            ></i>
                          </span>
                        </button>
                      </div>
                      <div class="dropdown-menu" id="dropdown-menu" role="menu">
                        <div class="dropdown-content">
                          <a class="dropdown-item" @click="onAddClicked('book')">
                            <i class="fa fa-fw fa-book"></i> Add a book
                          </a>
                          <a class="dropdown-item" @click="onAddClicked('slideshow')">
                            <i class="fa fa-fw fa-photo"></i> New slideshow
                          </a>
                          <a class="dropdown-item" @click="onAddClicked('puzzle')">
                            <i class="fa fa-fw fa-puzzle-piece"></i> Create a puzzle
                          </a>
                          <hr class="dropdown-divider" />
                          <a class="dropdown-item" @click="onAddClicked('child')">
                            <i class="fa fa-fw fa-child"></i> Add a child
                          </a>
                        </div>
                      </div>
                    </div>
                    <!-- End Dropdown -->
                    <!-- <button class="button" @click="onAddClicked()">
                      <i class="fa fa-fw fa-plus"></i> Add
                    </button>-->
                    <button
                      class="button is-success m-l-md"
                      @click="showCreateCallModal=true"
                      :disabled="!user.connections.children.length"
                      :title="user.connections.children.length ? 'Start a new call' : 'Only a parent of a child can start a call'"
                    >
                      <i class="fa fa-fw fa-phone"></i> Call
                    </button>
                  </div>
                </div>
              </nav>
              <div class="Books">
                <h2 class="subtitle">
                  <i class="fa fa-fw fa-book"></i> My Books
                </h2>
                <div class="is-flex m-b-md is-justify-centered has-wrap">
                  <div
                    class="book-thumb enabled m-l-md"
                    v-for="book in user.books"
                    :key="book.id"
                    @click="goToBook(book)"
                  >
                    <div class="book-cover">
                      <figure class="image is-2by3 m-a">
                        <img :src="`/u/books/${book.id}/thumbnail`" />
                      </figure>
                    </div>
                    <div class="book-text">
                      <div>{{book.title}}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { mapActions, mapGetters } from "vuex";
import ChildCard from "../components/Child_Card.vue";
import Services from "../../services/index";
import Loading from "../../shared/components/Loading/Loading.vue";
import ProfileHeader from "../components/ProfileHeader.vue";
import AddChildModal from "../components/AddChildModal.vue";
import AddConnectionModal from "../components/AddConnectionModal.vue";
import ConfigureNewCallModal from "../components/ConfigureNewCallModal.vue";
import FileSelect from "../../shared/components/FileSelect/FileSelect.vue";
import AvatarBadge from "../components/AvatarBadge.vue";
import Moment from "moment";
import Modal from "../../shared/components/Modal/Modal.vue";
import ChangeAvatarModal from "../components/ChangeAvatarModal.vue";
export default {
  name: "Home",
  components: {
    Loading,
    ProfileHeader,
    Modal,
    FileSelect,
    AvatarBadge,
    AddConnectionModal,
    ConfigureNewCallModal,
    ChildCard,
    AddChildModal,
    ChangeAvatarModal
  },
  beforeCreate() {},
  async created() {
    this.loading = false;
    return true;
  },
  data() {
    return {
      loading: true,
      child: null,
      isParent: false,
      inEditMode: false,
      showCoverModal: false,
      showCreateCallModal: false,
      showAddChildModal: false,
      showAddConnectionModal: false,
      childCoverModalImage: null,
      addMenuOpen: false,
      showChangeAvatarModal: false
    };
  },
  methods: {
    async updateAvatar(event) {
      if (!event.isDefaultImage) {
        try {
          const response = await Services.ApiService.updateUser({
            avatar: event.image
          });
          if (response.code === 0) {
            await this.getUser();
            this.notify({ message: "Updated Successfully!", level: "success" });
          }
        } catch (e) {
          console.error(e);
        }
      }
      this.showChangeAvatarModal = false;
      return true;
    },
    onAddClicked(action: "book" | "slideshow" | "puzzle" | "child") {
      switch (action) {
        case "child":
          this.showAddChildModal = true;
          break;
        case "book":
          this.$router.push({ path: `/create/${action}` });
          break;
        default:
          this.notify({
            message: `Add ${action} button clicked. Still not working`
          });
      }
      this.addMenuOpen = false;
    },
    onDeleteClicked() {
      this.notify({ message: "Delete button clicked. Still not working" });
    },
    goChildProfile(connection) {
      this.$router.push({ path: `/child/${connection.id}` });
    },
    goToBook(book) {
      this.$router.push({ path: `/book/${book.id}` });
    },
    async onChildCreated(child) {
      this.loading = true;
      await this.getUser();
      this.loading = false;
      this.showAddChildModal = false;
      this.notify({
        message: `Woohoo! ${child.name} created!`,
        level: "success"
      });
      this.goChildProfile(child);
    },
    onCreateChildFailed(msg) {
      this.notify({ message: `ERROR: ${msg}`, level: "danger" });
      this.showAddChildModal = false;
    },
    async makeCall(event) {
      try {
        const response = await Services.ApiService.createCall(event);
        this.notify({ message: `Connecting...` });
        this.$router.push({ path: `/call/${response.data.id}` });
      } catch (e) {
        console.error(e);
      }
      return true;
    },
    async changeCover() {
      if (this.childCoverModalImage) {
        this.loading = true;
        try {
          this.child.profile_cover = await Services.ApiService.updateChild(
            this.child.id,
            { profile_cover: this.childCoverModalImage }
          );
        } catch (error) {
          console.error(error);
        }
        this.loading = false;
      }
      this.showCoverModal = false;
      this.this.childCoverModalImage = null;
    },
    togleEditMode() {
      this.inEditMode = !this.inEditMode;
      if (this.inEditMode) {
        this.showCoverModal = true;
      }
    },
    ...mapActions(["getUser", "notify"])
  },
  computed: {
    age() {
      const years = Moment().diff(this.child.dob, "years");
      const months = Moment().diff(this.child.dob, "months") % 12;
      const isNewBorn = !years && !months;
      let text = "a new boarn!";
      if (!isNewBorn) {
        text = "";
        if (years) text += `${years} years`;
        if (years && months) text += ` and`;
        if (months) text += ` ${months} months`;
        text += " old";
      }
      return `${text}`;
    },
    ...mapGetters(["user"])
  }
};
</script>

