'use client';

import { useEffect, useState, useCallback } from 'react';
import { api } from '@/lib/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Users, Briefcase, ClipboardList, Star } from 'lucide-react';

interface Stats {
  users: number;
  professionals: number;
  services: number;
  avgRating: number;
}

export default function DashboardPage() {
  const [stats, setStats] = useState<Stats>({ users: 0, professionals: 0, services: 0, avgRating: 0 });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(() => {
    setLoading(true);
    setError(null);
    Promise.all([
      api.get<{ data: any[]; meta: any }>('/users').then((r) => r.data).catch(() => [] as any[]),
      api.get<{ data: any[]; meta: any }>('/professionals').then((r) => r.data).catch(() => [] as any[]),
      api.get<{ data: any[]; meta: any }>('/services').then((r) => r.data).catch(() => [] as any[]),
    ])
      .then(([users, professionals, services]) => {
        setStats({
          users: users.length,
          professionals: professionals.length,
          services: services.length,
          avgRating: 0,
        });
      })
      .catch(() => setError('Error al cargar las estadísticas'))
      .finally(() => setLoading(false));
  }, []);

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

  const cards = [
    { label: 'Usuarios', value: stats.users, icon: Users },
    { label: 'Profesionales', value: stats.professionals, icon: Briefcase },
    { label: 'Servicios', value: stats.services, icon: ClipboardList },
    { label: 'Calificación', value: stats.avgRating.toFixed(1), icon: Star },
  ];

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">Dashboard</h1>
      {loading ? (
        <p className="text-muted-foreground">Cargando estadísticas...</p>
      ) : error ? (
        <div className="flex flex-col items-center justify-center py-8 text-destructive">
          <p>{error}</p>
          <Button variant="outline" size="sm" onClick={load} className="mt-2">
            Reintentar
          </Button>
        </div>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
          {cards.map((c) => (
            <Card key={c.label}>
              <CardHeader className="flex-row items-center justify-between pb-2">
                <CardTitle className="text-sm font-medium text-muted-foreground">{c.label}</CardTitle>
                <c.icon className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <p className="text-3xl font-bold">{c.value}</p>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
