import { useQuery } from 'react-query';
import {
  Users,
  Building,
  Code,
  Database,
  Activity,
  HardDrive,
} 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 rounded-xl shadow-sm border border-gray-200 p-6">
    <div className="flex items-center">
      <div className="flex-shrink-0">
        <Icon className="h-8 w-8 text-primary-600" />
      </div>
      <div className="ml-5 w-0 flex-1">
        <dl>
          <dt className="text-sm font-medium text-gray-500 truncate">{title}</dt>
          <dd className="flex items-baseline">
            <div className="text-2xl font-semibold text-gray-900">{value}</div>
            {change && (
              <div
                className={`ml-2 flex items-baseline text-sm font-medium ${
                  changeType === 'increase' ? 'text-green-600' : 'text-red-600'
                }`}
              >
                {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 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}
        change="+12%"
        changeType="increase"
      />
      <StatCard
        title="Organizations"
        value={stats?.total_organizations || 0}
        icon={Building}
        change="+8%"
        changeType="increase"
      />
      <StatCard
        title="Applications"
        value={stats?.total_applications || 0}
        icon={Code}
        change="+15%"
        changeType="increase"
      />
      <StatCard
        title="Deployments"
        value={stats?.total_deployments || 0}
        icon={Activity}
        change="+20%"
        changeType="increase"
      />
    </div>
  );
}