<script setup>
import { Head, Link, router, useForm } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { ref } from 'vue';

const props = defineProps({
    testimonials: Array,
    filter: String,
    counts: Object,
});

const rejectionModal = ref(false);
const selectedTestimonial = ref(null);
const rejectionForm = useForm({
    reason: '',
});

const filters = [
    { value: 'pending', label: 'Pendientes', count: props.counts.pending },
    { value: 'approved', label: 'Aprobados', count: props.counts.approved },
    { value: 'rejected', label: 'Rechazados', count: props.counts.rejected },
    { value: 'coach', label: 'De Coaches', count: props.counts.coach_submissions },
    { value: 'all', label: 'Todos' },
];

const setFilter = (filter) => {
    router.get(route('admin.testimonials.approval'), { filter }, {
        preserveState: true,
        preserveScroll: true,
    });
};

const approveTestimonial = (id) => {
    router.post(route('admin.testimonials.approve', id), {}, {
        preserveScroll: true,
    });
};

const openRejectModal = (testimonial) => {
    selectedTestimonial.value = testimonial;
    rejectionForm.reset();
    rejectionModal.value = true;
};

const submitRejection = () => {
    rejectionForm.post(route('admin.testimonials.reject', selectedTestimonial.value.id), {
        preserveScroll: true,
        onSuccess: () => {
            rejectionModal.value = false;
            selectedTestimonial.value = null;
        },
    });
};

const toggleActive = (id) => {
    router.post(route('admin.testimonials.toggle-active', id), {}, {
        preserveScroll: true,
    });
};

const deleteTestimonial = (id) => {
    if (confirm('¿Estás seguro de eliminar este testimonio?')) {
        router.delete(route('admin.testimonials.destroy', id), {
            preserveScroll: true,
        });
    }
};

const getStatusBadge = (status) => {
    const badges = {
        pending: { class: 'bg-yellow-100 text-yellow-800', label: 'Pendiente' },
        approved: { class: 'bg-green-100 text-green-800', label: 'Aprobado' },
        rejected: { class: 'bg-red-100 text-red-800', label: 'Rechazado' },
    };
    return badges[status] || { class: 'bg-gray-100 text-gray-800', label: status };
};

const getSourceBadge = (source) => {
    const badges = {
        admin: { class: 'bg-blue-100 text-blue-800', label: 'Admin' },
        coach: { class: 'bg-purple-100 text-purple-800', label: 'Coach' },
    };
    return badges[source] || { class: 'bg-gray-100 text-gray-800', label: source };
};
</script>

