<script setup>
import { ref, onMounted } from 'vue'
import DashboardLayout from '../layouts/DashboardLayout.vue'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { Skeleton } from '@/components/ui/skeleton'

const API = '/api/dashboard/notes'
const newNote = ref('')
const notes = ref([])
const loading = ref(true)
const posting = ref(false)

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

async function post() {
  const text = newNote.value.trim()
  if (!text || posting.value) return
  posting.value = true
  try {
    await fetch(API, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title: '', content: text, category: 'note', pinned: false })
    })
    newNote.value = ''
    await load()
  } finally {
    posting.value = false
  }
}

async function pin(id, current) {
  await fetch(`${API}/${id}/pin`, { method: 'PATCH' })
  await load()
}

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">📋 Kế hoạch phát triển</h1>
        <p class="text-sm text-gray-500 mt-1">Ghi chép kế hoạch version, ý tưởng, thay đổi hệ thống</p>
      </div>

      <Separator />

      <!-- Composer -->
      <Card>
        <CardContent class="p-4 space-y-3">
          <Textarea
            v-model="newNote"
            placeholder="Viết kế hoạch, ghi chú, ý tưởng..."
            class="min-h-[100px] resize-none"
            @keydown.ctrl.enter="post"
          />
          <div class="flex items-center justify-between">
            <span class="text-xs text-gray-400">Ctrl+Enter để lưu nhanh</span>
            <Button @click="post" :disabled="posting || !newNote.trim()" size="sm">
              {{ posting ? 'Đang lưu...' : '💾 Lưu' }}
            </Button>
          </div>
        </CardContent>
      </Card>

      <!-- Feed -->
      <div class="space-y-3">
        <!-- Loading skeletons -->
        <template v-if="loading">
          <Card v-for="i in 3" :key="i">
            <CardContent class="p-4 space-y-2">
              <Skeleton class="h-4 w-24" />
              <Skeleton class="h-12 w-full" />
            </CardContent>
          </Card>
        </template>

        <!-- Empty -->
        <div v-else-if="!notes.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>

        <!-- Notes -->
        <Card v-else v-for="note in notes" :key="note.id"
              :class="note.pinned ? 'border-amber-300 bg-amber-50/50' : ''">
          <CardContent class="p-4">
            <div class="flex items-start justify-between gap-3">
              <div class="flex-1 min-w-0">
                <div class="flex items-center gap-2 mb-2">
                  <span class="text-xs text-gray-400">{{ fmtTime(note.created_at) }}</span>
                  <Badge v-if="note.pinned" variant="outline"
                         class="h-4 px-1.5 text-[10px] border-amber-400 text-amber-700 bg-amber-50">
                    📌 PIN
                  </Badge>
                </div>
                <p class="text-sm text-gray-800 whitespace-pre-wrap leading-relaxed">{{ note.content }}</p>
              </div>
              <div class="flex gap-1.5 shrink-0">
                <Button variant="ghost" size="sm" class="h-7 px-2 text-xs"
                        @click="pin(note.id, note.pinned)">
                  {{ note.pinned ? 'Bỏ pin' : '📌' }}
                </Button>
                <Button variant="ghost" size="sm" class="h-7 px-2 text-xs text-red-500 hover:text-red-700 hover:bg-red-50"
                        @click="del(note.id)">
                  🗑️
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

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