<template>
    <Teleport to="body">
        <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
            <div class="w-full max-w-md rounded-xl bg-white p-6 shadow-2xl">
                <h3 class="mb-4 text-lg font-bold text-neutral-900">
                    {{ $t('profile.cropAvatar') }}
                </h3>

                <div class="mx-auto mb-4 h-72 w-72">
                    <Cropper
                        ref="cropperRef"
                        :src="imageSrc"
                        :stencil-component="CircleStencil"
                        :stencil-props="{ aspectRatio: 1 }"
                        :canvas="{ width: 256, height: 256 }"
                        class="h-full w-full"
                    />
                </div>

                <div class="flex justify-end gap-3">
                    <MalioButton
                        variant="tertiary"
                        :label="$t('common.cancel')"
                        button-class="w-auto px-4"
                        @click="emit('cancel')"
                    />
                    <MalioButton
                        :label="$t('common.confirm')"
                        button-class="w-auto px-4"
                        :disabled="cropping"
                        @click="onConfirm"
                    />
                </div>
            </div>
        </div>
    </Teleport>
</template>

<script setup lang="ts">
import { Cropper, CircleStencil } from 'vue-advanced-cropper'
import 'vue-advanced-cropper/dist/style.css'

const props = defineProps<{
    imageFile: File
}>()

const emit = defineEmits<{
    (e: 'crop', blob: Blob): void
    (e: 'cancel'): void
}>()

const cropperRef = ref()
const cropping = ref(false)
const imageSrc = ref('')

onMounted(() => {
    imageSrc.value = URL.createObjectURL(props.imageFile)
})

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

async function onConfirm() {
    cropping.value = true

    try {
        const { canvas } = cropperRef.value.getResult()

        if (!canvas) return

        const blob = await new Promise<Blob | null>((resolve) => {
            canvas.toBlob(resolve, 'image/png')
        })

        if (blob) {
            emit('crop', blob)
        }
    } finally {
        cropping.value = false
    }
}
</script>
