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

export default function UsersPage() {
  const [users, setUsers]     = useState([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch]   = useState('');
  const [status, setStatus]   = useState('');
  const [page, setPage]       = useState(1);
  const limit = 20;

  const load = () => {
    setLoading(true);
    api.get('/admin/users', { params: { search, status, page, limit } })
      .then(r => setUsers(r.data.data))
      .catch(console.error)
      .finally(() => setLoading(false));
  };

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

  const handleSearch = (e) => { e.preventDefault(); setPage(1); load(); };

  const updateStatus = async (id, newStatus) => {
    await api.patch(`/admin/users/${id}/status`, { status: newStatus });
    load();
  };

  return (
    <div className="space-y-4">
      {/* Filters */}
      <form onSubmit={handleSearch} className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex flex-col sm:flex-row gap-3">
        <input type="text" placeholder="Buscar por nombre o email…" value={search}
          onChange={e => setSearch(e.target.value)}
          className="flex-1 border border-gray-200 rounded-xl px-4 py-2.5 text-sm outline-none focus:border-primary" />
        <select value={status} onChange={e => setStatus(e.target.value)}
          className="border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none bg-white">
          <option value="">Todos los estados</option>
          <option value="active">Activo</option>
          <option value="suspended">Suspendido</option>
          <option value="banned">Baneado</option>
        </select>
        <button type="submit" className="bg-primary text-white font-semibold text-sm px-6 py-2.5 rounded-xl hover:opacity-90 transition">
          Buscar
        </button>
      </form>

      {/* Table */}
      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm min-w-[700px]">
            <thead className="bg-gray-50 border-b border-gray-100">
              <tr>
                {['ID','Nombre','Email','Ciudad','Vendedor','Estado','Registro','Acción'].map(h => (
                  <th key={h} className="px-4 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {loading ? (
                <tr><td colSpan={8} className="text-center py-12 text-gray-400">Cargando…</td></tr>
              ) : users.length === 0 ? (
                <tr><td colSpan={8} className="text-center py-12 text-gray-400">Sin usuarios</td></tr>
              ) : users.map(u => (
                <tr key={u.id} className="hover:bg-blue-50/30 transition-colors">
                  <td className="px-4 py-3 text-gray-400 text-xs">{u.id}</td>
                  <td className="px-4 py-3">
                    <p className="font-semibold text-gray-800">{u.name}</p>
                    <p className="text-xs text-gray-400">@{u.username}</p>
                  </td>
                  <td className="px-4 py-3 text-xs text-gray-500">{u.email}</td>
                  <td className="px-4 py-3 text-xs text-gray-500">{u.city || '—'}</td>
                  <td className="px-4 py-3">
                    {u.is_seller
                      ? <span className="inline-flex items-center text-xs font-semibold px-2.5 py-1 rounded-full bg-blue-100 text-blue-700">Sí</span>
                      : <span className="inline-flex items-center text-xs font-semibold px-2.5 py-1 rounded-full bg-gray-100 text-gray-500">No</span>}
                  </td>
                  <td className="px-4 py-3">
                    <span className={`inline-flex items-center text-xs font-semibold px-2.5 py-1 rounded-full ${
                      u.status === 'active' ? 'bg-emerald-100 text-emerald-700' :
                      u.status === 'suspended' ? 'bg-amber-100 text-amber-700' : 'bg-red-100 text-red-700'}`}>
                      {u.status}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-xs text-gray-400 whitespace-nowrap">{new Date(u.created_at).toLocaleDateString('es-MX')}</td>
                  <td className="px-4 py-3">
                    <select value={u.status} onChange={e => updateStatus(u.id, e.target.value)}
                      className="text-xs border border-gray-200 rounded-lg px-2 py-1 bg-white outline-none focus:border-primary">
                      <option value="active">Activo</option>
                      <option value="suspended">Suspender</option>
                      <option value="banned">Banear</option>
                    </select>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Pagination */}
      <div className="flex items-center justify-between">
        <span className="text-xs text-gray-400">Página {page}</span>
        <div className="flex gap-2">
          <button onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1}
            className="px-4 py-2 text-xs rounded-xl border border-gray-200 disabled:opacity-40 hover:bg-gray-50 transition font-medium">← Anterior</button>
          <button onClick={() => setPage(p => p + 1)} disabled={users.length < limit}
            className="px-4 py-2 text-xs rounded-xl border border-gray-200 disabled:opacity-40 hover:bg-gray-50 transition font-medium">Siguiente →</button>
        </div>
      </div>
    </div>
  );
}
