<script setup>
import { useForm } from '@inertiajs/vue3';
import { ref } from 'vue';
import PrimaryButton from '@/Components/PrimaryButton.vue';

const props = defineProps({
    comments: {
        type: Array,
        default: () => [],
    },
    commentableId: Number,
    commentableType: String,
});

const isExpanded = ref(false);

const form = useForm({
    content: '',
    commentable_id: props.commentableId,
    commentable_type: props.commentableType,
});

const submit = () => {
    form.post(route('comments.store'), {
        preserveScroll: true,
        onSuccess: () => {
            form.reset('content');
        },
    });
};
</script>

<template>
    <div class="mt-4 border-t border-gray-100 dark:border-gray-700 pt-4">
        <div class="flex items-center justify-between mb-2">
            <h4 class="text-xs font-bold uppercase text-gray-400">Commentaires ({{ comments.length }})</h4>
            <button @click="isExpanded = !isExpanded" class="text-xs text-blue-500 hover:underline">
                {{ isExpanded ? 'Masquer' : 'Afficher' }}
            </button>
        </div>

        <div v-if="isExpanded" class="space-y-4">
            <div v-for="comment in comments" :key="comment.id" class="flex space-x-3">
                <div class="flex-shrink-0">
                    <div class="h-8 w-8 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center text-xs font-bold text-gray-500">
                        {{ comment.user.name.charAt(0) }}
                    </div>
                </div>
                <div class="flex-1 bg-gray-50 dark:bg-gray-900/50 p-3 rounded-lg text-sm">
                    <div class="flex items-center justify-between mb-1">
                        <span class="font-bold text-gray-900 dark:text-gray-100">{{ comment.user.name }}</span>
                        <span class="text-[10px] text-gray-400">{{ new Date(comment.created_at).toLocaleString() }}</span>
                    </div>
                    <p class="text-gray-700 dark:text-gray-300 whitespace-pre-wrap">{{ comment.content }}</p>
                </div>
            </div>

            <form @submit.prevent="submit" class="mt-4">
                <div>
                    <textarea 
                        v-model="form.content" 
                        placeholder="Ajouter un commentaire..." 
                        class="w-full text-sm border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 focus:border-blue-500 rounded-md shadow-sm"
                        rows="2"
                        required
                    ></textarea>
                </div>
                <div class="mt-2 flex justify-end">
                    <PrimaryButton :class="{ 'opacity-25': form.processing }" :disabled="form.processing" class="!px-3 !py-1 !text-[10px]">
                        Publier
                    </PrimaryButton>
                </div>
            </form>
        </div>
    </div>
</template>
