<script setup lang="ts">
import {
    ref,
    computed,
    onMounted,
    onBeforeUnmount,
    useTemplateRef,
    inject,
    defineEmits,
} from 'vue'
import { convertFileToBlob } from '@/helpers/convertFileToBlob.ts'
import { convertBlobToBase64 } from '@/helpers/convertBlobToBase64.ts'
import { resizeImage } from '@/helpers/resizeImage.ts'
import PluginDragAndDrop from "@plugin/components/PluginDragAndDrop.vue";
import PluginLoader from "@plugin/components/PluginLoader.vue";
import PluginSearchInput from "@plugin/components/PluginSearchInput.vue";
import axios from "axios";
import useSnackbar from "@plugin/composables/snackbar.ts";

type VariantType = 'area' | 'button-card' | 'button'

interface UploadResponse {
    id: string | null;
}

// Props
interface Props {
    enablePasteListener?: boolean
    disabled?: boolean
    variant?: VariantType
    buttonColor?: string
    maximumDimension?: number
    maximumSize?: number
    maximumUploadSize?: number
    format?: string
    quality?: number
    restrictionError?: string
    windowDropArea?: boolean
}

const props = withDefaults(defineProps<Props>(), {
    enablePasteListener: false,
    disabled: false,
    variant: 'area',
    buttonColor: 'default',
    maximumDimension: 2000,
    maximumSize: 10,
    maximumUploadSize: 1000,
    format: 'image/jpeg',
    quality: 0.85,
    windowDropArea: false,
})

const emit = defineEmits<{
    (e: 'upload', link: string): void
}>();

const { createNotification } = useSnackbar();


const acceptedFileExtensions = ref('.jpg, .jpeg, .png, .webp')
const additionalFileExtentions = ref('')
const minimumBase64FileChars = ref(512)
const minDimension = ref(100)
const isDragging = ref(false)
const isFileProcessing = ref(false)
const loading = ref(false)
const selectedFile = ref<File | null>(null)
const inputSearch = ref('')
const isTextSearch = ref(false)
const uploadImg = useTemplateRef<HTMLInputElement>('uploadImg')
const dragArea = useTemplateRef<HTMLDivElement>('dragArea')

const hostAddress = inject('hostAddress')
const utmMedium = inject('utmMedium')
const utmCampaign = inject('utmCampaign')

const disableTextSearch = computed(() => !inputSearch.value.trim())


const newTextSearch = (): void => {
    if (disableTextSearch.value) {
        createNotification({
            message: 'Please type in the text search prompt to proceed',
            type: 'warning',
        })

        return
    }

    isTextSearch.value = true


    window.open(`${hostAddress}/en/search-by-text?desc=${inputSearch.value}&type=relatedText&page=1?utm_source=referral&utm_medium=${utmMedium}&utm_campaign=${utmCampaign}`, '_blank')
}

const onDragEnter = (): void => {
    isDragging.value = true
}

const onDragLeave = (event: DragEvent): void => {
    isDragging.value = dragArea.value?.contains(event.relatedTarget as Node) ?? false
}

const onClick = (event: MouseEvent): void => {
    const inputFileEl = event.target as HTMLInputElement
    inputFileEl.value = ''
}

const onFileUpload = async (event: Event): Promise<void> => {
    const fileInput = event.target as HTMLInputElement
    selectedFile.value = extractFileFromFileList(fileInput.files as FileList)
    await processAndSendSelectedFile()
}

const onDropFile = async (event: DragEvent): Promise<void> => {
    isDragging.value = false
    const files = event.dataTransfer?.files
    if (files) {
        selectedFile.value = extractFileFromFileList(files)
        await processAndSendSelectedFile()
    }
}

const onPaste = async (event: ClipboardEvent): Promise<void> => {
    const clipboardData = event.clipboardData || window.Clipboard
    const files = clipboardData.files
    selectedFile.value = extractFileFromFileList(files)
    await processAndSendSelectedFile()
}

