'use client'

import { useState, useEffect, useCallback } from 'react'
import { Globe, Eye, Trash2, ExternalLink, Loader2, Shield, ShieldAlert } from 'lucide-react'
import { toast } from 'sonner'

interface PublishedNote {
  id: string
  title: string | null
  publicSlug: string | null
  publishedAt: string | null
  user: { name: string | null }
  _count?: { reports: number }
}

export default function PublishedAdminPage() {
  const [notes, setNotes] = useState<PublishedNote[]>([])
  const [loading, setLoading] = useState(true)

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const res = await fetch('/api/admin/published')
      const data = await res.json()
      setNotes(data.notes || [])
    } catch { toast.error('Erreur') }
    finally { setLoading(false) }
  }, [])

  useEffect(() => { load() }, [load])

  const forceUnpublish = async (noteId: string) => {
    try {
      const res = await fetch('/api/admin/published', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ noteId }),
      })
      if (res.ok) {
        toast.success('Note dépubliée')
        load()
      } else { toast.error('Erreur') }
    } catch { toast.error('Erreur') }
  }

  return (
    <div className="p-6 max-w-5xl mx-auto" dir="auto">
      <div className="flex items-center gap-2 mb-6">
        <Shield size={20} className="text-brand-accent" />
        <h1 className="text-xl font-semibold">Pages publiées</h1>
        <span className="text-sm text-muted-foreground">({notes.length})</span>
      </div>

      {loading ? (
        <div className="flex justify-center py-12"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>
      ) : notes.length === 0 ? (
        <p className="text-sm text-muted-foreground text-center py-12">Aucune note publiée.</p>
      ) : (
        <div className="space-y-2">
          {notes.map(note => (
            <div key={note.id} className="flex items-center gap-3 p-3.5 rounded-xl border border-border bg-card hover:shadow-sm transition-all">
              <div className="w-9 h-9 rounded-lg bg-green-50 dark:bg-green-950/20 flex items-center justify-center shrink-0">
                <Globe size={16} className="text-green-600 dark:text-green-400" />
              </div>
              <div className="flex-1 min-w-0">
                <div className="text-sm font-medium truncate">{note.title || 'Sans titre'}</div>
                <div className="text-[11px] text-muted-foreground">
                  par {note.user?.name || 'Inconnu'} · {note.publishedAt ? new Date(note.publishedAt).toLocaleDateString() : ''}
                  {note._count?.reports ? (
                    <span className="ml-2 inline-flex items-center gap-1 text-red-500 font-medium">
                      <ShieldAlert size={10} /> {note._count.reports} signalement{note._count.reports > 1 ? 's' : ''}
                    </span>
                  ) : null}
                </div>
              </div>
              <div className="flex items-center gap-1 shrink-0">
                <a href={`/p/${note.publicSlug}`} target="_blank" rel="noopener noreferrer"
                  className="p-2 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors" title="Voir">
                  <ExternalLink size={15} />
                </a>
                <button onClick={() => forceUnpublish(note.id)}
                  className="p-2 rounded-lg hover:bg-red-50 dark:hover:bg-red-950/20 text-muted-foreground hover:text-red-500 transition-colors" title="Dépublier">
                  <Trash2 size={15} />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
