<!-- AvatarUpload.vue -->
<template>
    <div class="avatar-upload">
        <div class="avatar-preview">
            <img v-if="previewUrl" :src="previewUrl" alt="Аватар" class="avatar-image" @error="handleImageError" />
            <div v-else class="avatar-placeholder">
                👤
            </div>
        </div>

        <div v-if="showActions" class="avatar-actions">
            <label class="btn btn-small" :class="{ 'btn-disabled': uploading }">
                {{ uploading ? 'Загрузка...' : '📷 Загрузить' }}
                <input type="file" accept="image/*" @change="handleFileSelect" :disabled="uploading"
                    style="display: none;">
            </label>

            <button v-if="previewUrl" class="btn btn-small btn-danger" @click="deleteAvatar" :disabled="uploading">
                🗑️ Удалить
            </button>
        </div>

        <div v-if="error" class="error-message">
            {{ error }}
        </div>
    </div>
</template>

<script>
import { useAuthStore } from '../stores/auth'

export default {
    name: 'AvatarUpload',
    props: {
        user: Object,
        showActions: {
            type: Boolean,
            default: true
        }
    },
    setup() {
        const authStore = useAuthStore()
        return { authStore }
    },
    data() {
        return {
            previewUrl: null,
            uploading: false,
            error: ''
        }
    },
    watch: {
        user: {
            immediate: true,
            handler(newUser) {
                console.log('User data in AvatarUpload:', newUser)
                if (newUser?.avatar) {
                    console.log('Avatar path:', newUser.avatar)
                    const fullUrl = this.getFullAvatarUrl(newUser.avatar)
                    console.log('Full avatar URL:', fullUrl)
                    this.previewUrl = fullUrl
                } else {
                    console.log('No avatar found')
                    this.previewUrl = null
                }
            }
        }
    },
    methods: {
        getFullAvatarUrl(avatarPath) {
            if (!avatarPath) return null;

            console.log('Building URL for avatar path:', avatarPath);

            if (avatarPath.startsWith('http')) {
                return avatarPath;
            }

            // Извлекаем имя файла из пути
            const filename = avatarPath.trim('/').split('/').pop();

            // Используем API эндпоинт вместо прямого доступа
            const fullUrl = `https://begushiybashkir.ru/api/v1/user/avatars/${filename}`;
            console.log('Built URL with API endpoint:', fullUrl);
            return fullUrl;
        },

        handleImageError(event) {
            console.error('Error loading avatar image:', event)
            this.previewUrl = null
        },

        handleFileSelect(event) {
            const file = event.target.files[0]
            if (file) {
                // Валидация файла
                if (!file.type.startsWith('image/')) {
                    this.error = 'Пожалуйста, выберите файл изображения'
                    return
                }

                if (file.size > 5 * 1024 * 1024) { // 5MB
                    this.error = 'Размер файла не должен превышать 5MB'
                    return
                }

                // Создаем preview
                const reader = new FileReader()
                reader.onload = (e) => {
                    this.previewUrl = e.target.result
                }
                reader.readAsDataURL(file)

                // Загружаем на сервер
                this.uploadAvatar(file)

                // Сбрасываем input
                event.target.value = ''
            }
        },

        async uploadAvatar(file) {
            this.uploading = true
            this.error = ''

            try {
                const result = await this.authStore.updateAvatar(file)
                console.log('Upload result:', result)

                if (result.success) {
                    this.$emit('avatar-updated', result.avatar)
                } else {
                    this.error = result.error || 'Ошибка загрузки'
                    // Восстанавливаем старый preview
                    this.previewUrl = this.getFullAvatarUrl(this.user?.avatar)
                }
            } catch (err) {
                console.error('Upload error:', err)
                this.error = 'Ошибка загрузки: ' + (err.message || 'Неизвестная ошибка')
                this.previewUrl = this.getFullAvatarUrl(this.user?.avatar)
            } finally {
                this.uploading = false
            }
        },

        async deleteAvatar() {
            this.uploading = true
            this.error = ''

            try {
                const result = await this.authStore.deleteAvatar()
                console.log('Delete result:', result)

                if (result.success) {
                    this.previewUrl = null
                    this.$emit('avatar-updated', null)
                } else {
                    this.error = result.error || 'Ошибка удаления'
                }
            } catch (err) {
                console.error('Delete error:', err)
                this.error = 'Ошибка удаления: ' + (err.message || 'Неизвестная ошибка')
            } finally {
                this.uploading = false
            }
        }
    }
}
</script>

<style scoped>
.avatar-upload {
    text-align: center;
    margin: 1rem 0;
}

.avatar-preview {
    width: 120px;
    height: 120px;
    margin: 0 auto 1rem;
    border-radius: 50%;
    overflow: hidden;
    border: 3px solid #e0e0e0;
    background-color: #f5f5f5;
}

.avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.avatar-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 3rem;
    background-color: #e0e0e0;
}

.avatar-actions {
    display: flex;
    gap: 0.5rem;
    justify-content: center;
    flex-wrap: wrap;
}

.btn-small {
    padding: 0.5rem 1rem;
    font-size: 0.9rem;
}

.btn-danger {
    background-color: #dc3545;
    color: white;
}

.btn-danger:hover:not(:disabled) {
    background-color: #c82333;
}

.btn-disabled {
    background-color: #ccc;
    cursor: not-allowed;
}

.error-message {
    color: #dc3545;
    font-size: 0.9rem;
    margin-top: 0.5rem;
}
</style>