'use client';

import { useState, useEffect, useCallback } from 'react';
import { MessageSquare, Trash2, CheckCircle, XCircle } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';

export function AdminCommunity() {
  const [posts, setPosts] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchPosts = useCallback(async () => {
    try { const r = await fetch('/api/admin/community'); const d = await r.json(); if (d.success) setPosts(d.posts || []); } catch { }
    finally { setLoading(false); }
  }, []);
  useEffect(() => { fetchPosts(); }, [fetchPosts]);

  const toggleApproved = async (id: string, cur: boolean) => {
    try { await fetch('/api/admin/community', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id, isApproved: !cur }) }); fetchPosts(); } catch { }
  };
  const deletePost = async (id: string) => {
    try { await fetch('/api/admin/community', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id }) }); fetchPosts(); } catch { }
  };

  if (loading) return <div className="flex items-center justify-center py-20"><span className="h-8 w-8 animate-spin rounded-full border-4 border-orange-500 border-t-transparent" /></div>;

  return (
    <div className="space-y-4">
      <p className="text-sm text-muted-foreground">{posts.length} community posts</p>
      <div className="grid gap-4 sm:grid-cols-2">
        {posts.map((p) => (
          <Card key={p.id} className="border-0 shadow-sm"><CardContent className="p-4">
            <div className="flex items-start justify-between gap-3">
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-1"><Badge className={`text-[10px] border-0 ${p.isApproved ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400' : 'bg-amber-50 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400'}`}>{p.isApproved ? 'Approved' : 'Pending'}</Badge></div>
                <p className="text-sm font-medium">{p.title}</p>
                <p className="text-xs text-muted-foreground mt-1 line-clamp-2">{p.content?.slice(0, 120)}</p>
                <p className="text-[10px] text-muted-foreground mt-2">by {p.author?.name || 'Unknown'} &middot; {new Date(p.createdAt).toLocaleDateString()}</p>
              </div>
              <div className="flex gap-1">
                <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => toggleApproved(p.id, p.isApproved)}>{p.isApproved ? <XCircle className="h-3.5 w-3.5 text-amber-500" /> : <CheckCircle className="h-3.5 w-3.5 text-emerald-500" />}</Button>
                <AlertDialog><AlertDialogTrigger asChild><Button variant="ghost" size="icon" className="h-7 w-7"><Trash2 className="h-3.5 w-3.5 text-destructive" /></Button></AlertDialogTrigger>
                  <AlertDialogContent><AlertDialogHeader><AlertDialogTitle>Delete Post</AlertDialogTitle><AlertDialogDescription>Delete this community post?</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction onClick={() => deletePost(p.id)} className="bg-destructive text-destructive-foreground">Delete</AlertDialogAction></AlertDialogFooter></AlertDialogContent>
                </AlertDialog>
              </div>
            </div>
          </CardContent></Card>
        ))}
        {posts.length === 0 && <div className="col-span-full py-16 text-center"><MessageSquare className="mx-auto h-12 w-12 text-slate-300" strokeWidth={1.5} /><p className="mt-3 text-sm text-muted-foreground">No community posts found</p></div>}
      </div>
    </div>
  );
}
