<template>
  <div>
    <div class="pb-5 border-b border-gray-200 sm:flex sm:items-center sm:justify-between">
      <h3 class="text-lg leading-6 font-medium text-gray-900">
        {{ $t('comments.title') }}
      </h3>
      <div class="mt-3 sm:mt-0 sm:ml-4">
        <div class="flex space-x-3">
          <select
            v-model="platformFilter"
            class="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm rounded-md"
          >
            <option value="all">{{ $t('comments.allPlatforms') }}</option>
            <option value="TikTok">TikTok</option>
            <option value="YouTube">YouTube</option>
            <option value="Instagram">Instagram</option>
          </select>
          <button
            @click="refreshComments"
            class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
          >
            <svg class="-ml-1 mr-2 h-5 w-5 text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z" clip-rule="evenodd" />
            </svg>
            {{ $t('comments.refresh') }}
          </button>
        </div>
      </div>
    </div>

    <div class="mt-6">
      <div v-if="loading" class="flex justify-center">
        <svg class="animate-spin -ml-1 mr-3 h-10 w-10 text-primary-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
      </div>
      <div v-else>
        <div class="bg-white shadow overflow-hidden sm:rounded-md">
          <ul class="divide-y divide-gray-200">
            <li v-if="filteredComments.length === 0" class="px-4 py-4 sm:px-6">
              <p class="text-sm text-gray-500">{{ $t('comments.noCommentsFound') }}</p>
            </li>
            <li v-for="(comment, index) in filteredComments" :key="index" class="px-4 py-4 sm:px-6">
              <div class="flex space-x-3">
                <div class="flex-shrink-0">
                  <div class="h-10 w-10 rounded-full bg-gray-200"></div>
                </div>
                <div class="min-w-0 flex-1">
                  <div class="flex items-center justify-between">
                    <p class="text-sm font-medium text-gray-900">
                      {{ $t('comments.anonymousUser') }}
                    </p>
                    <div class="flex items-center">
                      <span :class="[
                        comment.platform === 'TikTok' ? 'bg-blue-100 text-blue-800' : 
                        comment.platform === 'YouTube' ? 'bg-red-100 text-red-800' : 
                        'bg-pink-100 text-pink-800',
                        'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium mr-2'
                      ]">
                        {{ comment.platform }}
                      </span>
                      <span class="text-sm text-gray-500">
                        {{ formatDate(comment.created_at) }}
                      </span>
                    </div>
                  </div>
                  <p class="mt-1 text-sm text-gray-500">
                    {{ comment.comment_text }}
                  </p>
                  <div class="mt-2 text-sm">
                    <span class="font-medium text-gray-900">
                      {{ $t('comments.on') }}: {{ comment.videoTitle }}
                    </span>
                  </div>
                  <div class="mt-2 flex">
                    <button
                      @click="showReplyForm(comment)"
                      class="text-sm text-primary-600 hover:text-primary-500"
                    >
                      {{ $t('comments.reply') }}
                    </button>
                    <span class="mx-2 text-gray-500">•</span>
                    <button
                      @click="deleteComment(comment)"
                      class="text-sm text-red-600 hover:text-red-500"
                    >
                      {{ $t('comments.delete') }}
                    </button>
                  </div>
                  
                  <!-- Reply Form -->
                  <div v-if="comment.showReplyForm" class="mt-4">
                    <div class="flex space-x-3">
                      <div class="flex-shrink-0">
                        <div class="h-8 w-8 rounded-full bg-primary-200 flex items-center justify-center text-primary-600">
                          {{ userInitials }}
                        </div>
                      </div>
                      <div class="min-w-0 flex-1">
                        <form @submit.prevent="submitReply(comment)">
                          <div>
                            <textarea
                              v-model="comment.replyText"
                              rows="2"
                              class="shadow-sm block w-full focus:ring-primary-500 focus:border-primary-500 sm:text-sm border border-gray-300 rounded-md"
                              :placeholder="$t('comments.addYourReply')"
                            ></textarea>
                          </div>
                          <div class="mt-3 flex items-center justify-between">
                            <div class="flex-shrink-0">
                              <button
                                type="submit"
                                class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md shadow-sm text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
                              >
                                {{ $t('comments.reply') }}
                              </button>
                              <button
                                type="button"
                                @click="cancelReply(comment)"
                                class="ml-2 inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500"
                              >
                                {{ $t('comments.cancel') }}
                              </button>
                            </div>
                          </div>
                        </form>
                      </div>
                    </div>
                  </div>
                  
                  <!-- Replies -->
                  <div v-if="comment.replies && comment.replies.length > 0" class="mt-4 space-y-4">
                    <div v-for="(reply, replyIndex) in comment.replies" :key="replyIndex" class="flex space-x-3">
                      <div class="flex-shrink-0">
                        <div class="h-8 w-8 rounded-full bg-primary-200 flex items-center justify-center text-primary-600">
                          {{ userInitials }}
                        </div>
                      </div>
                      <div class="min-w-0 flex-1 bg-gray-50 rounded-lg p-3">
                        <div class="flex items-center justify-between">
                          <p class="text-sm font-medium text-gray-900">
                            {{ $t('comments.you') }}
                          </p>
                          <p class="text-sm text-gray-500">
                            {{ formatDate(reply.created_at) }}
                          </p>
                        </div>
                        <p class="mt-1 text-sm text-gray-500">
                          {{ reply.reply_text }}
                        </p>
                        <div class="mt-2">
                          <button
                            @click="deleteReply(comment, replyIndex)"
                            class="text-sm text-red-600 hover:text-red-500"
                          >
                            {{ $t('comments.delete') }}
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </li>
          </ul>
        </div>
        
        <!-- Pagination -->
        <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6 mt-4">
          <div class="flex-1 flex justify-between sm:hidden">
            <button
              @click="prevPage"
              :disabled="currentPage === 1"
              class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {{ $t('comments.previous') }}
            </button>
            <button
              @click="nextPage"
              :disabled="currentPage === totalPages"
              class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {{ $t('comments.next') }}
            </button>
          </div>
          <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
            <div>
              <p class="text-sm text-gray-700">
                {{ $t('comments.showing') }}
                <span class="font-medium">{{ (currentPage - 1) * pageSize + 1 }}</span>
                {{ $t('comments.to') }}
                <span class="font-medium">{{ Math.min(currentPage * pageSize, totalComments) }}</span>
                {{ $t('comments.of') }}
                <span class="font-medium">{{ totalComments }}</span>
                {{ $t('comments.results') }}
              </p>
            </div>
            <div>
              <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                <button
                  @click="prevPage"
                  :disabled="currentPage === 1"
                  class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <span class="sr-only">{{ $t('comments.previous') }}</span>
                  <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                    <path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd" />
                  </svg>
                </button>
                <button
                  v-for="page in paginationRange"
                  :key="page"
                  @click="goToPage(page)"
                  :class="[
                    page === currentPage
                      ? 'z-10 bg-primary-50 border-primary-500 text-primary-600'
                      : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50',
                    'relative inline-flex items-center px-4 py-2 border text-sm font-medium'
                  ]"
                >
                  {{ page }}
                </button>
                <button
                  @click="nextPage"
                  :disabled="currentPage === totalPages"
                  class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <span class="sr-only">{{ $t('comments.next') }}</span>
                  <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                    <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />
                  </svg>
                </button>
              </nav>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '../stores/auth';
