<script setup>
import { mediaService } from "@/api/mediaService";
import { formatDate } from "@/utils/date";
import { formatFileSize } from "@/utils/filesize";
import { getFileIcon, getFileTypeByMimeCN } from "@/utils/filetype";
import { InputText } from "primevue";
import Badge from "primevue/badge";
import Button from "primevue/button";
import Column from "primevue/column";
import ConfirmDialog from 'primevue/confirmdialog';
import DataTable from "primevue/datatable";
import Dialog from 'primevue/dialog';
import Dropdown from "primevue/dropdown";
import ProgressSpinner from "primevue/progressspinner";
import Toast from "primevue/toast";
import { useConfirm } from "primevue/useconfirm";
import { useToast } from "primevue/usetoast";
import { computed, h, onMounted, ref } from "vue";
import { useRouter } from "vue-router";

import {
    BsFileEarmark,
    BsFileExcel,
    BsFileImage,
    BsFileMusic,
    BsFilePdf,
    BsFilePlayFill,
    BsFilePpt,
    BsFileText,
    BsFileWord,
    BsFileZip
} from 'vue-icons-plus/bs';

// Import useConfirm dynamically to avoid the error when the service is not provided
const confirm = useConfirm();
const toast = useToast();

const router = useRouter();

// Remove upload related refs and methods
const openUploadDialog = () => {
    router.push("/medias/uploads");
};
const globalFilterValue = ref("");
const loading = ref(false);
const filters = ref({
    global: { value: null, matchMode: "contains" },
});

// Add pagination state
const first = ref(0);
const rows = ref(10);
const totalRecords = ref(0);
const currentPage = ref(1);

// Add computed for total pages
const totalPages = computed(() => {
    return Math.ceil(totalRecords.value / rows.value);
});

// Sample data - in a real app, this would come from an API
const mediaFiles = ref([]);

// Fetch media data
const fetchMediaFiles = async () => {
    loading.value = true;
    try {
        const response = await mediaService.getMedias({
            page: currentPage.value,
            limit: rows.value,
        });
        mediaFiles.value = response.data.items;
        totalRecords.value = response.data.total;
        console.log(totalRecords.value);
    } catch (error) {
        toast.add({
            severity: "error",
            summary: "错误",
            detail: "加载媒体文件失败",
            life: 3000,
        });
    } finally {
        loading.value = false;
    }
};

// Add page change handler
const onPage = (event) => {
    first.value = event.first;
    rows.value = event.rows;
    currentPage.value = Math.floor(event.first / event.rows) + 1;

    console.log(event);
    fetchMediaFiles();
};

onMounted(() => {
    fetchMediaFiles();
});

// Remove getBadgeSeverity function as it's no longer needed

// Create icons object
const icons = {
    BsFileEarmark,
    BsFileExcel,
    BsFileImage,
    BsFileMusic,
    BsFilePdf,
    BsFilePlayFill,
    BsFilePpt,
    BsFileText,
    BsFileWord,
    BsFileZip
};

// Replace getFileIcon function with a simpler version
const getFileIconComponent = (file) => {
    return getFileIcon(file, icons);
};

// Add Dialog control refs
const previewDialogVisible = ref(false);
const previewContent = ref(null);
const previewHeader = ref('媒体预览');

// 检查文件是否可预览
const isPreviewable = (file) => {
    if (!file?.mime_type) return false;
    const type = file.mime_type.split('/')[0];
    return ['image', 'video', 'audio'].includes(type);
};

// 预览文件
const previewFile = (file) => {
    if (!file?.mime_type) return;
    const type = file.mime_type.split('/')[0];
    const url = mediaService.getMediaPreviewUrl(file.id);

    switch (type) {
        case 'image':
            previewContent.value = h('img', {
                src: url,
                style: {
                    maxWidth: '100%',
                    maxHeight: '80vh',
                    objectFit: 'contain'
                }
            });
            break;
        case 'video':
            previewContent.value = h('video', {
                src: url,
                controls: true,
                style: {
                    maxWidth: '100%',
                    maxHeight: '80vh'
                }
            });
            break;
        case 'audio':
            previewContent.value = h('audio', {
                src: url,
                controls: true,
                style: {
                    width: '100%'
                }
            });
            break;
        default:
            return;
    }

    previewDialogVisible.value = true;
};

// Add delete related methods
const confirmDelete = (file) => {
    confirm.require({
        message: `确定要删除文件 "${file.name}" 吗？`,
        header: '确认删除',
        icon: 'pi pi-exclamation-triangle',
        acceptClass: 'p-button-danger',
        accept: () => handleDelete(file),
        reject: () => { },
        acceptLabel: '删除',
        rejectLabel: '取消'
    });
};

