<script setup>
import { ref, computed } from 'vue';
import { CloudArrowUpIcon, XMarkIcon, DocumentIcon } from '@heroicons/vue/24/outline';

const props = defineProps({
    modelValue: {
        type: [File, null],
        default: null,
    },
    label: {
        type: String,
        default: 'Dosya Yükle',
    },
    required: {
        type: Boolean,
        default: false,
    },
    help: {
        type: String,
        default: '',
    },
     error: {
        type: String,
        default: '',
    },
    accept: {
        type: String,
        default: 'image/*,application/pdf', // Default accepted file types
    },
    id: {
        type: String,
        default: () => `dropzone-${Math.random().toString(36).substring(2, 15)}`,
    },
    disabled: {
        type: Boolean,
        default: false,
    },
});

const emit = defineEmits(['update:modelValue']);

const fileInput = ref(null);
const isDragging = ref(false);

const componentValue = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value),
});

const openFileDialog = () => {
    if (props.disabled) return;
    fileInput.value?.click();
};

const handleFileChange = (event) => {
    const files = event.target.files;
    if (files && files.length > 0) {
        componentValue.value = files[0];
    }
    if (fileInput.value) {
        fileInput.value.value = '';
    }
};

const acceptedTypesDisplay = computed(() => {
    if (!props.accept) return '';
    const typeMap = {
        'application/pdf': 'PDF',
        'image/jpeg': 'JPG',
        'image/jpg': 'JPG',
        'image/png': 'PNG',
        'image/*': 'Resim',
    };

    const displayTypes = new Set();
    props.accept.split(',')
        .map(type => type.trim().toLowerCase())
        .forEach(type => {
            if (typeMap[type]) {
                displayTypes.add(typeMap[type]);
            } else if (type.startsWith('image/')) {
                displayTypes.add('Resim');
            }
        });

    return Array.from(displayTypes).join(', ');
});

const handleDrop = (event) => {
    if (props.disabled) return;
    isDragging.value = false;
    const files = event.dataTransfer?.files;
    if (files && files.length > 0) {
        const file = files[0];
        if (props.accept.includes('*/*') || props.accept.split(',').some(type => file.type.match(type.trim().replace('*', '.*')))) {
            componentValue.value = file;
        } else {
            console.warn(`Invalid file type: ${file.type}. Accepted: ${props.accept}`);
        }
    }
};

const removeFile = () => {
    componentValue.value = null;
};

const dragOver = () => {
    if (props.disabled) return;
    isDragging.value = true;
};

const dragLeave = () => {
    isDragging.value = false;
};

const formatBytes = (bytes, decimals = 2) => {
    if (!+bytes) return '0 Bytes';
    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
};
</script>

<template>
    <div class="flex flex-col gap-2">
        <label
            :for="id"
            :class="`${
                disabled ? 'text-gray-400' : 'text-gray-900 dark:text-white'
            } block text-sm font-medium`"
        >
            {{ label }} <span v-if="required" class="text-red-600">*</span>
        </label>

        <div
            :class="[
                'flex justify-center items-center w-full px-6 py-10 border-2 border-dashed rounded-lg cursor-pointer transition-colors',
                disabled ? 'bg-gray-200 border-gray-300 cursor-not-allowed' :
                isDragging ? 'border-primary-500 bg-primary-50' :
                error ? 'border-red-400 bg-red-50' :
                'border-gray-300 hover:border-gray-400 bg-gray-50 dark:border-gray-600 dark:hover:border-gray-500 dark:bg-gray-700 dark:hover:bg-gray-600',
            ]"
            @click="openFileDialog"
            @dragover.prevent="dragOver"
            @dragleave.prevent="dragLeave"
            @drop.prevent="handleDrop"
        >
            <input
                :id="id"
                ref="fileInput"
                type="file"
                class="hidden"
                :accept="accept"
                :disabled="disabled"
                @change="handleFileChange"
            />

            <div v-if="!componentValue" class="text-center">
                <CloudArrowUpIcon class="mx-auto h-12 w-12 text-gray-400" />
                <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">
                    <span class="font-semibold">Dosya seçmek için tıklayın</span> veya sürükleyip bırakın
                </p>
                <p class="mt-1 text-xs text-gray-500 dark:text-gray-500">
                    ({{ acceptedTypesDisplay }})
                </p>
            </div>

            <div v-else class="text-center w-full">
                 <div class="flex items-center justify-center gap-2 bg-gray-100 dark:bg-gray-600 p-3 rounded-md border border-gray-300 dark:border-gray-500 relative">
                    <DocumentIcon class="h-8 w-8 text-gray-500 dark:text-gray-400 flex-shrink-0" />
                    <div class="text-left overflow-hidden">
                        <p class="text-sm font-medium text-gray-900 dark:text-gray-200 truncate" :title="componentValue.name">
                            {{ componentValue.name }}
                        </p>
                        <p class="text-xs text-gray-500 dark:text-gray-400">
                            {{ formatBytes(componentValue.size) }}
                        </p>
                    </div>
                    <button
                        v-if="!disabled"
                        type="button"
                        @click.stop="removeFile"
                        class="absolute top-1 right-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 p-1 rounded-full bg-white dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-500"
                        aria-label="Remove file"
                    >
                        <XMarkIcon class="h-4 w-4" />
                    </button>
                </div>
            </div>
        </div>
         <div v-if="help" class="text-sm text-gray-600">
            {{ help }}
        </div>
        <div v-if="error" class="text-sm text-red-600">
            {{ error }}
        </div>
    </div>
</template>