<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 links = ref([])
const loading = ref(true)
const activeFilter = ref('all')
const showModal = ref(false)
const saving = ref(false)
const form = ref({ id: '', title: '', url: '', description: '', category: 'tool', icon: '', pinned: false })

const catColors = { tool: 'bg-blue-100 text-blue-700', doc: 'bg-purple-100 text-purple-700', ref: 'bg-green-100 text-green-700', other: 'bg-gray-100 text-gray-700' }
const filters = [
  { key: 'all', label: 'Tất cả' },
  { key: 'pinned', label: '📌 Pinned' },
  { key: 'tool', label: '🛠️ Tool' },
  { key: 'doc', label: '📄 Doc' },
  { key: 'ref', label: '🔗 Reference' },
]

const filtered = computed(() => {
  let f = links.value
  if (activeFilter.value === 'pinned') f = f.filter(l => l.pinned)
  else if (activeFilter.value !== 'all') f = f.filter(l => l.category === activeFilter.value)
  return [...f].sort((a, b) => (a.pinned && !b.pinned ? -1 : !a.pinned && b.pinned ? 1 : 0))
})

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

function openNew() {
  form.value = { id: '', title: '', url: '', description: '', category: 'tool', icon: '', pinned: false }
  showModal.value = true
}
function openEdit(l) {
  form.value = { id: l.id, title: l.title, url: l.url, description: l.description || '', category: l.category, icon: l.icon || '', pinned: l.pinned }
  showModal.value = true
}

async function save() {
  if (!form.value.title.trim() || !form.value.url.trim()) return
  saving.value = true
  try {
    const { id, ...body } = form.value
    await fetch(id ? `/api/dashboard/links/${id}` : '/api/dashboard/links', {
      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/links/${id}/pin`, { method: 'PATCH' })
  await load()
}
async function del(id) {
  if (!confirm('Xóa resource này?')) return
  await fetch(`/api/dashboard/links/${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-2xl font-black text-gray-900">🔗 Resources</h1>
          <p class="text-sm text-gray-500 mt-1">Links, tài liệu, công cụ hay dùng</p>
        </div>
        <div class="flex items-center gap-3">
          <Badge variant="secondary">{{ links.length }} links</Badge>
          <Button @click="openNew">+ Add Resource</Button>
        </div>
      </div>

      <Separator />

      <!-- Filters -->
      <div class="flex gap-2">
        <button v-for="f in filters" :key="f.key" @click="activeFilter = f.key"
          :class="['px-3 py-1.5 rounded-full text-xs font-medium transition-colors',
            activeFilter === f.key ? 'bg-amber-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200']">
          {{ f.label }}
        </button>
      </div>

      <!-- Grid -->
      <div class="grid grid-cols-2 gap-4">
        <template v-if="loading">
          <Card v-for="i in 4" :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-3 w-full" />
            </CardContent>
          </Card>
        </template>

        <div v-else-if="!filtered.length" class="col-span-2 text-center py-16 text-gray-400">
          <div class="text-4xl mb-3">🔗</div>
          <p class="text-sm">Chưa có resource nào.</p>
        </div>

        <Card v-else v-for="link in filtered" :key="link.id"
              :class="['group hover:shadow-md transition-all', link.pinned ? 'border-amber-300 bg-amber-50/40' : '']">
          <CardContent class="p-4">
            <div class="flex items-start gap-3">
              <div class="w-10 h-10 bg-gray-100 rounded-lg flex items-center justify-center text-lg shrink-0">
                {{ link.icon || '🔗' }}
              </div>
              <div class="flex-1 min-w-0">
                <div class="flex items-center gap-2 mb-1">
                  <span :class="['text-[10px] font-semibold px-1.5 py-0.5 rounded', catColors[link.category] || catColors.other]">
                    {{ link.category }}
                  </span>
                  <span v-if="link.pinned" class="text-xs">📌</span>
                </div>
                <p class="font-semibold text-sm text-gray-800 truncate">{{ link.title }}</p>
                <a :href="link.url" target="_blank"
                   class="text-xs text-amber-600 hover:underline truncate block">{{ link.url }}</a>
                <p v-if="link.description" class="text-xs text-gray-500 mt-1 line-clamp-2">{{ link.description }}</p>
              </div>
            </div>
            <div class="flex gap-1.5 mt-3 pt-2 border-t border-gray-100 opacity-0 group-hover:opacity-100 transition-opacity">
              <Button variant="outline" size="sm" class="h-7 text-xs gap-1" @click="window.open(link.url, '_blank')">↗ Mở</Button>
              <Button variant="ghost" size="sm" class="h-7 text-xs" @click="togglePin(link.id)">📌</Button>
              <Button variant="ghost" size="sm" class="h-7 text-xs" @click="openEdit(link)">✏️</Button>
              <Button variant="ghost" size="sm" class="h-7 text-xs text-red-500 hover:bg-red-50" @click="del(link.id)">🗑️</Button>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>

    <!-- Modal -->
    <Dialog v-model:open="showModal">
      <DialogContent class="max-w-md">
        <DialogHeader><DialogTitle>{{ form.id ? '✏️ Edit' : '🔗 Add Resource' }}</DialogTitle></DialogHeader>
        <div class="space-y-3 py-2">
          <div><Label class="text-xs mb-1 block">Tiêu đề *</Label><Input v-model="form.title" placeholder="Tên resource..." /></div>
          <div><Label class="text-xs mb-1 block">URL *</Label><Input v-model="form.url" placeholder="https://..." /></div>
          <div><Label class="text-xs mb-1 block">Mô tả</Label><Textarea v-model="form.description" class="min-h-[80px]" placeholder="Mô tả ngắn..." /></div>
          <div class="flex gap-3">
            <div class="flex-1">
              <Label class="text-xs mb-1 block">Category</Label>
              <Select v-model="form.category">
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="tool">🛠️ Tool</SelectItem>
                  <SelectItem value="doc">📄 Doc</SelectItem>
                  <SelectItem value="ref">🔗 Reference</SelectItem>
                  <SelectItem value="other">📦 Other</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div class="w-20"><Label class="text-xs mb-1 block">Icon</Label><Input v-model="form.icon" placeholder="🔗" /></div>
          </div>
          <div class="flex items-center gap-2">
            <input type="checkbox" v-model="form.pinned" id="pinCheck" class="accent-amber-600" />
            <Label for="pinCheck" class="text-xs cursor-pointer">📌 Pin lên đầu</Label>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" @click="showModal = false">Hủy</Button>
          <Button @click="save" :disabled="saving || !form.title.trim() || !form.url.trim()">{{ saving ? '...' : 'Lưu' }}</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  </DashboardLayout>
</template>
