<template>
    <div>
        <!-- Upload Section (when no file is attached) -->
        <div v-if="!hasFile">
            <a-upload
                :accept="acceptFormat"
                v-model:file-list="fileList"
                name="file"
                :show-upload-list="false"
                :before-upload="beforeUpload"
                :customRequest="() => {}"
            >
                <a-button>
                    <template #icon>
                        <UploadOutlined />
                    </template>
                    {{ $t("common.upload") }}
                </a-button>
            </a-upload>
        </div>

        <!-- Download & Delete Section (when file exists) -->
        <div v-else>
            <a-space>
                <!-- Show download button if URL exists (either local or server) -->
                <a-typography-link
                    v-if="downloadUrl"
                    :href="downloadUrl"
                    :download="selectedFileName"
                    target="_blank"
                >
                    <a-tag color="success">
                        <template #icon>
                            <DownloadOutlined />
                        </template>
                        {{ $t("common.download") }}
                    </a-tag>
                </a-typography-link>

                <a-typography-link @click="handleDelete">
                    <a-tag color="error">
                        <template #icon>
                            <DeleteOutlined />
                        </template>
                        {{ $t("common.delete") }}
                    </a-tag>
                </a-typography-link>
            </a-space>
        </div>
    </div>
</template>

<script setup>
import {
    UploadOutlined,
    DownloadOutlined,
    DeleteOutlined
} from "@ant-design/icons-vue";
import { ref, computed, watch } from "vue";

const props = defineProps({
    acceptFormat: {
        default: "*/*",
        type: String,
    },
    formData: {
        type: Object,
        required: true,
    },
    uploadField: {
        default: "file",
        type: String,
    },
});

const emit = defineEmits(["onFileSelected", "onDelete"]);

const fileList = ref([]);
const selectedFileName = ref(null);
const selectedFileUrl = ref(null);

// Watch for changes in formData to reset component state
watch(
    () => props.formData,
    (newFormData) => {
        // Reset local state when formData changes (e.g., drawer reopened)
        // If formData doesn't have the file or URL, clear local state
        if (!newFormData[props.uploadField] && !newFormData[`${props.uploadField}_url`]) {
            // Revoke old object URL to free memory
            if (selectedFileUrl.value) {
                URL.revokeObjectURL(selectedFileUrl.value);
            }

            selectedFileName.value = null;
            selectedFileUrl.value = null;
            fileList.value = [];
        }
    },
    { deep: true }
);

// Check if file exists (either newly selected or existing from formData)
const hasFile = computed(() => {
    // Check if there's a selected file OR if there's a URL (existing uploaded file)
    return selectedFileName.value || props.formData[`${props.uploadField}_url`];
});

// Get download URL - either local preview or server URL
const downloadUrl = computed(() => {
    // Priority: local preview URL for newly selected file
    if (selectedFileUrl.value) {
        return selectedFileUrl.value;
    }

    // Otherwise, use server URL
    return props.formData[`${props.uploadField}_url`] || null;
});

const beforeUpload = (file) => {
    // Store the selected filename
    selectedFileName.value = file.name;

    // Create a local URL for immediate download/preview
    selectedFileUrl.value = URL.createObjectURL(file);

    // Emit the file object to parent
    emit("onFileSelected", file);

    // Return false to prevent automatic upload
    return false;
};

const handleDelete = () => {
    // Revoke the object URL to free memory
    if (selectedFileUrl.value) {
        URL.revokeObjectURL(selectedFileUrl.value);
    }

    // Clear the selected file
    selectedFileName.value = null;
    selectedFileUrl.value = null;
    fileList.value = [];

    // Clear formData fields
    props.formData[props.uploadField] = undefined;
    props.formData[`${props.uploadField}_url`] = undefined;

    // Emit delete event
    emit("onDelete");
};
</script>

<style scoped>
/* Add any custom styles if needed */
</style>
