import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { DataTable } from '../../components/ui/DataTable';
import { Badge } from '../../components/ui/Badge';
import { Avatar } from '../../components/ui/Avatar';
import { api } from '../../api/client';

interface AdminUser {
  id: string;
  email: string;
  fullName: string;
  avatar?: string;
  role: string;
  isBanned: boolean;
  createdAt: string;
  _count: { listings: number; sentOffers: number; reports: number };
}

export function AdminUsersPage() {
  const navigate = useNavigate();
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');

  const fetchUsers = useCallback(async () => {
    const params = new URLSearchParams({ page: String(page), pageSize: '20' });
    if (search) params.set('search', search);
    const res = await api.get<{ data: AdminUser[]; total: number }>(`/admin/users?${params}`);
    setUsers(res.data);
    setTotal(res.total);
  }, [page, search]);

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

  const roleBadge = (role: string) => {
    const variant = role === 'SUPER_ADMIN' ? 'error' : role === 'ADMIN' ? 'warning' : role === 'MODERATOR' ? 'info' : 'default';
    return <Badge variant={variant} size="sm">{role}</Badge>;
  };

  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-6">Users</h1>
      <DataTable
        columns={[
          {
            key: 'user',
            header: 'User',
            render: (u: AdminUser) => (
              <div className="flex items-center gap-3">
                <Avatar name={u.fullName} src={u.avatar} size="sm" />
                <div>
                  <p className="font-medium text-gray-900">{u.fullName}</p>
                  <p className="text-xs text-gray-400">{u.email}</p>
                </div>
              </div>
            ),
          },
          { key: 'role', header: 'Role', render: (u: AdminUser) => roleBadge(u.role) },
          {
            key: 'status',
            header: 'Status',
            render: (u: AdminUser) => u.isBanned
              ? <Badge variant="error" size="sm">Banned</Badge>
              : <Badge variant="success" size="sm">Active</Badge>,
          },
          { key: 'listings', header: 'Listings', render: (u: AdminUser) => u._count.listings },
          { key: 'createdAt', header: 'Joined', render: (u: AdminUser) => new Date(u.createdAt).toLocaleDateString() },
        ]}
        data={users}
        total={total}
        page={page}
        pageSize={20}
        onPageChange={setPage}
        searchValue={search}
        onSearch={(v) => { setSearch(v); setPage(1); }}
        searchPlaceholder="Search users..."
        actions={(u: AdminUser) => (
          <button
            onClick={() => navigate(`/admin/users/${u.id}`)}
            className="text-sm text-primary-600 hover:text-primary-700 font-medium cursor-pointer"
          >
            View
          </button>
        )}
      />
    </div>
  );
}