const extractFileFromFileList = (files: FileList): File | null => {
    if (files.length === 0) return null
    if (files.length > 1) {
        createNotification({
            message: 'You can only upload one file at a time',
            type: 'error',
        })
        return null
    }
    return files[0]
}

const processAndSendSelectedFile = async (): Promise<void> => {
    isTextSearch.value = false
    if (!selectedFile.value) return

    isFileProcessing.value = true
    const fileValidated = await validateFile(selectedFile.value)
    if (!fileValidated) {
        resetProcessedFile()
        return
    }
    const fileExtension = selectedFile.value.name.split('.').pop()?.toLowerCase() || ''
    if (additionalFileExtentions.value.includes(fileExtension)) {

        const formData = new FormData()
        formData.append('file', selectedFile.value)
        const headers = { 'Content-Type': 'multipart/form-data' }
        try {
            const response = await axios.post(`${hostAddress}/api/upload/process/file`, formData, { headers })
            const sentFileId = response.data.id
            emit('upload', `${hostAddress}/en/results/${sentFileId}?utm_source=referral&utm_medium=${utmMedium}&utm_campaign=${utmCampaign}`)
            isFileProcessing.value = false
        } catch (exception: any) {
            resetProcessedFile()
            if (exception?.response?.status === 430) {
                createNotification({
                    message: 'TOR Network is not supported',
                    type: 'error',
                })
            } else {
                createNotification({
                    message: 'Upload failed due to a server error. Please try again.',
                    type: 'error',
                })
            }
            isFileProcessing.value = false
        }
    } else {
        const base64File = await convertFileToBase64(selectedFile.value)
        if (!base64File) {
            resetProcessedFile()
            return
        }
        const sentFileId = await sendFileToServer(base64File)
        if (!sentFileId) {
            resetProcessedFile()
            return
        }
        isFileProcessing.value = false

        emit('upload', sentFileId)
    }
}

const validateFile = async (file: File): Promise<boolean> => {
    return validateFileExtension(file) && validateFileSize(file) && (await validateFileDimensions(file))
}

const validateFileDimensions = async (file: File): Promise<boolean> => {
    const fileExtension = file.name.split('.').pop()?.toLowerCase() || ''
    if (additionalFileExtentions.value.includes(fileExtension)) return true
    const img = new Image()
    const objectUrl = URL.createObjectURL(file)
    const dimensions = await new Promise<{ width: number; height: number }>((resolve, reject) => {
        img.onload = () => resolve({ width: img.width, height: img.height })
        img.onerror = reject
        img.src = objectUrl
    })
    const validDimensions = !(dimensions.width < minDimension.value || dimensions.height < minDimension.value)
    if (!validDimensions) {
        createNotification({
            message: `Image is too small (less than ${minDimension.value}px in one dimension) and can't be processed.`,
            type: 'error',
        })
        return false
    }
    return validDimensions
}

const validateFileSize = (file: File): boolean => {
    const sizeInMB = file.size / 1024 ** 2
    const validSize = sizeInMB < props.maximumSize
    if (!validSize) {
        createNotification({
            message: `File should be less than ${props.maximumSize}MB).`,
            type: 'error',
        })
    }
    return validSize
}

const validateFileExtension = (file: File): boolean => {
    const fileExtension = file.name.split('.').pop()
    let isValidFileExtenstion = false
    if (fileExtension) {
        const validExtentions = acceptedFileExtensions.value + additionalFileExtentions.value
        isValidFileExtenstion = validExtentions.includes(fileExtension.toLowerCase())
    }
    if (!isValidFileExtenstion) {
        createNotification({
            message: `File should be: JPG, JPEG, PNG, WEBP`,
            type: 'error',
        })
        return false
    }
    return true
}

