import { useState, useEffect, useCallback } from 'react';
import { DataTable } from '../../components/ui/DataTable';
import { Badge } from '../../components/ui/Badge';
import { api } from '../../api/client';

interface AdminListing {
  id: string;
  title: string;
  price: number;
  category: string;
  status: string;
  isFeatured: boolean;
  createdAt: string;
  viewCount: number;
  seller: { id: string; fullName: string; avatar?: string };
  images: { url: string }[];
  _count: { offers: number; favorites: number };
}

const TABS = ['ALL', 'PENDING_REVIEW', 'ACTIVE', 'SOLD', 'DELETED'];

export function AdminListingsPage() {
  const [listings, setListings] = useState<AdminListing[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [tab, setTab] = useState('ALL');

  const fetchListings = useCallback(async () => {
    const params = new URLSearchParams({ page: String(page), pageSize: '20' });
    if (search) params.set('search', search);
    if (tab !== 'ALL') params.set('status', tab);
    const res = await api.get<{ data: AdminListing[]; total: number }>(`/admin/listings?${params}`);
    setListings(res.data);
    setTotal(res.total);
  }, [page, search, tab]);

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

  const statusBadge = (status: string) => {
    const v = status === 'ACTIVE' ? 'success' : status === 'PENDING_REVIEW' ? 'warning' : status === 'SOLD' ? 'info' : 'error';
    return <Badge variant={v} size="sm">{status.replace('_', ' ')}</Badge>;
  };

  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-4">Listings</h1>
      <div className="flex gap-2 mb-4 flex-wrap">
        {TABS.map((t) => (
          <button
            key={t}
            onClick={() => { setTab(t); setPage(1); }}
            className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors cursor-pointer ${
              tab === t ? 'bg-primary-100 text-primary-700' : 'text-gray-500 hover:bg-gray-100'
            }`}
          >
            {t.replace('_', ' ')}
          </button>
        ))}
      </div>
      <DataTable
        columns={[
          {
            key: 'title',
            header: 'Listing',
            render: (l: AdminListing) => (
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-gray-100 overflow-hidden flex-shrink-0">
                  {l.images[0] ? <img src={l.images[0].url} className="w-full h-full object-cover" /> : <div className="w-full h-full bg-gray-200" />}
                </div>
                <div>
                  <p className="font-medium text-gray-900 truncate max-w-xs">{l.title}</p>
                  <p className="text-xs text-gray-400">{l.seller.fullName}</p>
                </div>
              </div>
            ),
          },
          { key: 'price', header: 'Price', render: (l: AdminListing) => `$${l.price.toFixed(2)}` },
          { key: 'status', header: 'Status', render: (l: AdminListing) => statusBadge(l.status) },
          { key: 'category', header: 'Category', render: (l: AdminListing) => l.category.replace('_', ' ') },
          { key: 'views', header: 'Views', render: (l: AdminListing) => l.viewCount },
          { key: 'createdAt', header: 'Created', render: (l: AdminListing) => new Date(l.createdAt).toLocaleDateString() },
        ]}
        data={listings}
        total={total}
        page={page}
        pageSize={20}
        onPageChange={setPage}
        searchValue={search}
        onSearch={(v) => { setSearch(v); setPage(1); }}
        searchPlaceholder="Search listings..."
      />
    </div>
  );
}
