<template>
    <div>
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>Kategori Yönetimi</h2>
        </div>

        <!-- Filter / Search -->
        <div class="card mb-4">
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-4">
                        <select v-model="filterStatus" class="form-select" @change="fetchCategories(1)">
                            <option value="">Aktif Kategoriler</option>
                            <option value="only">Silinenler (Çöp Kutusu)</option>
                            <option value="with">Tümü (Silinenler Dahil)</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <!-- Categories List Card -->
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center bg-white">
                <h5 class="mb-0">Kategoriler</h5>
                <button class="btn btn-success btn-sm" @click="openModal(null)">
                    <i class="fas fa-plus me-2"></i> Yeni Kategori
                </button>
            </div>
            <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-if="categories.length === 0" class="text-center py-5 text-muted">
                    Kayıt bulunamadı.
                </div>

                <div v-else class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Başlık</th>
                                <th>Slug</th>
                                <th>Açıklama</th>
                                <th>Durum</th>
                                <th class="text-end">İşlemler</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="category in categories" :key="category.ID">
                                <td>{{ category.ID }}</td>
                                <td>
                                    <!-- Indentation for hierarchy if available, otherwise flat -->
                                    <div :style="{ paddingLeft: (category.parent_id ? 20 : 0) + 'px' }">
                                        <span v-if="category.parent_id" class="text-muted me-1">↳</span>
                                        {{ category.title }}
                                    </div>
                                </td>
                                <td><span class="badge bg-light text-dark">{{ category.slug }}</span></td>
                                <td>{{ category.description }}</td>
                                <td>
                                    <span v-if="category.DeletedAt" class="badge bg-danger">Silindi</span>
                                    <span v-else class="badge bg-success">Aktif</span>
                                </td>
                                <td class="text-end">
                                    <div v-if="!category.DeletedAt">
                                        <button class="btn btn-sm btn-outline-primary me-2" @click="openModal(category)">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger" @click="deleteCategory(category.ID)">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                    <div v-else>
                                        <button class="btn btn-sm btn-outline-success me-2" @click="restoreCategory(category.ID)">
                                            <i class="fas fa-trash-restore"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger" @click="hardDeleteCategory(category.ID)">
                                            <i class="fas fa-times-circle"></i> Kalıcı Sil
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

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

        <!-- Create/Edit Modal -->
        <div class="modal fade" id="categoryModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">{{ isEditing ? 'Kategoriyi Düzenle' : 'Yeni Kategori' }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="saveCategory">
                            <div class="mb-3">
                                <label class="form-label">Başlık</label>
                                <input v-model="formData.title" type="text" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Açıklama</label>
                                <textarea v-model="formData.description" class="form-control" rows="3"></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Üst Kategori (Opsiyonel)</label>
                                <select v-model="formData.parent_id" class="form-select">
                                    <option :value="null">Ana Kategori</option>
                                    <!-- Only show active categories as parents to avoid confusion -->
                                    <option v-for="cat in activeCategories" :key="cat.ID" :value="cat.ID"
                                        :disabled="cat.ID === formData.ID">
                                        {{ cat.title }}
                                    </option>
                                </select>
                            </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="loading">
                                    <span v-if="loading" 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 { Category } from '~~/types/category';
import Swal from 'sweetalert2';

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

const config = useRuntimeConfig();
const { data: authData } = useAuth();
const categories = ref<Category[]>([]);
const activeCategories = ref<Category[]>([]); // For parent selection
const loading = ref(false);
const isEditing = ref(false);
const formData = ref<Partial<Category>>({});
const filterStatus = ref(''); // '' = active, 'only' = trashed, 'with' = all
let categoryModal: any = null;

const pagination = ref({
    page: 1,
    per_page: 10,
    total: 0
});

// -- API --

const fetchCategories = async (page = 1) => {
    loading.value = true;
    try {
        const query: any = { page }; // Pagination if supported by admin endpoint
        if (filterStatus.value) {
            query.trashed = filterStatus.value;
        }

        // Use Admin endpoint for management
        const url = '/api/v1/admin/categories';
        
        const res = await $fetch<any>(url, {
            baseURL: config.public.BASE_API_URL,
            headers: { Authorization: `Bearer ${(authData.value as any)?.accessToken}` },
            query
        });

        if (res.data) {
             categories.value = res.data;
             pagination.value = res.meta || { page: 1, per_page: 100, total: res.data.length }; // Fallback if no meta
        } else if (Array.isArray(res)) {
             // Fallback for non-paginated response (if API changes or for active list)
             categories.value = res;
             pagination.value = { page: 1, per_page: 100, total: res.length };
        } else {
             categories.value = [];
        }

        // Fetch active categories for parent selection (always needs active ones)
        if (filterStatus.value === '') {
            activeCategories.value = categories.value;
        } else {
            // If we are viewing trashed, we still need active categories for the dropdown
            // We can fetch them separately/lightweight if needed, or just allow 'null' parent
            // checking if we have them cached or fetch explicitly
            // For now, let's just fetch active ones if we don't have them
             const activeRes = await $fetch<Category[]>('/api/v1/categories', {
                 baseURL: config.public.BASE_API_URL, 
                 headers: { Authorization: `Bearer ${(authData.value as any)?.accessToken}` }
             });
             activeCategories.value = activeRes || [];
        }

    } catch (e) {
        console.error(e);
        categories.value = [];
    } finally {
        loading.value = false;
    }
};

const openModal = (category: Category | null) => {
    isEditing.value = !!category;
    formData.value = category ? { ...category } : { title: '', description: '', parent_id: null };

    // Check if modal instance exists
    const el = document.getElementById('categoryModal');
    if (el) {
        // @ts-ignore
        categoryModal = new bootstrap.Modal(el);
        categoryModal.show();
    }
};

const saveCategory = async () => {
    loading.value = true;
    try {
        const url = isEditing.value
            ? `/api/v1/categories/${formData.value.ID}`
            : '/api/v1/categories';

        const method = isEditing.value ? 'PUT' : 'POST';

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

        Swal.fire('Başarılı', `Kategori ${isEditing.value ? 'güncellendi' : 'eklendi'}.`, 'success');
        if (categoryModal) categoryModal.hide();
        fetchCategories(pagination.value.page);

    } catch (error) {
        console.error(error);
        Swal.fire('Hata', 'İşlem başarısız.', 'error');
    } finally {
        loading.value = false;
    }
};

const deleteCategory = async (id: number) => {
    const result = await Swal.fire({
        title: 'Emin misiniz?',
        text: "Kategori silinecek (Çöp kutusuna taşınacak).",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Evet, Sil',
        cancelButtonText: 'İptal',
        confirmButtonColor: '#d33'
    });

    if (!result.isConfirmed) return;

    try {
        await $fetch(`/api/v1/categories/${id}`, {
            method: 'DELETE',
            baseURL: config.public.BASE_API_URL,
            headers: { Authorization: `Bearer ${(authData.value as any)?.accessToken}` }
        });

        Swal.fire('Silindi', 'Kategori silindi.', 'success');
        fetchCategories(pagination.value.page);
    } catch (error) {
        console.error(error);
        Swal.fire('Hata', 'Silme işlemi başarısız.', 'error');
    }
};

const restoreCategory = async (id: number) => {
    try {
        await $fetch(`/api/v1/admin/categories/${id}/restore`, {
            method: 'POST',
            baseURL: config.public.BASE_API_URL,
            headers: { Authorization: `Bearer ${(authData.value as any)?.accessToken}` }
        });
        
        Swal.fire('Başarılı', 'Kategori geri yüklendi.', 'success');
        fetchCategories(pagination.value.page);
    } catch (error) {
         console.error(error);
         Swal.fire('Hata', 'Geri yükleme başarısız.', 'error');
    }
};

const hardDeleteCategory = async (id: number) => {
    const result = await Swal.fire({
        title: 'Kalıcı Olarak Sil?',
        text: "Bu işlem geri alınamaz!",
        icon: 'error',
        showCancelButton: true,
        confirmButtonText: 'Evet, Kalıcı Sil',
        cancelButtonText: 'İptal',
        confirmButtonColor: '#d33'
    });

    if (!result.isConfirmed) return;

    try {
        await $fetch(`/api/v1/admin/categories/${id}/hard`, {
            method: 'DELETE',
            baseURL: config.public.BASE_API_URL,
            headers: { Authorization: `Bearer ${(authData.value as any)?.accessToken}` }
        });
        
        Swal.fire('Silindi', 'Kategori kalıcı olarak silindi.', 'success');
        fetchCategories(pagination.value.page);
    } catch (error) {
         console.error(error);
         Swal.fire('Hata', 'Silme işlemi başarısız.', 'error');
    }
};

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