import { useState, useEffect } from 'react';
import { CheckCircle, XCircle } from 'lucide-react';
import { Badge } from '../../components/ui/Badge';
import { Button } from '../../components/ui/Button';
import { Modal } from '../../components/ui/Modal';
import { api } from '../../api/client';

interface QueueItem {
  id: string;
  title: string;
  description: string;
  price: number;
  category: string;
  condition: string;
  location: string;
  createdAt: string;
  seller: { id: string; fullName: string; avatar?: string; email: string };
  images: { url: string; order: number }[];
}

export function AdminModerationPage() {
  const [queue, setQueue] = useState<QueueItem[]>([]);
  const [total, setTotal] = useState(0);
  const [rejectId, setRejectId] = useState<string | null>(null);
  const [rejectReason, setRejectReason] = useState('');

  const fetchQueue = () => {
    api.get<{ data: QueueItem[]; total: number }>('/admin/moderation/queue')
      .then((res) => { setQueue(res.data); setTotal(res.total); })
      .catch(() => {});
  };

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

  const handleApprove = async (id: string) => {
    await api.post(`/admin/listings/${id}/approve`);
    fetchQueue();
  };

  const handleReject = async () => {
    if (!rejectId || !rejectReason) return;
    await api.post(`/admin/listings/${rejectId}/reject`, { reason: rejectReason });
    setRejectId(null);
    setRejectReason('');
    fetchQueue();
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Moderation Queue</h1>
        <Badge variant="warning" size="md">{total} pending</Badge>
      </div>

      {queue.length === 0 ? (
        <div className="bg-white rounded-xl border border-gray-200 p-12 text-center">
          <p className="text-gray-400">No listings pending review</p>
        </div>
      ) : (
        <div className="space-y-4">
          {queue.map((item) => (
            <div key={item.id} className="bg-white rounded-xl border border-gray-200 p-5">
              <div className="flex gap-5">
                <div className="w-32 h-32 rounded-lg bg-gray-100 overflow-hidden flex-shrink-0">
                  {item.images[0] ? (
                    <img src={item.images[0].url} className="w-full h-full object-cover" />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-4xl bg-gray-200" />
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <h3 className="font-semibold text-gray-900 text-lg">{item.title}</h3>
                  <p className="text-sm text-gray-500 mt-1">
                    ${item.price.toFixed(2)} · {item.category} · {item.condition.replace('_', ' ')}
                  </p>
                  <p className="text-sm text-gray-600 mt-2 line-clamp-2">{item.description}</p>
                  <p className="text-xs text-gray-400 mt-2">
                    By {item.seller.fullName} ({item.seller.email}) · {new Date(item.createdAt).toLocaleString()}
                  </p>
                </div>
                <div className="flex flex-col gap-2 flex-shrink-0">
                  <Button variant="outline" size="sm" onClick={() => handleApprove(item.id)}>
                    <CheckCircle className="w-4 h-4 mr-1 text-green-500" /> Approve
                  </Button>
                  <Button variant="danger" size="sm" onClick={() => setRejectId(item.id)}>
                    <XCircle className="w-4 h-4 mr-1" /> Reject
                  </Button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      <Modal isOpen={!!rejectId} onClose={() => setRejectId(null)} title="Reject Listing" size="sm">
        <p className="text-sm text-gray-500 mb-4">Provide a reason for rejection. The seller will be notified.</p>
        <textarea
          value={rejectReason}
          onChange={(e) => setRejectReason(e.target.value)}
          rows={3}
          placeholder="Reason for rejection..."
          className="w-full rounded-xl border border-gray-200 bg-white px-4 py-2.5 text-sm placeholder:text-gray-400 focus:border-primary-400 focus:ring-2 focus:ring-primary-100 focus:outline-none resize-none mb-4"
        />
        <div className="flex gap-3">
          <Button variant="secondary" className="flex-1" onClick={() => setRejectId(null)}>Cancel</Button>
          <Button variant="danger" className="flex-1" onClick={handleReject} disabled={!rejectReason}>Reject</Button>
        </div>
      </Modal>
    </div>
  );
}
