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

const statConfig = [
  { key: 'users',                label: 'Total Usuarios',          gradient: 'from-blue-500 to-blue-600' },
  { key: 'sellers',              label: 'Vendedores activos',       gradient: 'from-violet-500 to-violet-600' },
  { key: 'requirements',        label: 'Requerimientos',           gradient: 'from-teal-500 to-teal-600' },
  { key: 'active_subscriptions',label: 'Suscripciones activas',    gradient: 'from-orange-500 to-orange-600' },
];

export default function DashboardPage() {
  const [stats, setStats]     = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.get('/admin/stats')
      .then(r => setStats(r.data.data))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  return (
    <div className="space-y-6">
      {/* Stat cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {loading
          ? Array(4).fill(0).map((_, i) => <div key={i} className="h-28 rounded-2xl bg-gray-200 animate-pulse" />)
          : statConfig.map(s => (
              <StatCard key={s.key} label={s.label} value={stats?.[s.key]} gradient={s.gradient} />
            ))
        }
      </div>

      {/* Content row */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Quick links */}
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
          <h3 className="font-bold text-gray-800 text-base mb-4">Accesos rápidos</h3>
          <div className="space-y-2">
            {[
              { label: 'Gestionar usuarios',          href: '/users',         color: 'bg-blue-50 text-blue-600' },
              { label: 'Ver requerimientos',          href: '/requirements',  color: 'bg-teal-50 text-teal-600' },
              { label: 'Gestionar planes',            href: '/plans',         color: 'bg-violet-50 text-violet-600' },
              { label: 'Ver suscripciones activas',  href: '/subscriptions', color: 'bg-orange-50 text-orange-600' },
              { label: 'Gestionar categorías',        href: '/categories',    color: 'bg-emerald-50 text-emerald-600' },
              { label: 'Ver logs de admin',           href: '/logs',          color: 'bg-gray-50 text-gray-600' },
            ].map(l => (
              <a key={l.href} href={l.href}
                className="flex items-center justify-between px-4 py-3 rounded-xl hover:bg-gray-50 border border-gray-100 transition-colors group">
                <span className="text-sm font-medium text-gray-700">{l.label}</span>
                <svg className="w-4 h-4 text-gray-300 group-hover:text-primary transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7"/>
                </svg>
              </a>
            ))}
          </div>
        </div>

        {/* Platform summary */}
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
          <h3 className="font-bold text-gray-800 text-base mb-4">Resumen de la plataforma</h3>
          <div className="space-y-4">
            {[
              { label: 'Total propuestas enviadas',        value: stats?.offers,          color: 'bg-blue-500' },
              { label: 'Tratos completados',               value: stats?.completed_deals, color: 'bg-emerald-500' },
              { label: 'Suscripciones activas',            value: stats?.active_subscriptions, color: 'bg-violet-500' },
              { label: 'Vendedores registrados',           value: stats?.sellers,         color: 'bg-orange-500' },
            ].map(item => (
              <div key={item.label}>
                <div className="flex justify-between items-center mb-1.5">
                  <span className="text-sm text-gray-600">{item.label}</span>
                  <span className="text-sm font-bold text-gray-800">{loading ? '…' : (item.value ?? 0)}</span>
                </div>
                <div className="h-1.5 bg-gray-100 rounded-full overflow-hidden">
                  <div className={`h-full ${item.color} rounded-full transition-all duration-700`}
                    style={{ width: loading ? '0%' : `${Math.min(((item.value ?? 0) / 100) * 100, 100)}%` }} />
                </div>
              </div>
            ))}
          </div>

          <div className="mt-6 pt-4 border-t border-gray-100 grid grid-cols-2 gap-4">
            <div className="text-center p-3 bg-gray-50 rounded-xl">
              <p className="text-xl font-bold text-gray-800">{stats ? ((stats.completed_deals / (stats.offers || 1)) * 100).toFixed(1) : '—'}%</p>
              <p className="text-xs text-gray-500 mt-0.5">Tasa de conversión</p>
            </div>
            <div className="text-center p-3 bg-gray-50 rounded-xl">
              <p className="text-xl font-bold text-gray-800">{stats ? (stats.offers / (stats.requirements || 1)).toFixed(1) : '—'}</p>
              <p className="text-xs text-gray-500 mt-0.5">Propuestas / req.</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
