<template>
    <button class="input-tool-item" type="button" :disabled="isPending" @click="handleClick">
        <input ref="inputRef" class="input-tool-native-input" type="file" accept="image/*,video/*"
            @change="handleChange" />
        <img :src="sendImgIcon" class="input-tool-icon" :alt="t('相册')" />
        <span class="input-tool-label">{{ t('相册') }}</span>
    </button>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import AIDeskCoreInstance from '@tencentcloud/ai-desk-core';
import toast from '../../../../../../utils/toast';
import sendImgIcon from './sendImgIcon.svg';
import { parseUnknownError } from '../../../../../../utils/parseUnknownError';

const props = defineProps<{
    sessionId: string;
}>();

const emit = defineEmits<{
    (event: 'sent'): void;
}>();

const { t } = useI18n();
const inputRef = ref<HTMLInputElement | null>(null);
const isPending = ref(false);
const videoExtensions = ['mp4', 'mov', 'm4v', 'webm', 'ogg', 'ogv', 'avi', 'wmv', 'mkv'];
const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'heic', 'heif'];

const resetInputValue = () => {
    const input = inputRef.value;
    if (!input) {
        return;
    }

    input.value = '';
};

const getFileExtension = (fileName: string) => fileName.split('.').pop()?.toLowerCase() ?? '';

const isVideoFile = (file: File) => {
    if (file.type.startsWith('video/')) {
        return true;
    }

    return videoExtensions.includes(getFileExtension(file.name));
};

const isImageFile = (file: File) => {
    if (file.type.startsWith('image/')) {
        return true;
    }

    return imageExtensions.includes(getFileExtension(file.name));
};

const sendSelectedFile = async (file: File) => {
    const payload = {
        file,
    };

    if (isVideoFile(file)) {
        await AIDeskCoreInstance.chatService.sendVideoMessage({
            sessionId: props.sessionId,
            payload,
        });
        return;
    }

    if (isImageFile(file)) {
        await AIDeskCoreInstance.chatService.sendImageMessage({
            sessionId: props.sessionId,
            payload,
        });
        return;
    }

    throw new Error('unsupported-media-type');
};

const handleClick = () => {
    if (!props.sessionId || isPending.value) {
        return;
    }

    inputRef.value?.click();
};

const handleChange = async (event: Event) => {
    const input = event.target as HTMLInputElement | null;
    const file = input?.files?.[0];

    if (!file) {
        resetInputValue();
        return;
    }

    try {
        isPending.value = true;
        emit('sent');
        await sendSelectedFile(file);
    } catch (error) {
        console.error(error);
        if (error instanceof Error && error.message === 'unsupported-media-type') {
            toast.error(t('暂不支持发送该文件类型'));
        } else if (isVideoFile(file)) {
            toast.error(parseUnknownError(error))
        } else {
            toast.error(parseUnknownError(error))
        }
    } finally {
        isPending.value = false;
        resetInputValue();
    }
};
</script>

<style scoped>
.input-tool-item {
    position: relative;
    display: inline-flex;
    flex: 0 0 70px;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 70px;
    height: 70px;
    padding: 0;
    border: 1px solid #E6E9F0;
    border-radius: 12px;
    background: #fff;
    box-sizing: border-box;
}

.input-tool-item:disabled {
    opacity: 0.4;
}

.input-tool-native-input {
    display: none;
}

.input-tool-icon {
    display: block;
    width: 28px;
    height: 28px;
}

.input-tool-label {
    margin-top: 10px;
    color: #222;
    font-size: 12px;
    line-height: 16px;
    text-align: center;
    white-space: nowrap;
}
</style>