const convertFileToBase64 = async (file: File): Promise<string | null> => {
    try {
        const blob = await convertFileToBlob(file)
        const resizedBlob = await resizeImage(blob, {
            maxWidth: props.maximumDimension,
            maxHeight: props.maximumDimension,
            maxSize: props.maximumUploadSize,
            type: props.format,
            quality: props.quality,
        })
        return await convertBlobToBase64(resizedBlob)
    } catch (error) {
        createNotification({
            message: 'Error while converting file',
            type: 'error',
        })
        return null
    }
}

const sendFileToServer = async (base64File: string): Promise<string | null> => {
    if (!validateBase64FileLength(base64File)) return null
    try {
        const response = await axios.post(`${hostAddress}/api/hugging-upload`, {
            image: base64File,
        })
        const data: UploadResponse = response.data
        return data.id
    } catch (err: any) {
        if (err.message === 'captcha_error') return null;

        if (err.response.status === 430) {
            createNotification({
                message: 'TOR Network is not supported',
                type: 'error',
            })
        } else if (err!.response.status === 429) {
            createNotification({
                message: 'Detected unusual activity.',
                type: 'error',
            });
        } else {
            createNotification({
                message: 'Server error occured',
                type: 'error',
            })
        }
        return null
    }
}

const validateBase64FileLength = (base64File: string): boolean => {
    if (base64File.length < minimumBase64FileChars.value) {
        createNotification({
            message: 'The image you have uploaded does not contain enough information to be processed',
            type: 'error',
        })

        return false
    }
    return true
}

const resetProcessedFile = (): void => {
    (<HTMLInputElement>uploadImg.value).value = ''
    isFileProcessing.value = false
    selectedFile.value = null
}

const cancel = (): void => {
    loading.value = false
}

const selectFile = (): void => {
    if (!props.disabled) {
        loading.value = true
        uploadImg.value?.click()
    }
}


onMounted(async () => {
    if (props.enablePasteListener) {
        window.addEventListener('paste', onPaste)
    }

})

onBeforeUnmount(() => {
    if (props.enablePasteListener) {
        window.removeEventListener('paste', onPaste)
    }
})
</script>

