<script setup>
import { ref, computed, 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 { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { Skeleton } from '@/components/ui/skeleton'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'

const notes = ref([])
const loading = ref(true)
const activeFilter = ref('all')
const showModal = ref(false)
const saving = ref(false)
const form = ref({ id: '', title: '', content: '', category: 'note', pinned: false })

const catIcons = { note: '📝', doc: '📄', todo: '✅', announcement: '📢' }
const filters = [
  { key: 'all', label: 'Tất cả' },
  { key: 'pinned', label: '📌 Pinned' },
  { key: 'note', label: '📝 Note' },
  { key: 'doc', label: '📄 Doc' },
  { key: 'todo', label: '✅ Todo' },
  { key: 'announcement', label: '📢 Announcement' },
]

const filtered = computed(() => {
  let f = notes.value
  if (activeFilter.value === 'pinned') f = f.filter(n => n.pinned)
  else if (activeFilter.value !== 'all') f = f.filter(n => n.category === activeFilter.value)
  return [...f].sort((a, b) =>
    (a.pinned && !b.pinned ? -1 : !a.pinned && b.pinned ? 1 :
      new Date(b.updated_at || b.created_at) - new Date(a.updated_at || a.created_at))
  )
})

function fmtTime(iso) {
  if (!iso) return ''
  const d = new Date(iso), diff = (Date.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`
  return d.toLocaleDateString('vi-VN')
}

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

function openNew() {
  form.value = { id: '', title: '', content: '', category: 'note', pinned: false }
  showModal.value = true
}

function openEdit(n) {
  form.value = { id: n.id, title: n.title, content: n.content || '', category: n.category, pinned: n.pinned }
  showModal.value = true
}

async function save() {
  if (!form.value.title.trim()) return
  saving.value = true
  try {
    const { id, ...body } = form.value
    await fetch(id ? `/api/dashboard/notes/${id}` : '/api/dashboard/notes', {
      method: id ? 'PUT' : 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body)
    })
    showModal.value = false
    await load()
  } finally { saving.value = false }
}

async function togglePin(id) {
  await fetch(`/api/dashboard/notes/${id}/pin`, { method: 'PATCH' })
  await load()
}

async function del(id) {
  if (!confirm('Xóa note này?')) return
  await fetch(`/api/dashboard/notes/${id}`, { method: 'DELETE' })
  await load()
}

onMounted(load)
</script>

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

      <!-- Header -->
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-3xl font-bold tracking-tight text-foreground">Team Notes</h1>
          <p class="text-sm text-muted-foreground mt-1">Ghi chú nội bộ, tài liệu, việc cần làm</p>
        </div>
        <Button @click="openNew" class="gap-2">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5v14"/></svg>
          New Note
        </Button>
      </div>

      <Separator />

      <!-- Filters -->
      <div class="flex gap-2 flex-wrap">
        <button
          v-for="f in filters" :key="f.key"
          @click="activeFilter = f.key"
          :class="['px-3 py-1.5 rounded-full text-xs font-semibold border transition-all',
            activeFilter === f.key
              ? 'bg-primary text-primary-foreground border-primary shadow-sm'
              : 'bg-background text-muted-foreground border-border hover:border-foreground/30 hover:text-foreground']"
        >{{ f.label }}</button>
      </div>

      <!-- Grid -->
      <div class="grid grid-cols-3 gap-4">
        <!-- Skeletons -->
        <template v-if="loading">
          <Card v-for="i in 6" :key="i">
            <CardContent class="p-4 space-y-2">
              <Skeleton class="h-4 w-16" />
              <Skeleton class="h-5 w-3/4" />
              <Skeleton class="h-16 w-full" />
            </CardContent>
          </Card>
        </template>

        <!-- Empty -->
        <div v-else-if="!filtered.length" class="col-span-3 flex flex-col items-center justify-center py-20 text-muted-foreground border border-dashed border-border rounded-xl bg-muted/10">
          <svg xmlns="http://www.w3.org/2000/svg" width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="opacity-20 mb-3"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><line x1="16" x2="8" y1="13" y2="13"/><line x1="16" x2="8" y1="17" y2="17"/><line x1="10" x2="8" y1="9" y2="9"/></svg>
          <p class="text-sm font-medium text-foreground">Không có ghi chú nào</p>
        </div>

        <!-- Cards -->
        <Card v-else v-for="note in filtered" :key="note.id"
              :class="['group cursor-pointer hover:shadow-md transition-all hover:border-primary/30',
                note.pinned ? 'border-primary/30 bg-primary/5' : 'border-border']">
          <CardContent class="p-4">
            <div class="flex items-start justify-between mb-3">
              <Badge variant="secondary" class="text-[10px] px-1.5 py-0.5">
                {{ catIcons[note.category] || '📝' }} {{ note.category }}
              </Badge>
              <span v-if="note.pinned" class="text-primary opacity-60" title="Pinned">
                <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/></svg>
              </span>
            </div>
            <p class="font-bold text-sm text-foreground mb-1.5 truncate">{{ note.title }}</p>
            <p class="text-xs text-muted-foreground line-clamp-3 leading-relaxed">{{ note.content }}</p>
            <div class="flex items-center justify-between mt-4 pt-3 border-t border-border">
              <span class="text-[10px] text-muted-foreground/60 font-mono">{{ fmtTime(note.updated_at || note.created_at) }}</span>
              <div class="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                <Button variant="ghost" size="icon" class="h-6 w-6 text-muted-foreground hover:text-primary"
                        @click.stop="togglePin(note.id)">
                  <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" x2="12" y1="17" y2="22"/><path d="M5 17H2v-2l3-3V7a1 1 0 0 1 1-1h2v2h4V6h2a1 1 0 0 1 1 1v5l3 3v2h-3"/></svg>
                </Button>
                <Button variant="ghost" size="icon" class="h-6 w-6 text-muted-foreground hover:text-foreground"
                        @click.stop="openEdit(note)">
                  <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/></svg>
                </Button>
                <Button variant="ghost" size="icon" class="h-6 w-6 text-muted-foreground hover:text-destructive"
                        @click.stop="del(note.id)">
                  <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>

    <!-- Modal -->
    <Dialog v-model:open="showModal">
      <DialogContent class="max-w-md">
        <DialogHeader>
          <DialogTitle>{{ form.id ? '✏️ Edit Note' : '📝 New Note' }}</DialogTitle>
        </DialogHeader>
        <div class="space-y-4 py-2">
          <div>
            <Label class="text-xs mb-1 block">Tiêu đề *</Label>
            <Input v-model="form.title" placeholder="Tiêu đề..." />
          </div>
          <div>
            <Label class="text-xs mb-1 block">Nội dung</Label>
            <Textarea v-model="form.content" class="min-h-[120px]" placeholder="Nội dung ghi chú..." />
          </div>
          <div class="flex gap-4">
            <div class="flex-1">
              <Label class="text-xs mb-1 block">Loại</Label>
              <Select v-model="form.category">
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="note">📝 Note</SelectItem>
                  <SelectItem value="doc">📄 Doc</SelectItem>
                  <SelectItem value="todo">✅ Todo</SelectItem>
                  <SelectItem value="announcement">📢 Announcement</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div class="flex items-end gap-2">
              <input type="checkbox" v-model="form.pinned" id="pinCheck" class="accent-amber-600" />
              <Label for="pinCheck" class="text-xs cursor-pointer">📌 Pin</Label>
            </div>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" @click="showModal = false">Hủy</Button>
          <Button @click="save" :disabled="saving || !form.title.trim()">
            {{ saving ? 'Đang lưu...' : 'Lưu' }}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  </DashboardLayout>
</template>
