<template>
    <div class="pc-send-media-button">
        <BaseIconButton :icon="icon" :title="t('图片/视频')" :disabled="!sessionId" @click="triggerPick" />
        <input ref="inputRef" class="pc-native-input" type="file" accept="image/*,video/*" @change="handleChange" />
    </div>
</template>

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

const props = defineProps<{ sessionId: string }>();
const { t } = useI18n();
const icon = sendImgIcon;

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 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 resetInput = () => {
    if (inputRef.value) {
        inputRef.value.value = '';
    }
};

const triggerPick = () => {
    if (!props.sessionId || isPending.value) {
        return;
    }
    inputRef.value?.click();
};

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 handleChange = async (event: Event) => {
    const target = event.target as HTMLInputElement | null;
    const file = target?.files?.[0];
    if (!file || !props.sessionId) {
        resetInput();
        return;
    }

    try {
        isPending.value = true;
        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(t('发送视频失败'));
        } else {
            toast.error(t('发送图片失败'));
        }
    } finally {
        isPending.value = false;
        resetInput();
    }
};
</script>

<style scoped>
.pc-send-media-button {
    display: inline-flex;
}

.pc-native-input {
    display: none;
}
</style>
