/**
 * Modern network stats cards with animations and glassmorphism.
 */

import { useEffect, useState } from 'react';
import {
  Activity,
  Box,
  Cpu,
  Users,
  Clock,
  Database,
  Zap,
  TrendingUp,
  Server,
} from 'lucide-react';
import type { NetworkStats } from '../lib/types';
import { cn } from '../lib/utils';
import { useAnimatedNumber } from '../hooks/useAnimatedNumber';

interface StatsCardsProps {
  stats: NetworkStats;
}

interface StatCardProps {
  icon: React.ReactNode;
  label: string;
  value: number | string;
  animatedValue?: boolean;
  suffix?: string;
  subValue?: string;
  trend?: 'up' | 'down' | 'neutral';
  pulse?: boolean;
  highlight?: boolean;
  delay?: number;
  gradient?: string;
}

function AnimatedValue({
  value,
  suffix = '',
  compact = false,
  delay = 0,
}: {
  value: number;
  suffix?: string;
  compact?: boolean;
  delay?: number;
}) {
  const animatedValue = useAnimatedNumber(value, { duration: 2000, delay });

  if (compact) {
    if (animatedValue >= 1_000_000_000) {
      return <>{(animatedValue / 1_000_000_000).toFixed(2)}B{suffix}</>;
    }
    if (animatedValue >= 1_000_000) {
      return <>{(animatedValue / 1_000_000).toFixed(2)}M{suffix}</>;
    }
    if (animatedValue >= 1_000) {
      return <>{(animatedValue / 1_000).toFixed(1)}K{suffix}</>;
    }
  }

  return <>{animatedValue.toLocaleString()}{suffix}</>;
}