const handleDelete = async (file) => {
    try {
        await mediaService.delete(file.id);
        toast.add({
            severity: 'success',
            summary: '成功',
            detail: '文件已删除',
            life: 3000
        });
        fetchMediaFiles();
    } catch (error) {
        toast.add({
            severity: 'error',
            summary: '错误',
            detail: '删除文件失败',
            life: 3000
        });
    }
};
</script>

<template>
    <Toast />
    <ConfirmDialog />
    <!-- Remove ConfirmDialog -->

    <!-- Add Dialog component -->
    <Dialog v-model:visible="previewDialogVisible" :modal="true" :header="previewHeader"
        :style="{ width: '80vw', maxWidth: '1000px' }">
        <div class="flex justify-center items-center">
            <component :is="previewContent" />
        </div>
    </Dialog>

    <div class="w-full">
        <div class="flex justify-between items-center mb-6 gap-4">
            <h1 class="text-2xl font-semibold text-gray-800 text-nowrap">媒体库</h1>

            <Button class="text-nowrap !px-8" icon="pi pi-upload" label="上传" severity="primary"
                @click="openUploadDialog" />
        </div>

        <!-- Media Table -->
        <div class="card mt-10">
            <div class="pb-10 flex">
                <InputText v-model="globalFilterValue" placeholder="搜索媒体..." class="flex-1" />
            </div>

            <DataTable v-model:filters="filters" :value="mediaFiles" :paginator="true" v-model:first="first"
                v-model:rows="rows" :totalRecords="totalRecords" @page="onPage"
                paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                :rows-per-page-options="[10, 25, 50]"
                current-page-report-template="第 {first} 到 {last} 条，共 {totalRecords} 条" :lazy="true"
                :show-current-page-report="true">
                <template #paginatorLeft>
                    <div class="flex items-center">每页: {{ rows }}</div>
                </template>
                <template #paginatorRight>
                    <div class="flex items-center">
                        第 {{ currentPage }} 页，共 {{ totalPages }} 页
                    </div>
                </template>
                <template #empty>
                    <div class="text-center p-4">未找到媒体文件</div>
                </template>
                <template #loading>
                    <div class="flex flex-col items-center justify-center p-4">
                        <ProgressSpinner style="width: 50px; height: 50px" />
                        <span class="mt-2">加载中...</span>
                    </div>
                </template>

                <Column field="name" header="文件名">
                    <template #body="{ data }">
                        <div class="flex items-center">
                            <div
                                class="flex-shrink-0 h-10 w-10 mr-3 bg-gray-100 rounded flex items-center justify-center">
                                <component :is="getFileIconComponent(data)" class="text-xl text-gray-600" />
                            </div>
                            <div class="text-sm font-medium text-gray-900">{{ data.name }}</div>
                        </div>
                    </template>
                </Column>

                <Column field="created_at" header="上传时间">
                    <template #body="{ data }">
                        <div class="flex flex-col">
                            <span class="text-gray-400"> {{ formatDate(data.created_at) }}</span>
                        </div>
                    </template>
                </Column>

                <Column field="size" header="文件大小">
                    <template #body="{ data }">
                        {{ formatFileSize(data.size) }}
                    </template>
                </Column>

                <Column field="media_type" header="文件类型">
                    <template #body="{ data }">
                        <Badge :value="getFileTypeByMimeCN(data.mime_type)" />
                    </template>
                    <template #filter="{ filterModel, filterCallback }">
                        <Dropdown v-model="filterModel.value" @change="filterCallback()" :options="mediaTypes"
                            optionLabel="name" optionValue="value" placeholder="全部" class="p-column-filter" showClear />
                    </template>
                </Column>

                <Column header="" :exportable="false" style="min-width: 8rem">
                    <template #body="{ data }">
                        <div class="flex justify-center space-x-2">
                            <Button v-if="isPreviewable(data)" icon="pi pi-eye" rounded text severity="info"
                                @click="previewFile(data)" aria-label="Preview" />
                            <Button icon="pi pi-download" rounded text severity="secondary" @click="downloadFile(data)"
                                aria-label="Download" />
                            <Button icon="pi pi-trash" rounded text severity="danger" @click="confirmDelete(data)"
                                aria-label="Delete" />
                        </div>
                    </template>
                </Column>
            </DataTable>
        </div>
    </div>
</template>

<style scoped>
.p-fileupload {
    border: 2px dashed #cbd5e0;
    transition: all 0.3s ease;
}

.p-fileupload:hover {
    border-color: #4299e1;
    background-color: rgba(66, 153, 225, 0.05);
}

/* Add Dialog custom styles */
:deep(.p-dialog-content) {
    padding: 2rem;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
