<script setup>
import { ref, onMounted } from 'vue'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Card, CardContent } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Separator } from '@/components/ui/separator'
import { Skeleton } from '@/components/ui/skeleton'

const API = '/api/dashboard/changelog'
const entries = ref([])
const loading = ref(true)
const author = ref('Admin')
const content = ref('')
const posting = ref(false)

async function load() {
  loading.value = true
  try {
    const r = await fetch(API)
    const d = await r.json()
    entries.value = d.entries || []
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

async function add() {
  const c = content.value.trim()
  if (!c || posting.value) return
  posting.value = true
  try {
    await fetch(API, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ content: c, author: author.value || 'Admin' })
    })
    content.value = ''
    await load()
  } finally {
    posting.value = false
  }
}

async function del(id) {
  if (!confirm('Xóa ghi chú này?')) return
  await fetch(`${API}/${id}`, { method: 'DELETE' })
  await load()
}

function fmtTime(iso) {
  if (!iso) return ''
  const d = new Date(iso), now = new Date(), diff = (now - d) / 1000
  if (diff < 60) return 'vừa xong'
  if (diff < 3600) return `${Math.floor(diff / 60)} phút trước`
  if (diff < 86400) return `${Math.floor(diff / 3600)} giờ trước`
  if (diff < 604800) return `${Math.floor(diff / 86400)} ngày trước`
  return d.toLocaleDateString('vi-VN', { day: '2-digit', month: '2-digit', year: 'numeric' })
}

onMounted(load)
</script>

<template>
  <DashboardLayout>
    <div class="p-8 max-w-3xl space-y-6">

      <!-- Header -->
      <div>
        <h1 class="text-2xl font-black text-gray-900">📜 Changelog</h1>
        <p class="text-sm text-gray-500 mt-1">Lịch sử thay đổi chatbot & hệ thống</p>
      </div>

      <Separator />

      <!-- Add form -->
      <Card>
        <CardContent class="p-4">
          <div class="flex gap-2">
            <Input v-model="author" placeholder="Tên bạn" class="w-28 shrink-0" />
            <Input
              v-model="content"
              placeholder="Bạn đã thay đổi gì? VD: Sửa prompt thêm rule..."
              @keydown.enter="add"
            />
            <Button @click="add" :disabled="posting || !content.trim()">
              {{ posting ? '...' : '+ Thêm' }}
            </Button>
          </div>
        </CardContent>
      </Card>

      <!-- Timeline -->
      <div class="space-y-0">
        <!-- Loading -->
        <template v-if="loading">
          <div v-for="i in 4" :key="i" class="flex gap-4 pb-6">
            <div class="flex flex-col items-center">
              <Skeleton class="h-3 w-3 rounded-full" />
              <Skeleton class="w-0.5 flex-1 mt-1" />
            </div>
            <div class="flex-1 pb-2 space-y-1.5">
              <Skeleton class="h-3 w-32" />
              <Skeleton class="h-10 w-full" />
            </div>
          </div>
        </template>

        <!-- Empty -->
        <div v-else-if="!entries.length" class="text-center py-16 text-gray-400">
          <div class="text-4xl mb-3">📋</div>
          <p class="text-sm">Chưa có ghi chú nào. Thêm dòng đầu tiên!</p>
        </div>

        <!-- Entries timeline -->
        <div v-else v-for="(entry, i) in entries" :key="entry.id" class="flex gap-4 pb-6 group">
          <!-- Timeline line -->
          <div class="flex flex-col items-center">
            <div class="h-3 w-3 rounded-full bg-amber-500 shrink-0 mt-1 ring-2 ring-amber-100"></div>
            <div v-if="i < entries.length - 1" class="w-0.5 bg-gray-100 flex-1 mt-1"></div>
          </div>

          <!-- Content -->
          <div class="flex-1 min-w-0 pb-2">
            <div class="flex items-center justify-between gap-2 mb-1.5">
              <div class="flex items-center gap-2">
                <span class="text-xs font-semibold text-gray-700">{{ entry.author || 'Admin' }}</span>
                <span class="text-xs text-gray-400">·</span>
                <span class="text-xs text-gray-400">{{ fmtTime(entry.created_at) }}</span>
              </div>
              <Button
                variant="ghost" size="sm"
                class="h-6 px-2 text-xs text-red-400 hover:text-red-600 hover:bg-red-50 opacity-0 group-hover:opacity-100 transition-opacity"
                @click="del(entry.id)"
              >🗑️</Button>
            </div>
            <p class="text-sm text-gray-700 leading-relaxed">{{ entry.content }}</p>
          </div>
        </div>
      </div>

    </div>
  </DashboardLayout>
</template>