<template>
    <Head title="Gestión de Testimonios" />

    <AdminLayout>
        <template #header>
            <div class="flex items-center justify-between">
                <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
                    Gestión de Testimonios
                </h2>
                <Link 
                    :href="route('admin.landing.index')"
                    class="text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white"
                >
                    ← Volver a Landing
                </Link>
            </div>
        </template>

        <div class="py-12">
            <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-6">
                
                <!-- Pending alert -->
                <div 
                    v-if="counts.pending > 0" 
                    class="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-xl p-4"
                >
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 rounded-full bg-yellow-100 dark:bg-yellow-800 flex items-center justify-center">
                            <svg class="w-5 h-5 text-yellow-600 dark:text-yellow-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                            </svg>
                        </div>
                        <div>
                            <p class="font-semibold text-yellow-800 dark:text-yellow-300">
                                {{ counts.pending }} {{ counts.pending === 1 ? 'testimonio pendiente' : 'testimonios pendientes' }} de revisión
                            </p>
                            <p class="text-sm text-yellow-700 dark:text-yellow-400">
                                Los coaches han enviado testimonios que esperan tu aprobación.
                            </p>
                        </div>
                    </div>
                </div>

                <!-- Filters -->
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-4">
                    <div class="flex flex-wrap gap-2">
                        <button
                            v-for="f in filters"
                            :key="f.value"
                            @click="setFilter(f.value)"
                            :class="[
                                'px-4 py-2 rounded-lg text-sm font-medium transition-colors',
                                filter === f.value
                                    ? 'bg-indigo-600 text-white'
                                    : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'
                            ]"
                        >
                            {{ f.label }}
                            <span 
                                v-if="f.count !== undefined" 
                                class="ml-1.5 px-1.5 py-0.5 text-xs rounded-full"
                                :class="filter === f.value ? 'bg-indigo-500' : 'bg-gray-200 dark:bg-gray-600'"
                            >
                                {{ f.count }}
                            </span>
                        </button>
                    </div>
                </div>

                <!-- Testimonials List -->
                <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden">
                    <div class="divide-y divide-gray-200 dark:divide-gray-700">
                        <div 
                            v-for="testimonial in testimonials" 
                            :key="testimonial.id"
                            class="p-6 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
                        >
                            <div class="flex items-start gap-4">
                                <!-- Avatar -->
                                <div class="flex-shrink-0">
                                    <img 
                                        v-if="testimonial.avatar" 
                                        :src="testimonial.avatar" 
                                        :alt="testimonial.name"
                                        class="w-14 h-14 rounded-full object-cover border-2 border-gray-200 dark:border-gray-600"
                                    />
                                    <div 
                                        v-else 
                                        class="w-14 h-14 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center text-white font-bold text-xl"
                                    >
                                        {{ testimonial.name.charAt(0) }}
                                    </div>
                                </div>

                                <!-- Content -->
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center gap-2 mb-2">
                                        <h4 class="font-semibold text-gray-900 dark:text-white">
                                            {{ testimonial.name }}
                                        </h4>
                                        <span 
                                            class="px-2 py-0.5 text-xs font-medium rounded-full"
                                            :class="getStatusBadge(testimonial.status).class"
                                        >
                                            {{ getStatusBadge(testimonial.status).label }}
                                        </span>
                                        <span 
                                            class="px-2 py-0.5 text-xs font-medium rounded-full"
                                            :class="getSourceBadge(testimonial.source).class"
                                        >
                                            {{ getSourceBadge(testimonial.source).label }}
                                        </span>
                                    </div>

                                    <p class="text-sm text-gray-500 dark:text-gray-400 mb-2">
                                        {{ testimonial.role }}
                                        <template v-if="testimonial.coach">
                                            • <a :href="`mailto:${testimonial.coach.email}`" class="text-indigo-600 hover:underline">{{ testimonial.coach.email }}</a>
                                        </template>
                                    </p>

                                    <!-- Rating -->
                                    <div class="flex gap-0.5 mb-3">
                                        <svg 
                                            v-for="i in 5" 
                                            :key="i"
                                            class="w-4 h-4"
                                            :class="i <= testimonial.rating ? 'text-yellow-400' : 'text-gray-300'"
                                            fill="currentColor" 
                                            viewBox="0 0 20 20"
                                        >
                                            <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                                        </svg>
                                    </div>

                                    <!-- Quote -->
                                    <blockquote class="text-gray-700 dark:text-gray-300 italic border-l-4 border-gray-200 dark:border-gray-600 pl-4 mb-4">
                                        "{{ testimonial.content }}"
                                    </blockquote>

                                    <!-- Rejection reason -->
                                    <div 
                                        v-if="testimonial.status === 'rejected' && testimonial.rejection_reason"
                                        class="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3 mb-4"
                                    >
                                        <p class="text-sm text-red-700 dark:text-red-400">
                                            <strong>Motivo:</strong> {{ testimonial.rejection_reason }}
                                        </p>
                                    </div>

                                    <!-- Meta -->
                                    <div class="flex items-center gap-4 text-xs text-gray-500 dark:text-gray-400">
                                        <span v-if="testimonial.submitted_at">
                                            Enviado: {{ testimonial.submitted_at }}
                                        </span>
                                        <span v-if="testimonial.reviewed_at">
                                            Revisado: {{ testimonial.reviewed_at }}
                                        </span>
                                    </div>
                                </div>

                                <!-- Actions -->
                                <div class="flex flex-col gap-2">
                                    <template v-if="testimonial.status === 'pending'">
                                        <button
                                            @click="approveTestimonial(testimonial.id)"
                                            class="px-4 py-2 bg-green-600 text-white text-sm font-medium rounded-lg hover:bg-green-700 transition-colors"
                                        >
                                            Aprobar
                                        </button>
                                        <button
                                            @click="openRejectModal(testimonial)"
                                            class="px-4 py-2 bg-red-600 text-white text-sm font-medium rounded-lg hover:bg-red-700 transition-colors"
                                        >
                                            Rechazar
                                        </button>
                                    </template>

                                    <template v-else-if="testimonial.status === 'approved'">
                                        <button
                                            @click="toggleActive(testimonial.id)"
                                            :class="[
                                                'px-4 py-2 text-sm font-medium rounded-lg transition-colors',
                                                testimonial.is_active
                                                    ? 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600'
                                                    : 'bg-indigo-600 text-white hover:bg-indigo-700'
                                            ]"
                                        >
                                            {{ testimonial.is_active ? 'Ocultar' : 'Mostrar' }}
                                        </button>
                                    </template>

                                    <button
                                        @click="deleteTestimonial(testimonial.id)"
                                        class="px-4 py-2 text-red-600 hover:text-red-700 text-sm font-medium hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
                                    >
                                        Eliminar
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- Empty state -->
                        <div v-if="testimonials.length === 0" class="p-12 text-center">
                            <svg class="w-16 h-16 mx-auto mb-4 text-gray-300 dark:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                            </svg>
                            <p class="text-gray-500 dark:text-gray-400">
                                No hay testimonios en esta categoría.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Rejection Modal -->
        <Teleport to="body">
            <div 
                v-if="rejectionModal" 
                class="fixed inset-0 z-50 overflow-y-auto"
                @click.self="rejectionModal = false"
            >
                <div class="flex min-h-full items-center justify-center p-4">
                    <div class="fixed inset-0 bg-black/50" @click="rejectionModal = false"></div>
                    
                    <div class="relative bg-white dark:bg-gray-800 rounded-2xl shadow-xl max-w-md w-full p-6">
                        <h3 class="text-lg font-bold text-gray-900 dark:text-white mb-4">
                            Rechazar Testimonio
                        </h3>

                        <p class="text-sm text-gray-600 dark:text-gray-400 mb-4">
                            ¿Estás seguro de rechazar el testimonio de <strong>{{ selectedTestimonial?.name }}</strong>?
                        </p>

                        <form @submit.prevent="submitRejection">
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                    Motivo del rechazo (opcional)
                                </label>
                                <textarea
                                    v-model="rejectionForm.reason"
                                    rows="3"
                                    class="w-full rounded-lg border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 focus:border-indigo-500 focus:ring-indigo-500"
                                    placeholder="Ej: El contenido no cumple con nuestras directrices..."
                                ></textarea>
                            </div>

                            <div class="flex justify-end gap-3">
                                <button
                                    type="button"
                                    @click="rejectionModal = false"
                                    class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                                >
                                    Cancelar
                                </button>
                                <button
                                    type="submit"
                                    :disabled="rejectionForm.processing"
                                    class="px-4 py-2 bg-red-600 text-white text-sm font-medium rounded-lg hover:bg-red-700 disabled:opacity-50 transition-colors"
                                >
                                    Confirmar Rechazo
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </Teleport>
    </AdminLayout>
</template>
