'use client';
import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import Topbar from '@/components/Topbar';
import api from '@/lib/api';

export default function UserDetailPage() {
  const { id }  = useParams();
  const [user, setUser]     = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.get(`/admin/users/${id}`)
      .then(r => setUser(r.data.data))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, [id]);

  const updateStatus = async (status) => {
    if (!confirm(`¿Cambiar estado a "${status}"?`)) return;
    await api.patch(`/admin/users/${id}/status`, { status });
    setUser(prev => ({ ...prev, status }));
  };

  if (loading) return <><Topbar title="Usuario" /><main className="p-6 text-gray-400">Cargando…</main></>;
  if (!user)   return <><Topbar title="Usuario" /><main className="p-6 text-gray-400">No encontrado</main></>;

  return (
    <>
      <Topbar title={`Usuario — ${user.name}`} />
      <main className="flex-1 p-6 overflow-auto">
        <div className="max-w-2xl">
          <div className="bg-white rounded-xl border border-gray-200 p-6 mb-4">
            <div className="flex items-center gap-4 mb-6">
              <div className="w-14 h-14 rounded-full bg-primary flex items-center justify-center text-white font-bold text-xl">
                {user.name[0]}
              </div>
              <div>
                <h2 className="text-lg font-bold text-gray-800">{user.name}</h2>
                <p className="text-gray-500 text-sm">@{user.username}</p>
              </div>
              <span className={`ml-auto text-xs font-bold px-3 py-1 rounded-full ${
                user.status === 'active' ? 'bg-green-100 text-green-700' :
                user.status === 'suspended' ? 'bg-yellow-100 text-yellow-700' :
                'bg-red-100 text-red-700'}`}>
                {user.status}
              </span>
            </div>

            <div className="grid grid-cols-2 gap-4 text-sm">
              {[
                ['Email',    user.email],
                ['Teléfono', user.phone || '—'],
                ['Ciudad',   user.city  || '—'],
                ['Estado',   user.state || '—'],
                ['Vendedor', user.is_seller ? 'Sí' : 'No'],
                ['Registro', new Date(user.created_at).toLocaleDateString('es-MX')],
              ].map(([label, val]) => (
                <div key={label} className="bg-gray-50 rounded-lg p-3">
                  <div className="text-xs text-gray-400 font-semibold uppercase mb-1">{label}</div>
                  <div className="font-semibold text-gray-800">{val}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="bg-white rounded-xl border border-gray-200 p-5">
            <h3 className="font-bold text-gray-800 mb-3">Acciones</h3>
            <div className="flex gap-3 flex-wrap">
              <button onClick={() => updateStatus('active')}
                className="bg-green-100 text-green-700 font-semibold text-sm px-4 py-2 rounded-lg hover:bg-green-200">
                ✅ Activar
              </button>
              <button onClick={() => updateStatus('suspended')}
                className="bg-yellow-100 text-yellow-700 font-semibold text-sm px-4 py-2 rounded-lg hover:bg-yellow-200">
                ⏸️ Suspender
              </button>
              <button onClick={() => updateStatus('banned')}
                className="bg-red-100 text-red-700 font-semibold text-sm px-4 py-2 rounded-lg hover:bg-red-200">
                🚫 Banear
              </button>
            </div>
          </div>
        </div>
      </main>
    </>
  );
}
