'use client';
import { useState, useEffect, useCallback } from 'react';
import { reviewsApi } from '@/lib/api-client';

interface Review {
  id: string; productId: string; userId: string; orderId: string;
  rating: number; title: string; body: string; status: string; createdAt: string;
}

const STATUS_LABELS: Record<string, string> = { pending: 'Pendiente', published: 'Publicada', rejected: 'Rechazada' };
const STATUS_CLS: Record<string, string> = {
  pending: 'bg-amber-100 text-amber-700',
  published: 'bg-green-100 text-green-700',
  rejected: 'bg-red-100 text-red-700',
};

function Stars({ n }: { n: number }) {
  return (
    <span className="text-amber-400 text-sm">
      {'★'.repeat(n)}{'☆'.repeat(5 - n)}
    </span>
  );
}

export default function ReviewsPage() {
  const [items, setItems] = useState<Review[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [filter, setFilter] = useState<string>('');

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const d = await reviewsApi.listAdmin({ status: filter || undefined, limit: 50 }) as { items: Review[]; total: number };
      setItems(d.items ?? []);
      setTotal(d.total ?? 0);
    } catch (e) { setError(e instanceof Error ? e.message : 'Error'); }
    finally { setLoading(false); }
  }, [filter]);

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

  const moderate = async (id: string, status: 'published' | 'rejected') => {
    try {
      await reviewsApi.moderate(id, status);
      load();
    } catch (e) { alert(e instanceof Error ? e.message : 'Error'); }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div><h1 className="text-2xl font-bold text-gray-900">Reseñas</h1><p className="text-sm text-gray-500 mt-0.5">{total} reseñas pendientes de moderación</p></div>
        <div className="flex gap-2">
          {['', 'pending', 'published', 'rejected'].map(s => (
            <button key={s} onClick={() => setFilter(s)} className={`px-3 py-1.5 rounded-lg text-xs font-medium ${filter === s ? 'bg-[#2D6A4F] text-white' : 'bg-white border border-gray-300 text-gray-600 hover:bg-gray-50'}`}>
              {s ? STATUS_LABELS[s] : 'Todas'}
            </button>
          ))}
        </div>
      </div>

      <div className="space-y-4">
        {loading ? <div className="p-12 text-center text-gray-400">Cargando...</div> :
         error ? <div className="text-center text-red-600">{error}</div> :
         items.length === 0 ? <div className="p-12 text-center text-gray-400">No hay reseñas</div> :
         items.map(r => (
           <div key={r.id} className="bg-white border border-gray-200 rounded-xl p-5">
             <div className="flex items-start justify-between mb-3">
               <div>
                 <Stars n={r.rating} />
                 <p className="font-semibold text-gray-900 text-sm mt-1">{r.title}</p>
                 <p className="text-xs text-gray-400 mt-0.5">{new Date(r.createdAt).toLocaleString('es-ES')}</p>
               </div>
               <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${STATUS_CLS[r.status] ?? 'bg-gray-100 text-gray-600'}`}>{STATUS_LABELS[r.status] ?? r.status}</span>
             </div>
             <p className="text-sm text-gray-600 leading-relaxed mb-4">{r.body}</p>
             {r.status === 'pending' && (
               <div className="flex gap-3">
                 <button onClick={() => moderate(r.id, 'published')} className="px-4 py-2 bg-[#2D6A4F] hover:bg-[#1B4332] text-white text-xs font-semibold rounded-lg">✓ Publicar</button>
                 <button onClick={() => moderate(r.id, 'rejected')} className="px-4 py-2 border border-red-200 text-red-600 hover:bg-red-50 text-xs font-semibold rounded-lg">✕ Rechazar</button>
               </div>
             )}
             {r.status !== 'pending' && (
               <button onClick={() => moderate(r.id, r.status === 'published' ? 'rejected' : 'published')} className="text-xs text-gray-400 hover:text-gray-600">
                 {r.status === 'published' ? 'Despublicar' : 'Aprobar'}
               </button>
             )}
           </div>
         ))
        }
      </div>
    </div>
  );
}
