'use client';
import { useState, useEffect } from 'react';
import { Check, X, Trash2, Loader2, MessageSquare } from 'lucide-react';
import api from '@/lib/api';
import toast from 'react-hot-toast';
import { timeAgo } from '@/utils';

const TABS = ['pending','approved','spam','rejected'];

export default function AdminComments() {
  const [comments, setComments] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [status, setStatus] = useState('pending');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const fetchComments = async () => {
    setLoading(true); setError('');
    try { const r = await api.get('/comments/queue', { params: { page, limit: 20, status } }); setComments(r.data.data || r.data.comments || []); setTotal(r.data.meta?.total || r.data.total || 0); }
    catch { setError('Failed to load comments.'); toast.error('Failed to load'); } finally { setLoading(false); }
  };
  useEffect(() => { fetchComments(); }, [page, status]);

  const moderate = async (id: number, action: 'approve'|'reject'|'spam') => {
    try { await api.patch(`/comments/${id}/moderate`, { action }); toast.success(`Comment ${action}d`); fetchComments(); }
    catch { toast.error('Action failed'); }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Delete this comment? This cannot be undone.')) return;
    try { await api.delete(`/comments/${id}`); toast.success('Deleted'); fetchComments(); }
    catch { toast.error('Delete failed'); }
  };

  const totalPages = Math.ceil(total/20);

  return (
    <div>
      <div className="mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <h1 className="font-serif text-2xl font-extrabold text-body">Comments</h1>
        <div className="flex flex-wrap gap-2">
          {TABS.map(s=>(
            <button key={s} onClick={()=>{setStatus(s);setPage(1);}} className={`rounded-md px-3 py-1.5 text-xs font-medium capitalize transition ${
              status===s ? 'bg-brand-900 text-white' : 'border border-surface bg-surface text-muted hover:border-brand-500 hover:text-body'
            }`}>{s}</button>
          ))}
        </div>
      </div>

      <div className="space-y-3">
        {loading ? (
          <div className="flex items-center justify-center gap-2 rounded-card border border-surface bg-surface p-12 text-muted"><Loader2 size={18} className="animate-spin"/> Loading comments…</div>
        ) : error ? (
          <div className="rounded-card border border-surface bg-surface p-12 text-center">
            <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
            <button onClick={fetchComments} className="mt-3 rounded-md border border-surface px-4 py-2 text-sm font-medium text-body hover:bg-surface-sunken">Retry</button>
          </div>
        ) : comments.length === 0 ? (
          <div className="flex flex-col items-center gap-2 rounded-card border border-surface bg-surface p-12 text-center text-muted">
            <MessageSquare size={28} className="text-muted"/>
            <p className="text-sm">No {status} comments.</p>
          </div>
        ) : (
          comments.map((c:any) => (
            <div key={c.id} className="rounded-card border border-surface bg-surface p-4">
              <div className="flex items-start justify-between gap-4">
                <div className="min-w-0 flex-1">
                  <div className="mb-1 flex flex-wrap items-center gap-2">
                    <span className="text-sm font-semibold text-body">{c.authorName || c.user?.name || 'Anonymous'}</span>
                    {c.authorEmail && <span className="text-xs text-muted">{c.authorEmail}</span>}
                    <span className="text-xs text-muted">·</span>
                    <span className="text-xs text-muted">{timeAgo(c.createdAt)}</span>
                  </div>
                  <p className="text-sm text-body">{c.content}</p>
                  {c.article && <p className="mt-1 text-xs text-muted">On: {c.article.title}</p>}
                </div>
                <div className="flex items-center gap-1">
                  {status !== 'approved' && <button onClick={()=>moderate(c.id,'approve')} title="Approve" className="rounded-md p-1.5 text-emerald-600 transition hover:bg-emerald-50 dark:hover:bg-emerald-900/30"><Check size={16}/></button>}
                  {status !== 'spam' && <button onClick={()=>moderate(c.id,'spam')} title="Mark spam" className="rounded-md p-1.5 text-amber-600 transition hover:bg-amber-50 dark:hover:bg-amber-900/30"><X size={16}/></button>}
                  <button onClick={()=>handleDelete(c.id)} title="Delete" className="rounded-md p-1.5 text-red-500 transition hover:bg-red-50 dark:hover:bg-red-900/30"><Trash2 size={16}/></button>
                </div>
              </div>
            </div>
          ))
        )}
      </div>

      {!loading && !error && totalPages>1 && <div className="mt-6 flex justify-center gap-1">{Array.from({length:totalPages},(_,i)=>i+1).map(p=>(<button key={p} onClick={()=>setPage(p)} className={`rounded-md px-3 py-1 text-xs font-medium transition ${p===page?'bg-brand-900 text-white':'border border-surface bg-surface text-muted hover:border-brand-500 hover:text-body'}`}>{p}</button>))}</div>}
    </div>
  );
}