<template>
    <PluginDragAndDrop @upload-file="onDropFile" v-if="windowDropArea" />
    <div class="drag-section">
        <div v-if="variant === 'area'" class="drag-area">
            <div class="wrapper-card">
                <div v-if="restrictionError" class="wrapper">
                    <img
                        src="@/assets/img/wrong-format.webp"
                        alt="Error icon"
                    />
                    <div class="error-message">
                        <p>
                            {{ restrictionError }}
                        </p>
                        <p>
                            We appreciate your understanding.
                        </p>
                    </div>
                </div>
                <div
                    v-else
                    class="wrapper"
                    @click="selectFile"
                    :is-dragging="isDragging"
                    ref="dragArea"
                    @dragover.prevent
                    @dragleave="onDragLeave"
                    @dragenter.prevent="onDragEnter"
                    @drop.prevent="onDropFile"
                >
                    <div class="loader-wrapper" v-if="isFileProcessing">
                        <PluginLoader color="#D67419" :light-theme="true" />
                    </div>
                    <div class="drag-area-icon" v-else>
                        <svg class="app-svg-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path fill-rule="evenodd" clip-rule="evenodd" d="M19 1C19.5523 1 20 1.44772 20 2V4H22C22.5523 4 23 4.44772 23 5C23 5.55228 22.5523 6 22 6H20V8C20 8.55228 19.5523 9 19 9C18.4477 9 18 8.55228 18 8V6H16C15.4477 6 15 5.55228 15 5C15 4.44772 15.4477 4 16 4H18V2C18 1.44772 18.4477 1 19 1ZM7.7587 2H12.5C13.0523 2 13.5 2.44772 13.5 3C13.5 3.55228 13.0523 4 12.5 4H7.8C6.94342 4 6.36113 4.00078 5.91104 4.03755C5.47262 4.07337 5.24842 4.1383 5.09202 4.21799C4.7157 4.40973 4.40973 4.71569 4.21799 5.09202C4.1383 5.24842 4.07337 5.47262 4.03755 5.91104C4.00078 6.36113 4 6.94342 4 7.8V16.2C4 17.0566 4.00078 17.6389 4.03755 18.089C4.07337 18.5274 4.1383 18.7516 4.21799 18.908C4.39721 19.2597 4.6762 19.55 5.01918 19.743C5.10557 19.6076 5.19801 19.5052 5.25886 19.4393C5.41056 19.2752 5.61693 19.0876 5.83041 18.8936L14.3385 11.159C14.4994 11.0127 14.6586 10.8679 14.8043 10.7544C14.9663 10.6281 15.1671 10.4949 15.4236 10.4116C15.7843 10.2945 16.1708 10.2823 16.5381 10.3764C16.7994 10.4434 17.0082 10.5637 17.1778 10.6795C17.3304 10.7836 17.4984 10.918 17.6682 11.054L20.4878 13.3096C20.5095 13.327 20.5311 13.3443 20.5526 13.3614C20.8668 13.6123 21.1434 13.8331 21.3599 14.109C21.6295 14.4524 21.8208 14.8506 21.9206 15.2756C22.0007 15.617 22.0004 15.9709 22 16.3731C22 16.4005 22 16.4281 22 16.456V16.4913C22 16.6577 22 16.817 21.9995 16.9696C21.9998 16.9797 22 16.9898 22 17C22 17.0465 22 17.0924 22 17.1376C22.0005 17.933 22.0008 18.5236 21.8637 19.0353C21.7019 19.6392 21.4045 20.1853 21.0055 20.6395C20.8626 20.8022 20.7067 20.9531 20.5393 21.0907C20.1058 21.4469 19.5954 21.7136 19.0353 21.8637C18.5236 22.0008 17.933 22.0005 17.1376 22C17.0924 22 17.0465 22 17 22H16.552C16.5319 22 16.5116 22 16.4913 22H7.75868C7.73455 22 7.71056 22 7.68669 22L7.03139 22C6.77557 22 6.52731 22.0001 6.31909 21.9865C6.11522 21.98 5.92511 21.9703 5.74817 21.9558C5.18608 21.9099 4.66937 21.8113 4.18404 21.564C3.43139 21.1805 2.81947 20.5686 2.43598 19.816C2.18868 19.3306 2.09012 18.8139 2.04419 18.2518C1.99998 17.7106 1.99999 17.0463 2 16.2413V7.7587C1.99999 6.95373 1.99998 6.28937 2.04419 5.74817C2.09012 5.18608 2.18868 4.66937 2.43597 4.18404C2.81947 3.43139 3.43139 2.81947 4.18404 2.43597C4.66937 2.18868 5.18608 2.09012 5.74817 2.04419C6.28937 1.99998 6.95373 1.99999 7.7587 2ZM19.59 19.2132C19.6895 19.0829 19.7733 18.9398 19.8388 18.7866C19.8974 18.6496 19.9457 18.4536 19.9722 18.0757C19.9994 17.6884 20 17.1897 20 16.456C20 15.9243 19.9938 15.819 19.9735 15.7327C19.9403 15.591 19.8765 15.4583 19.7866 15.3438C19.7319 15.2741 19.6535 15.2035 19.2384 14.8713L16.4411 12.6335C16.2401 12.4727 16.1323 12.3873 16.0502 12.3313C16.0473 12.3293 16.0445 12.3274 16.0418 12.3256C16.0393 12.3276 16.0366 12.3296 16.0338 12.3318C15.9554 12.3929 15.8532 12.4849 15.6627 12.6581L7.58665 20C7.65583 20 7.72692 20 7.8 20H16.456C17.1897 20 17.6884 19.9994 18.0757 19.9722C18.4536 19.9457 18.6496 19.8974 18.7866 19.8388C18.9423 19.7722 19.0876 19.6867 19.2196 19.5851C19.3589 19.478 19.4834 19.3529 19.59 19.2132ZM8.5 7.5C7.94772 7.5 7.5 7.94772 7.5 8.5C7.5 9.05228 7.94772 9.5 8.5 9.5C9.05229 9.5 9.5 9.05228 9.5 8.5C9.5 7.94772 9.05229 7.5 8.5 7.5ZM5.5 8.5C5.5 6.84315 6.84315 5.5 8.5 5.5C10.1569 5.5 11.5 6.84315 11.5 8.5C11.5 10.1569 10.1569 11.5 8.5 11.5C6.84315 11.5 5.5 10.1569 5.5 8.5Z" fill="currentColor"/>
                        </svg>
                    </div>
                    <div class="drag-area-title">
                        <p>
                            <span>Upload</span> an image
                        </p>
                    </div>
                    <p class="drag-area-desc">
                        JPG, PNG, WEBP formats, max file size 10MB, min dimensions 200x200px
                    </p>
                </div>
            </div>
            <div class="search-input-container" v-if="!restrictionError">
                <PluginSearchInput
                    @on-submit="newTextSearch"
                    v-model="inputSearch"
                />
            </div>
        </div>
        <template v-else>
            <div v-if="!restrictionError" class="variant" @click="selectFile">
                <slot :loading="loading"></slot>
            </div>
        </template>
        <input
            class="upload-input"
            type="file"
            ref="uploadImg"
            :disabled="disabled"
            @accept="acceptedFileExtensions"
            @cancel="cancel"
            @click="onClick"
            @change="onFileUpload"
        />
    </div>