import axios from 'axios';

export default {
  name: 'Comments',
  setup() {
    const { t, locale } = useI18n();
    const authStore = useAuthStore();
    const loading = ref(true);
    const comments = ref([]);
    const platformFilter = ref('all');
    const currentPage = ref(1);
    const pageSize = 10;
    
    const user = computed(() => authStore.getUser);
    
    const userInitials = computed(() => {
      if (!user.value || !user.value.name) return '';
      
      const nameParts = user.value.name.split(' ');
      if (nameParts.length === 1) {
        return nameParts[0].charAt(0).toUpperCase();
      }
      
      return (nameParts[0].charAt(0) + nameParts[nameParts.length - 1].charAt(0)).toUpperCase();
    });
    
    const filteredComments = computed(() => {
      if (platformFilter.value === 'all') {
        return comments.value;
      }
      
      return comments.value.filter(comment => comment.platform === platformFilter.value);
    });
    
    const totalComments = computed(() => filteredComments.value.length);
    
    const totalPages = computed(() => Math.ceil(totalComments.value / pageSize));
    
    const paginationRange = computed(() => {
      const range = [];
      const maxPagesToShow = 5;
      
      if (totalPages.value <= maxPagesToShow) {
        // Show all pages
        for (let i = 1; i <= totalPages.value; i++) {
          range.push(i);
        }
      } else {
        // Show a subset of pages
        let startPage = Math.max(1, currentPage.value - Math.floor(maxPagesToShow / 2));
        let endPage = startPage + maxPagesToShow - 1;
        
        if (endPage > totalPages.value) {
          endPage = totalPages.value;
          startPage = Math.max(1, endPage - maxPagesToShow + 1);
        }
        
        for (let i = startPage; i <= endPage; i++) {
          range.push(i);
        }
      }
      
      return range;
    });
    
    const fetchComments = async () => {
      loading.value = true;
      try {
        // In a real app, this would be an API call
        // const response = await axios.get('/api/comments');
        // comments.value = response.data;
        
        // For demo purposes, we'll use mock data
        setTimeout(() => {
          comments.value = [
            {
              id: 1,
              platform: 'TikTok',
              comment_text: 'This is so relaxing! I love your content.',
              created_at: new Date(Date.now() - 3600000), // 1 hour ago
              videoTitle: 'Soft Whispering ASMR',
              showReplyForm: false,
              replyText: '',
              replies: [
                {
                  id: 1,
                  reply_text: 'Thank you so much! I\'m glad you enjoyed it.',
                  created_at: new Date(Date.now() - 1800000) // 30 minutes ago
                }
              ]
            },
            {
              id: 2,
              platform: 'YouTube',
              comment_text: 'The sound quality is amazing! What microphone do you use?',
              created_at: new Date(Date.now() - 7200000), // 2 hours ago
              videoTitle: 'Binaural ASMR Experience',
              showReplyForm: false,
              replyText: '',
              replies: []
            },
            {
              id: 3,
              platform: 'Instagram',
              comment_text: 'I fall asleep to this every night. Thank you!',
              created_at: new Date(Date.now() - 86400000), // 1 day ago
              videoTitle: 'Sleep-Inducing ASMR',
              showReplyForm: false,
              replyText: '',
              replies: [
                {
                  id: 2,
                  reply_text: 'That\'s wonderful to hear! Sweet dreams!',
                  created_at: new Date(Date.now() - 43200000) // 12 hours ago
                }
              ]
            },
            {
              id: 4,
              platform: 'YouTube',
              comment_text: 'Could you do more tapping videos? They\'re my favorite!',
              created_at: new Date(Date.now() - 172800000), // 2 days ago
              videoTitle: 'Tapping & Scratching Sounds',
              showReplyForm: false,
              replyText: '',
              replies: []
            },
            {
              id: 5,
              platform: 'TikTok',
              comment_text: 'Your videos help me with my anxiety. Thank you!',
              created_at: new Date(Date.now() - 259200000), // 3 days ago
              videoTitle: 'Calming ASMR for Anxiety',
              showReplyForm: false,
              replyText: '',
              replies: [
                {
                  id: 3,
                  reply_text: 'I\'m so happy to hear that my videos help you. Take care!',
                  created_at: new Date(Date.now() - 172800000) // 2 days ago
                }
              ]
            }
          ];
          
          // Add more mock comments for pagination testing
          for (let i = 6; i <= 25; i++) {
            comments.value.push({
              id: i,
              platform: ['TikTok', 'YouTube', 'Instagram'][Math.floor(Math.random() * 3)],
              comment_text: `This is a mock comment #${i} for pagination testing.`,
              created_at: new Date(Date.now() - (i * 3600000)), // i hours ago
              videoTitle: `Mock Video #${i}`,
              showReplyForm: false,
              replyText: '',
              replies: []
            });
          }
          
          loading.value = false;
        }, 1000);
      } catch (error) {
        console.error('Error fetching comments:', error);
        loading.value = false;
      }
    };
    
    const refreshComments = () => {
      fetchComments();
    };
    
    const showReplyForm = (comment) => {
      comment.showReplyForm = true;
    };
    
    const cancelReply = (comment) => {
      comment.showReplyForm = false;
      comment.replyText = '';
    };
    
    const submitReply = async (comment) => {
      if (!comment.replyText.trim()) return;
      
      try {
        // In a real app, this would be an API call
        // await axios.post(`/api/comments/${comment.id}/replies`, { text: comment.replyText });
        
        // For demo purposes, we'll just add it to the comment's replies
        if (!comment.replies) {
          comment.replies = [];
        }
        
        comment.replies.push({
          id: Date.now(), // Use timestamp as a temporary ID
          reply_text: comment.replyText,
          created_at: new Date()
        });
        
        // Reset the form
        comment.showReplyForm = false;
        comment.replyText = '';
      } catch (error) {
        console.error('Error submitting reply:', error);
      }
    };
    
    const deleteComment = async (comment) => {
      if (!confirm('Are you sure you want to delete this comment?')) return;
      
      try {
        // In a real app, this would be an API call
        // await axios.delete(`/api/comments/${comment.id}`);
        
        // For demo purposes, we'll just remove it from the comments array
        const index = comments.value.findIndex(c => c.id === comment.id);
        if (index !== -1) {
          comments.value.splice(index, 1);
        }
      } catch (error) {
        console.error('Error deleting comment:', error);
      }
    };
    
    const deleteReply = async (comment, replyIndex) => {
      if (!confirm('Are you sure you want to delete this reply?')) return;
      
      try {
        // In a real app, this would be an API call
        // await axios.delete(`/api/comments/${comment.id}/replies/${comment.replies[replyIndex].id}`);
        
        // For demo purposes, we'll just remove it from the replies array
        comment.replies.splice(replyIndex, 1);
      } catch (error) {
        console.error('Error deleting reply:', error);
      }
    };
    
    const formatDate = (date) => {
      if (!date) return '';
      
      const d = new Date(date);
      return d.toLocaleDateString(locale.value, {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    };
    
    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--;
      }
    };
    
    const nextPage = () => {
      if (currentPage.value < totalPages.value) {
        currentPage.value++;
      }
    };
    
    const goToPage = (page) => {
      currentPage.value = page;
    };
    
    onMounted(() => {
      fetchComments();
    });
    
    return {
      loading,
      comments,
      platformFilter,
      currentPage,
      pageSize,
      userInitials,
      filteredComments,
      totalComments,
      totalPages,
      paginationRange,
      refreshComments,
      showReplyForm,
      cancelReply,
      submitReply,
      deleteComment,
      deleteReply,
      formatDate,
      prevPage,
      nextPage,
      goToPage
    };
  }
};
</script> 