<template>
  <div>
    <v-card class="mb-3" title="Information" prepend-icon="mdi-face-man-profile" :loading="loading">
      <template #text>
        <v-form class="mt-1" @submit.prevent="submit">
          <v-row dense>
            <v-col :xs="12" :md="6">
              <v-text-field readonly hide-details label="Username" density="comfortable" variant="outlined"
                            v-model="data.name" />
            </v-col>
            <v-col :xs="12" :md="6">
              <v-text-field hide-details label="Nickname" density="comfortable" variant="outlined"
                            v-model="data.nick" />
            </v-col>
            <v-col :cols="12">
              <v-textarea hide-details label="Description" density="comfortable" variant="outlined"
                          v-model="data.description" />
            </v-col>
            <v-col :xs="12" :md="6" :lg="4">
              <v-text-field hide-details label="First Name" density="comfortable" variant="outlined"
                            v-model="data.first_name" />
            </v-col>
            <v-col :xs="12" :md="6" :lg="4">
              <v-text-field hide-details label="Last Name" density="comfortable" variant="outlined"
                            v-model="data.last_name" />
            </v-col>
            <v-col :xs="12" :lg="4">
              <v-text-field hide-details label="Birthday" density="comfortable" variant="outlined" type="datetime-local"
                            v-model="data.birthday" />
            </v-col>
          </v-row>

          <v-btn type="submit" class="mt-2" variant="text" prepend-icon="mdi-content-save" :disabled="loading">
            Apply Changes
          </v-btn>
        </v-form>
      </template>
    </v-card>

    <v-card>
      <section v-if="canEditImage">
      <v-card-text class="flex items-center gap-3">
        <v-avatar
          color="grey-lighten-2"
          icon="mdi-account-circle"
          class="rounded-card"
          size="large"
          :image="accountPicture ?? ''"
        />
        <v-file-input
          clearable
          hide-details
          label="New Avatar"
          variant="outlined"
          density="comfortable"
          accept="image/*"
          prepend-icon=""
          @input="(val: InputEvent) => loadImage(val, 'avatar')"
        />
      </v-card-text>

      <v-img
        cover
        class="bg-grey-lighten-2"
        max-height="280px"
        :aspect-ratio="16 / 9"
        :src="accountBanner ?? ''"
      />

      <v-card-text>
        <v-file-input
          clearable
          hide-details
          label="New Banner"
          variant="outlined"
          density="comfortable"
          accept="image/*"
          prepend-icon=""
          @input="(val: InputEvent) => loadImage(val, 'banner')"
        />
      </v-card-text>
      </section>

      <v-card-text v-else>
        <v-alert variant="tonal" type="info" class="text-sm">
          Due to limitations of some browsers (such as Safari). You cannot edit your personal images in this browser.
          We recommend Chrome or any Chromium-based browser. You can also use a PWA for a better experience!
        </v-alert>
      </v-card-text>
    </v-card>

    <v-bottom-sheet class="max-w-[480px]" v-model="cropping">
      <v-card prepend-icon="mdi-crop" title="Crop the image" class="no-scrollbar">
        <div class="pt-3">
          <vue-cropper
            ref="cropper"
            class="w-ful"
            :src="image.url"
            :stencil-props="{ aspectRatio: image.ratio }"
          />
        </div>
        <v-card-actions class="pb-16">
          <v-spacer></v-spacer>

          <v-btn color="grey-darken-3" @click="cropping = false">Cancel</v-btn>
          <v-btn :disabled="loading" @click="applyImage">Apply</v-btn>
        </v-card-actions>
      </v-card>
    </v-bottom-sheet>
  </div>
</template>

<script setup lang="ts">
import { computed, onUnmounted, ref, watch } from "vue"
import { useUserinfo, getAtk } from "@/stores/userinfo"
import { buildRequestUrl, request } from "@/scripts/request"
import { useUI } from "@/stores/ui"
import { Cropper as VueCropper } from "vue-advanced-cropper"

const id = useUserinfo()

const { showSnackbar, showErrorSnackbar } = useUI()
const loading = ref(false)

const data = ref<any>({})
const image = ref<any>({
  url: null,
  type: null,
  ratio: 1
})

const cropper = ref<any>()
const cropping = ref(false)

const canEditImage = computed(() => navigator.userAgent.toLowerCase().indexOf("safari") > -1)

watch(
  id.userinfo,
  (val) => {
    if (val.isReady) {
      data.value.name = id.userinfo.data.name
      data.value.nick = id.userinfo.data.nick
      data.value.description = id.userinfo.data.description
      data.value.first_name = id.userinfo.data.profile.first_name
      data.value.last_name = id.userinfo.data.profile.last_name
      data.value.birthday = id.userinfo.data.profile.birthday

      if (data.value.birthday) data.value.birthday = data.value.birthday.substring(0, 16)
    }
  },
  { immediate: true, deep: true }
)

async function submit() {
  const payload = data.value
  if (payload.birthday) payload.birthday = new Date(payload.birthday).toISOString()

  loading.value = true
  const res = await request("identity", "/api/users/me", {
    method: "PUT",
    headers: { "Content-Type": "application/json", Authorization: `Bearer ${await getAtk()}` },
    body: JSON.stringify(payload)
  })
  if (res.status !== 200) {
    showErrorSnackbar(await res.text())
  } else {
    await id.readProfiles()
    showSnackbar("Your personal information has been updated.")
  }
  loading.value = false
}

function loadImage(event: InputEvent, type: string) {
  const { files } = event.target as HTMLInputElement
  if (!(files && files[0])) {
    return
  }

  if (image.value.url) URL.revokeObjectURL(image.value.url)
  const blob = URL.createObjectURL(files[0])
  const reader = new FileReader()
  reader.addEventListener("load", () => image.value.url = blob)
  reader.readAsArrayBuffer(files[0])

  if (type === "avatar") image.value.ratio = 1
  if (type === "banner") image.value.ratio = 16 / 9

  image.value.type = type
  cropping.value = true
}

const accountPicture = computed(() => id.userinfo.data?.avatar ?
  buildRequestUrl("identity", `/api/avatar/${id.userinfo.data?.avatar}`) :
  null
)
const accountBanner = computed(() => id.userinfo.data?.banner ?
  buildRequestUrl("identity", `/api/avatar/${id.userinfo.data?.banner}`) :
  null
)

onUnmounted(() => {
  if (image.value.url) URL.revokeObjectURL(image.value.url)
})

async function applyImage() {
  if (loading.value) return
  if (!image.value.url || !image.value.type) return

  const { canvas }: { canvas: HTMLCanvasElement } = cropper.value.getResult()

  const payload = new FormData()
  payload.set(image.value.type, await new Promise<Blob>((resolve, reject) => {
    canvas.toBlob((data: Blob | null) => {
      if (data == null) {
        showErrorSnackbar("Cannot get blob data through canvas, please try again in desktop browser.")
        reject("Cannot get blob data")
      } else {
        resolve(data)
      }
    })
  }))

  cropping.value = false

  loading.value = true
  const res = await request("identity", `/api/users/me/${image.value.type}`, {
    method: "PUT",
    headers: { Authorization: `Bearer ${await getAtk()}` },
    body: payload
  })
  if (res.status !== 200) {
    showErrorSnackbar(await res.text())
  } else {
    await id.readProfiles()
    showSnackbar("Your avatar has been updated.")
    image.value.url = null
  }
  loading.value = false
}
</script>

<style>
@import "vue-advanced-cropper/dist/style.css";
@import "vue-advanced-cropper/dist/theme.compact.css";

.rounded-card {
  border-radius: 8px;
}
</style>
