<template>
  <div class="space-y-6">
    <!-- Header / Summary Bar -->
    <div class="flex items-center justify-between bg-card/40 p-4 rounded-2xl border border-border/50">
      <h2 class="text-sm font-bold uppercase tracking-widest text-primary ml-2">{{ t('admin.reviews.title') }}</h2>
      <div class="text-xs font-bold text-muted-foreground uppercase tracking-widest bg-muted/30 px-4 py-2 rounded-xl border border-border/50">
        {{ t("admin.total") }}: {{ total }}
      </div>
    </div>

    <!-- Empty State -->
    <div v-if="!loading && reviews.length === 0" class="flex flex-col items-center justify-center py-20 bg-card/40 border border-border/50 rounded-3xl opacity-50">
      <MessageSquare class="w-12 h-12 text-muted-foreground/20 mb-4" />
      <p class="text-sm text-muted-foreground">{{ t('admin.reviews.noReviews') }}</p>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="flex items-center justify-center py-20">
      <Loader2 class="w-8 h-8 text-primary animate-spin" />
    </div>

    <!-- Table Layout -->
    <div v-if="!loading && reviews.length > 0" class="bg-card/40 backdrop-blur-md border border-border/50 rounded-3xl overflow-hidden shadow-xl">
      <div class="overflow-x-auto">
        <table class="w-full text-left border-collapse">
          <thead>
            <tr class="bg-muted/30 border-b border-border/50">
              <th class="p-4 text-[10px] font-bold uppercase tracking-wider">{{ t("admin.labels.user") }}</th>
              <th class="p-4 text-[10px] font-bold uppercase tracking-wider">{{ t("admin.reviews.rating") }}</th>
              <th class="p-4 text-[10px] font-bold uppercase tracking-wider">{{ t("admin.reviews.content") }}</th>
              <th class="p-4 text-[10px] font-bold uppercase tracking-wider">{{ t("admin.reviews.status") }}</th>
              <th class="p-4 text-[10px] font-bold uppercase tracking-wider">{{ t("admin.labels.registered") }}</th>
              <th class="p-4 text-[10px] font-bold uppercase tracking-wider text-right">{{ t("admin.labels.actions") }}</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-border/30">
            <tr v-for="review in reviews" :key="review.id" class="hover:bg-primary/5 transition-colors group/row">
              <td class="p-4">
                <div class="flex flex-col">
                  <span class="text-sm font-bold">{{ review.first_name }} {{ review.last_name }}</span>
                  <span class="text-[10px] text-muted-foreground opacity-50">{{ review.email }}</span>
                </div>
              </td>
              <td class="p-4">
                <div class="flex items-center gap-1">
                  <span class="text-sm font-bold">{{ review.rating }}</span>
                  <span class="text-[10px] text-muted-foreground">/ 5</span>
                </div>
              </td>
              <td class="p-4">
                <p class="text-xs text-foreground/80 max-w-md line-clamp-2 italic">
                  "{{ review.review_text }}"
                </p>
              </td>
              <td class="p-4">
                <span 
                  :class="[
                    'px-2 py-0.5 rounded-full text-[9px] font-bold uppercase border',
                    review.review_approved ? 'bg-emerald-500/10 text-emerald-500 border-emerald-500/20' : 'bg-amber-500/10 text-amber-500 border-amber-500/20'
                  ]"
                >
                  {{ review.review_approved ? t('admin.reviews.approved') : t('admin.reviews.pending') }}
                </span>
              </td>
              <td class="p-4 text-[10px] text-muted-foreground font-bold uppercase">
                {{ new Date(review.created_at).toLocaleDateString() }}
              </td>
              <td class="p-4 text-right">
                <div class="flex items-center justify-end gap-2">
                  <Button 
                    variant="outline" 
                    size="sm"
                    :class="[
                      'h-7 px-3 text-[10px] font-bold uppercase rounded-lg transition-all',
                      review.review_approved 
                        ? 'border-amber-500/30 text-amber-500 hover:bg-amber-500/10' 
                        : 'border-emerald-500/30 text-emerald-500 hover:bg-emerald-500/10'
                    ]"
                    @click="handleToggleApprove(review)"
                  >
                    {{ review.review_approved ? t('admin.reviews.hide') || 'Hide' : t('admin.reviews.approve') }}
                  </Button>
                  <Button 
                    variant="outline" 
                    size="sm"
                    class="h-7 px-3 text-[10px] font-bold uppercase rounded-lg border-rose-500/30 text-rose-500 hover:bg-rose-500/10"
                    @click="handleDelete(review.id)"
                  >
                    {{ t('admin.reviews.delete') }}
                  </Button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Pagination -->
    <div v-if="total > size" class="flex items-center justify-center gap-2 py-4">
       <Button v-for="p in Math.ceil(total / size)" :key="p" 
         variant="outline"
         @click="page = p" 
         :class="['w-8 h-8 rounded-lg font-bold text-xs transition-all p-0', page === p ? 'bg-primary text-white shadow-glow border-primary' : 'bg-card border border-border/50 text-muted-foreground hover:border-primary/50']">
         {{ p }}
       </Button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { MessageSquare, Loader2 } from 'lucide-vue-next';
import { adminGetReviews, approveOrderReview, adminUpdateOrder } from '@/lib/api';
import Button from '@/components/ui/button.vue';
import { toast } from 'vue-sonner';

const { t } = useI18n();
const reviews = ref<any[]>([]);
const total = ref(0);
const page = ref(1);
const size = 50;
const loading = ref(true);

const fetchReviews = async () => {
  loading.value = true;
  try {
    const res = await adminGetReviews(page.value, size);
    reviews.value = res.reviews;
    total.value = res.total;
  } catch (err) {
    console.error(err);
    toast.error(t('errors.fetch_failed'));
  } finally {
    loading.value = false;
  }
};

const handleToggleApprove = async (review: any) => {
  try {
    const newStatus = !review.review_approved;
    await adminUpdateOrder(review.id, {
      review_approved: newStatus
    });
    toast.success(newStatus ? t('admin.reviews.approvedSuccess') : t('admin.reviews.hiddenSuccess'));
    fetchReviews();
  } catch (err) {
    toast.error(t('errors.update_failed'));
  }
};

const handleDelete = async (orderId: number) => {
  if (!confirm(t('admin.reviews.confirmDelete'))) return;
  try {
    await adminUpdateOrder(orderId, {
      review_text: "",
      rating: 0,
      review_approved: false
    });
    toast.success(t('admin.reviews.deletedSuccess'));
    fetchReviews();
  } catch (err) {
    toast.error(t('errors.delete_failed'));
  }
};

watch(page, fetchReviews);
onMounted(fetchReviews);
</script>
