<template>
    <div>
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>Etiket Yönetimi</h2>
            <button class="btn btn-primary" @click="openModal()">
                <i class="fas fa-plus me-2"></i> Yeni Etiket
            </button>
        </div>

        <div class="card mb-4">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-outline-secondary" :class="{ active: filterTrashed === 'without' }" @click="changeFilter('without')">
                                Aktif
                            </button>
                            <button type="button" class="btn btn-outline-secondary" :class="{ active: filterTrashed === 'only' }" @click="changeFilter('only')">
                                Çöp Kutusu
                            </button>
                             <button type="button" class="btn btn-outline-secondary" :class="{ active: filterTrashed === 'with' }" @click="changeFilter('with')">
                                Hepsi
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-body">
                <div v-if="loading" class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Yükleniyor...</span>
                    </div>
                </div>

                <div v-else class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Etiket Adı</th>
                                <th>Oluşturulma</th>
                                <th>Durum</th>
                                <th class="text-end">İşlemler</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="tag in tags" :key="tag.ID">
                                <td>#{{ tag.ID }}</td>
                                <td>
                                    <span class="fw-bold">{{ tag.name }}</span>
                                </td>
                                <td>{{ new Date(tag.CreatedAt).toLocaleDateString('tr-TR') }}</td>
                                <td>
                                    <span v-if="tag.DeletedAt" class="badge bg-danger">Silinmiş</span>
                                    <span v-else class="badge bg-success">Aktif</span>
                                </td>
                                <td class="text-end">
                                    <div class="btn-group btn-group-sm">
                                        <button v-if="!tag.DeletedAt" class="btn btn-outline-primary" @click="openModal(tag)" title="Düzenle">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        
                                        <button v-if="!tag.DeletedAt" class="btn btn-outline-danger" @click="deleteTag(tag.ID)" title="Sil">
                                            <i class="fas fa-trash"></i>
                                        </button>

                                        <button v-if="tag.DeletedAt" class="btn btn-outline-success" @click="restoreTag(tag.ID)" title="Geri Yükle">
                                            <i class="fas fa-trash-restore"></i>
                                        </button>

                                        <button v-if="tag.DeletedAt" class="btn btn-outline-dark" @click="hardDeleteTag(tag.ID)" title="Kalıcı Sil">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <tr v-if="tags.length === 0">
                                <td colspan="5" class="text-center py-4">Kayıt bulunamadı.</td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <nav v-if="totalPages > 1" class="mt-4">
                    <ul class="pagination justify-content-center">
                        <li class="page-item" :class="{ disabled: currentPage === 1 }">
                            <button class="page-link" @click="changePage(currentPage - 1)">Önceki</button>
                        </li>
                        <li v-for="page in totalPages" :key="page" class="page-item" :class="{ active: currentPage === page }">
                            <button class="page-link" @click="changePage(page)">{{ page }}</button>
                        </li>
                        <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                            <button class="page-link" @click="changePage(currentPage + 1)">Sonraki</button>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>

        <!-- Tag Modal -->
        <div class="modal fade" id="tagModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">{{ isEditing ? 'Etiket Düzenle' : 'Yeni Etiket Ekle' }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="saveTag">
                            <div class="mb-3">
                                <label class="form-label">Etiket Adı</label>
                                <input v-model="tagForm.name" type="text" class="form-control" required>
                            </div>
                            <div class="text-end">
                                <button type="button" class="btn btn-secondary me-2" data-bs-dismiss="modal">İptal</button>
                                <button type="submit" class="btn btn-primary" :disabled="saving">
                                    <span v-if="saving" class="spinner-border spinner-border-sm me-2"></span>
                                    Kaydet
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

    </div>
</template>

<script setup lang="ts">
import type { Tag, TagResponse } from '~~/types/tag';
import Swal from 'sweetalert2';

definePageMeta({
    layout: 'admin',
    middleware: 'admin'
});

const config = useRuntimeConfig();
const { data: authData } = useAuth();

const loading = ref(false);
const saving = ref(false);
const tags = ref<Tag[]>([]);
const currentPage = ref(1);
const totalPages = ref(1);
const filterTrashed = ref<'without' | 'with' | 'only'>('without');

const tagForm = ref({
    ID: 0,
    name: ''
});
const isEditing = ref(false);
let tagModal: any = null;

const fetchTags = async () => {
    loading.value = true;
    try {
        const res = await $fetch<TagResponse>('/api/v1/admin/tags', {
            baseURL: config.public.BASE_API_URL,
            headers: { Authorization: `Bearer ${(authData.value as any)?.accessToken}` },
            params: {
                page: currentPage.value,
                limit: 10,
                ...(filterTrashed.value !== 'without' && { trashed: filterTrashed.value })
            }
        });

        if (res && res.data) {
            tags.value = res.data;
            totalPages.value = Math.ceil(res.meta.total / res.meta.per_page);
        } else {
            tags.value = [];
        }
    } catch (error) {
        console.error(error);
        Swal.fire('Hata', 'Etiketler yüklenirken bir hata oluştu.', 'error');
    } finally {
        loading.value = false;
    }
};

const changePage = (page: number) => {
    if (page >= 1 && page <= totalPages.value) {
        currentPage.value = page;
        fetchTags();
    }
};

const changeFilter = (filter: 'without' | 'with' | 'only') => {
    filterTrashed.value = filter;
    currentPage.value = 1;
    fetchTags();
};

const openModal = (tag: Tag | null = null) => {
    if (tag) {
        isEditing.value = true;
        tagForm.value = { ID: tag.ID, name: tag.name };
    } else {
        isEditing.value = false;
        tagForm.value = { ID: 0, name: '' };
    }

    const modalEl = document.getElementById('tagModal');
    if (modalEl) {
        // @ts-ignore
        tagModal = new bootstrap.Modal(modalEl);
        tagModal.show();
    }
};

const saveTag = async () => {
    saving.value = true;
    try {
        let url = '/api/v1/tags';
        let method: 'POST' | 'PUT' = 'POST';

        if (isEditing.value && tagForm.value.ID) {
            url = `/api/v1/tags/${tagForm.value.ID}`;
            method = 'PUT';
        }

        await $fetch(url, {
            method: method,
            baseURL: config.public.BASE_API_URL,
            headers: { Authorization: `Bearer ${(authData.value as any)?.accessToken}` },
            body: { name: tagForm.value.name }
        });

        if (tagModal) tagModal.hide();
        Swal.fire('Başarılı', `Etiket ${isEditing.value ? 'güncellendi' : 'eklendi'}.`, 'success');
        fetchTags();

    } catch (error: any) {
        console.error(error);
        Swal.fire('Hata', error.data?.message || 'İşlem başarısız.', 'error');
    } finally {
        saving.value = false;
    }
};

const deleteTag = async (id: number) => {
    const result = await Swal.fire({
        title: 'Emin misiniz?',
        text: "Bu etiketi çöp kutusuna taşımak istediğinize emin misiniz?",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Evet, Sil',
        cancelButtonText: 'İptal'
    });

    if (result.isConfirmed) {
        try {
            await $fetch(`/api/v1/tags/${id}`, {
                method: 'DELETE',
                baseURL: config.public.BASE_API_URL,
                headers: { Authorization: `Bearer ${(authData.value as any)?.accessToken}` }
            });
            Swal.fire('Silindi', 'Etiket çöp kutusuna taşındı.', 'success');
            fetchTags();
        } catch (error) {
            console.error(error);
            Swal.fire('Hata', 'Silme işlemi başarısız.', 'error');
        }
    }
};

const hardDeleteTag = async (id: number) => {
    const result = await Swal.fire({
        title: 'DİKKAT! Kalıcı Silme',
        text: "Bu işlem geri alınamaz! Etiketi tamamen silmek istediğinize emin misiniz?",
        icon: 'error',
        showCancelButton: true,
        confirmButtonText: 'Evet, Tamamen Sil',
        cancelButtonText: 'İptal'
    });

    if (result.isConfirmed) {
         try {
            await $fetch(`/api/v1/admin/tags/${id}/hard`, {
                method: 'DELETE',
                baseURL: config.public.BASE_API_URL,
                headers: { Authorization: `Bearer ${(authData.value as any)?.accessToken}` }
            });
            Swal.fire('Silindi', 'Etiket kalıcı olarak silindi.', 'success');
            fetchTags();
        } catch (error) {
            console.error(error);
            Swal.fire('Hata', 'Kalıcı silme işlemi başarısız.', 'error');
        }
    }
};

const restoreTag = async (id: number) => {
     try {
        await $fetch(`/api/v1/admin/tags/${id}/restore`, {
            method: 'POST',
            baseURL: config.public.BASE_API_URL,
            headers: { Authorization: `Bearer ${(authData.value as any)?.accessToken}` }
        });
        Swal.fire('Geri Yüklendi', 'Etiket başarıyla geri yüklendi.', 'success');
        fetchTags();
    } catch (error) {
        console.error(error);
        Swal.fire('Hata', 'Geri yükleme işlemi başarısız.', 'error');
    }
};

onMounted(() => {
    fetchTags();
});
</script>