function StatCard({
  icon,
  label,
  value,
  animatedValue = true,
  suffix,
  subValue,
  trend,
  pulse,
  highlight,
  delay = 0,
  gradient,
}: StatCardProps) {
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => setIsVisible(true), delay * 100);
    return () => clearTimeout(timer);
  }, [delay]);

  const numericValue = typeof value === 'number' ? value : parseFloat(value) || 0;

  return (
    <div
      className={cn(
        'relative group overflow-hidden rounded-xl transition-all duration-500',
        isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-4',
        highlight && 'col-span-2 md:col-span-1'
      )}
    >
      {/* Glassmorphism background */}
      <div className="absolute inset-0 bg-gradient-to-br from-white/5 to-white/0 backdrop-blur-sm" />

      {/* Border gradient */}
      <div
        className={cn(
          'absolute inset-0 rounded-xl',
          gradient || 'bg-gradient-to-br from-synor-500/20 via-transparent to-blue-500/20'
        )}
        style={{ padding: '1px' }}
      >
        <div className="absolute inset-[1px] rounded-xl bg-gray-900/90" />
      </div>

      {/* Glow effect on hover */}
      <div className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-500 bg-gradient-to-br from-synor-500/10 to-blue-500/10 rounded-xl" />

      {/* Content */}
      <div className="relative p-4 z-10">
        <div className="flex items-start justify-between">
          <div className="flex items-start gap-3">
            <div
              className={cn(
                'p-2.5 rounded-lg transition-all duration-300',
                highlight
                  ? 'bg-gradient-to-br from-synor-500 to-synor-600 text-white shadow-lg shadow-synor-500/25'
                  : 'bg-white/5 text-synor-400 group-hover:bg-white/10'
              )}
            >
              {icon}
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-1">
                {label}
              </p>
              <p
                className={cn(
                  'text-xl font-bold tracking-tight',
                  highlight ? 'text-white' : 'text-gray-100'
                )}
              >
                {animatedValue && typeof value === 'number' ? (
                  <AnimatedValue
                    value={numericValue}
                    suffix={suffix}
                    compact={numericValue > 1000}
                    delay={delay * 100}
                  />
                ) : (
                  <>
                    {value}
                    {suffix}
                  </>
                )}
              </p>
              {subValue && (
                <p className="text-[11px] text-gray-500 mt-1 flex items-center gap-1">
                  {trend === 'up' && <TrendingUp size={10} className="text-green-400" />}
                  {subValue}
                </p>
              )}
            </div>
          </div>

          {/* Status indicator */}
          {pulse && (
            <div className="relative">
              <div className="w-2 h-2 rounded-full bg-green-400" />
              <div className="absolute inset-0 w-2 h-2 rounded-full bg-green-400 animate-ping" />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export default function StatsCards({ stats }: StatsCardsProps) {
  return (
    <div className="space-y-4">
      {/* Hero Stats Row */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard
          icon={<Activity size={20} />}
          label="Network Status"
          value={stats.isSynced ? 'Synced' : 'Syncing'}
          animatedValue={false}
          subValue={`${stats.networkId} network`}
          pulse={stats.isSynced}
          highlight
          delay={0}
          gradient="bg-gradient-to-br from-green-500/30 via-transparent to-emerald-500/20"
        />
        <StatCard
          icon={<Box size={20} />}
          label="Total Blocks"
          value={stats.blockCount}
          subValue={`${stats.tipCount} active tips`}
          highlight
          delay={1}
          gradient="bg-gradient-to-br from-synor-500/30 via-transparent to-violet-500/20"
        />
        <StatCard
          icon={<Cpu size={20} />}
          label="Network Hashrate"
          value={stats.hashrateHuman}
          animatedValue={false}
          subValue={`${stats.blockRate.toFixed(2)} blocks/sec`}
          trend="up"
          highlight
          delay={2}
          gradient="bg-gradient-to-br from-blue-500/30 via-transparent to-cyan-500/20"
        />
        <StatCard
          icon={<Zap size={20} />}
          label="Blue Score"
          value={stats.virtualDaaScore}
          subValue="virtual DAA score"
          highlight
          delay={3}
          gradient="bg-gradient-to-br from-amber-500/30 via-transparent to-orange-500/20"
        />
      </div>

      {/* Secondary Stats Row */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <StatCard
          icon={<Database size={18} />}
          label="Difficulty"
          value={stats.difficulty}
          delay={4}
        />
        <StatCard
          icon={<Clock size={18} />}
          label="Mempool"
          value={stats.mempoolSize}
          suffix=" txs"
          delay={5}
        />
        <StatCard
          icon={<Users size={18} />}
          label="Peers"
          value={stats.peerCount}
          subValue="connected nodes"
          delay={6}
        />
        <StatCard
          icon={<Server size={18} />}
          label="Headers"
          value={stats.headerCount}
          delay={7}
        />
      </div>
    </div>
  );
}

export function StatsCardsSkeleton() {
  return (
    <div className="space-y-4">
      {/* Hero Row Skeleton */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {Array.from({ length: 4 }).map((_, i) => (
          <div
            key={i}
            className="relative overflow-hidden rounded-xl bg-gray-900/50 border border-gray-800"
          >
            <div className="p-4 animate-pulse">
              <div className="flex items-start gap-3">
                <div className="w-10 h-10 rounded-lg bg-gray-800" />
                <div className="flex-1">
                  <div className="h-3 w-20 bg-gray-800 rounded mb-2" />
                  <div className="h-6 w-28 bg-gray-800 rounded mb-1" />
                  <div className="h-2 w-16 bg-gray-800 rounded" />
                </div>
              </div>
            </div>
            {/* Shimmer effect */}
            <div className="absolute inset-0 -translate-x-full animate-[shimmer_2s_infinite] bg-gradient-to-r from-transparent via-white/5 to-transparent" />
          </div>
        ))}
      </div>

      {/* Secondary Row Skeleton */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        {Array.from({ length: 4 }).map((_, i) => (
          <div
            key={i}
            className="relative overflow-hidden rounded-xl bg-gray-900/50 border border-gray-800"
          >
            <div className="p-4 animate-pulse">
              <div className="flex items-start gap-3">
                <div className="w-9 h-9 rounded-lg bg-gray-800" />
                <div className="flex-1">
                  <div className="h-2 w-16 bg-gray-800 rounded mb-2" />
                  <div className="h-5 w-20 bg-gray-800 rounded" />
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