</template>

<style scoped lang="scss">
@import "@/assets/variables";
@import "@/assets/mixins";
@import '@plugin/assets/main.scss';
@import '@plugin/assets/_variables_override.scss';

.drag-section {
    .drag-area {
        background-color: $main-00;
        width: 100%;
        height: 100%;
        padding: 20px;
        display: flex;
        flex-direction: column;

        .wrapper-card {
            padding: 8px;
            border-radius: 8.782px;
            background: #FFF;
            box-shadow: 0px 1.464px 5.855px 0px rgba(89, 99, 168, 0.16);
        }

        .wrapper  >img {
            height: 120px;
            width: 120px;
        }

        &[is-dragging="true"] > .wrapper {
            border-color: $primary-400;
        }
    }

    > .upload-input {
        display: none;

        &:disabled {
            pointer-events: none;
        }
    }
}

.wrapper {
    background-color: $complementary-50;
    border-radius: 3px;
    padding: 16px 23px;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    transition: all 0.35s ease;
    border: 2px dashed $complementary-700;

    &:hover {
        cursor: pointer;
        border-color: $complementary-900;
    }

    .drag-area-icon {
        border-radius: 4px;
        border: 2px dashed $complementary-900;
        color: $complementary-900;
        padding: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .drag-area-title {
        margin-top: 20px;
        max-width: 200px;

        > p {
            @include semibold-16-24;
            color: $main-900;
            line-height: 20px;

            :deep(span) {
                color: $complementary-900;
            }
        }
    }

    .drag-area-desc {
        @include medium-14-20;
        color: $main-700;
        margin-top: 20px;
    }
}

.search-input-container {
    margin-top: 12px;

    @media (min-width: $mobile-768-breakpoint) {
        margin-top: 20px;
    }
}

.drag-section {
    .drag-area {
        background-color: $main-00;
        width: 100%;
        height: 100%;
        padding: 20px;

        .wrapper {

            .icon-area {
                filter: drop-shadow(0 0 60px $main-00);

                svg {
                    width: 120px;
                    height: 120px;
                }
            }

            > .error-message {
                @include medium-14-20;
                color: $main-900;
                margin-bottom: 20px;

                > p {
                    margin-top: 20px;
                    margin-bottom: 20px;
                }
            }

            > button {
                @include primary-simple;
                width: fit-content;
            }

        }
    }
}


</style>
