import { useQuery } from 'react-query';
import {
  Users,
  Code,
  Activity,
  Key,
} from 'lucide-react';
import apiService from '@/services/api';
import type { DashboardStats } from '@/types';

const StatCard = ({ title, value, icon: Icon, change, changeType }: any) => (
  <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border dark:border-gray-700 p-6">
    <div className="flex items-center">
      <div className="flex-shrink-0">
        <Icon className="h-8 w-8 text-primary-600 dark:text-primary-400" />
      </div>
      <div className="ml-5 w-0 flex-1">
        <dl>
          <dt className="text-sm font-medium text-gray-500 dark:text-gray-400 truncate">{title}</dt>
          <dd className="flex items-baseline">
            <div className="text-2xl font-semibold text-gray-900 dark:text-gray-100">{value}</div>
            {change && (
              <div
                className={`ml-2 flex items-baseline text-sm font-medium ${
                  changeType === 'increase' ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'
                }`}
              >
                {changeType === 'increase' ? '↑' : '↓'} {change}
              </div>
            )}
          </dd>
        </dl>
      </div>
    </div>
  </div>
);

export default function DashboardStatsComponent() {
  const { data: stats, isLoading } = useQuery<DashboardStats>(
    'dashboard-stats',
    () => apiService.getDashboardStats(),
    {
      refetchInterval: 30000, // Refetch every 30 seconds
    }
  );

  if (isLoading) {
    return (
      <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
        {[...Array(4)].map((_, i) => (
          <div key={i} className="animate-pulse">
            <div className="bg-gray-200 dark:bg-gray-700 rounded-xl h-32"></div>
          </div>
        ))}
      </div>
    );
  }

  return (
    <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
      <StatCard
        title="Total Users"
        value={stats?.total_users || 0}
        icon={Users}
      />
      <StatCard
        title="Applications"
        value={stats?.total_applications || 0}
        icon={Code}
      />
      <StatCard
        title="Deployments"
        value={stats?.total_deployments || 0}
        icon={Activity}
      />
      <StatCard
        title="API Keys"
        value={stats?.total_api_keys || 0}
        icon={Key}
      />
    </div>
  );
}