'use client';

import { useState, useEffect } from 'react';
import { Users, Activity, Shield, Clock } from 'lucide-react';
import { motion } from 'framer-motion';

interface Stats {
  totalUsers: number;
  recentLogins: number;
  totalLogs: number;
}

export default function DashboardContent({ userName, userRole }: { userName: string; userRole: string }) {
  const [stats, setStats] = useState<Stats>({ totalUsers: 0, recentLogins: 0, totalLogs: 0 });

  useEffect(() => {
    if (userRole === 'admin') {
      fetch('/api/users')
        .then((r) => r.json())
        .then((d) => {
          if (d?.users) {
            setStats((prev) => ({ ...prev, totalUsers: d.users?.length ?? 0 }));
          }
        })
        .catch(console.error);
      fetch('/api/logs')
        .then((r) => r.json())
        .then((d) => {
          if (d?.logs) {
            const logins = (d.logs ?? []).filter((l: { action?: string }) => l?.action === 'LOGIN_SUCCESS')?.length ?? 0;
            setStats((prev) => ({ ...prev, totalLogs: d.logs?.length ?? 0, recentLogins: logins }));
          }
        })
        .catch(console.error);
    }
  }, [userRole]);

  const cards = userRole === 'admin'
    ? [
        { label: 'Usuarios totales', value: stats.totalUsers, icon: Users, color: 'bg-blue-500' },
        { label: 'Inicios de sesión', value: stats.recentLogins, icon: Clock, color: 'bg-green-500' },
        { label: 'Registros de actividad', value: stats.totalLogs, icon: Activity, color: 'bg-purple-500' },
      ]
    : [];

  return (
    <div>
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }}>
        <h1 className="text-2xl font-bold text-[#1a365d] mb-1">Bienvenido, {userName}</h1>
        <p className="text-gray-500 mb-6">Panel de control de Climasan Core</p>
      </motion.div>

      {userRole === 'admin' && (
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-8">
          {cards?.map((card, i) => {
            const Icon = card?.icon;
            return (
              <motion.div
                key={card?.label}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: i * 0.1 }}
                className="bg-white rounded-lg shadow-sm p-5 flex items-center gap-4 hover:shadow-md transition-shadow"
              >
                <div className={`${card?.color} p-3 rounded-lg`}>
                  <Icon className="w-5 h-5 text-white" />
                </div>
                <div>
                  <p className="text-2xl font-bold text-[#1a365d]">{card?.value ?? 0}</p>
                  <p className="text-sm text-gray-500">{card?.label}</p>
                </div>
              </motion.div>
            );
          })}
        </div>
      )}

      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.3 }}
        className="bg-white rounded-lg shadow-sm p-6"
      >
        <div className="flex items-center gap-3 mb-4">
          <Shield className="w-5 h-5 text-[#1a365d]" />
          <h2 className="text-lg font-semibold text-[#1a365d]">Información del sistema</h2>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
          <div className="bg-gray-50 rounded-lg p-4">
            <p className="text-gray-500 mb-1">Versión</p>
            <p className="font-medium text-gray-800">Climasan Core v1.0</p>
          </div>
          <div className="bg-gray-50 rounded-lg p-4">
            <p className="text-gray-500 mb-1">Rol actual</p>
            <p className="font-medium text-gray-800 capitalize">{userRole}</p>
          </div>
        </div>
      </motion.div>
    </div>
  );
}
