import { useState, useEffect, useMemo } from 'react';
import { useStats, useBlocks } from '../hooks/useApi';
import StatsCards, { StatsCardsSkeleton } from '../components/StatsCards';
import BlockList, { BlockListSkeleton } from '../components/BlockList';
import ConnectionStatus from '../components/ConnectionStatus';
import { useRealtimeBlocks, useRealtimeStats } from '../contexts/WebSocketContext';
import { AlertCircle, TrendingUp, Coins, Target, Radio } from 'lucide-react';
import { useAnimatedNumber } from '../hooks/useAnimatedNumber';
import type { NetworkStats, ExplorerBlock } from '../lib/types';

export default function Home() {
  const { data: stats, isLoading: statsLoading, error: statsError } = useStats(30000);
  const { data: blocksData, isLoading: blocksLoading, error: blocksError } = useBlocks(1, 10);

  // Real-time WebSocket updates
  const { latestBlock, blockHistory, isConnected } = useRealtimeBlocks(10);
  const { stats: realtimeStats } = useRealtimeStats();

  // Flash animation state for new blocks
  const [flashBlock, setFlashBlock] = useState<string | null>(null);

  // Merge initial API data with real-time updates
  const mergedStats = useMemo<NetworkStats | null>(() => {
    if (!stats) return null;
    if (!realtimeStats) return stats;

    return {
      ...stats,
      blockCount: realtimeStats.blockCount,
      virtualDaaScore: realtimeStats.virtualDaaScore,
      difficulty: realtimeStats.difficulty,
      mempoolSize: realtimeStats.mempoolSize,
      hashrate: realtimeStats.hashrate,
      hashrateHuman: realtimeStats.hashrateHuman,
    };
  }, [stats, realtimeStats]);

  // Convert real-time block events to ExplorerBlock format and merge with API data
  const mergedBlocks = useMemo<ExplorerBlock[]>(() => {
    const apiBlocks = blocksData?.data || [];

    if (!blockHistory.length) return apiBlocks;

    // Convert real-time blocks to ExplorerBlock format
    const realtimeBlocks: ExplorerBlock[] = blockHistory.map((b) => ({
      hash: b.hash,
      version: 1,
      parentHashes: [],
      timestamp: b.timestamp,
      timestampHuman: new Date(b.timestamp).toISOString(),
      bits: 0,
      nonce: 0,
      daaScore: b.blueScore,
      blueScore: b.blueScore,
      blueWork: '',
      difficulty: 0,
      transactionCount: b.txCount,
      isChainBlock: b.isChainBlock,
      childrenHashes: [],
      mergeSetBlues: [],
      mergeSetReds: [],
    }));

    // Merge: real-time blocks first, then fill with API blocks (avoiding duplicates)
    const seen = new Set(realtimeBlocks.map((b) => b.hash));
    const merged = [...realtimeBlocks];

    for (const block of apiBlocks) {
      if (!seen.has(block.hash) && merged.length < 10) {
        merged.push(block);
        seen.add(block.hash);
      }
    }

    return merged.slice(0, 10);
  }, [blocksData, blockHistory]);

  // Flash effect when new block arrives
  useEffect(() => {
    if (latestBlock) {
      setFlashBlock(latestBlock.hash);
      const timer = setTimeout(() => setFlashBlock(null), 1000);
      return () => clearTimeout(timer);
    }
  }, [latestBlock]);

  return (
    <div className="space-y-8">
      {/* Hero Header */}
      <section className="relative">
        {/* Background glow effect */}
        <div className="absolute -top-20 left-1/2 -translate-x-1/2 w-[600px] h-[300px] bg-synor-500/20 rounded-full blur-[100px] pointer-events-none" />

        <div className="relative flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div className="text-center md:text-left">
            <h1 className="text-3xl md:text-4xl font-bold mb-2">
              <span className="bg-gradient-to-r from-synor-400 via-violet-400 to-synor-400 bg-clip-text text-transparent bg-[length:200%_auto] animate-gradient">
                Synor Network
              </span>
            </h1>
            <p className="text-gray-400 text-lg">
              Real-time blockchain explorer for the Synor GHOSTDAG network
            </p>
          </div>

          {/* Connection status */}
          <div className="flex items-center justify-center md:justify-end gap-3">
            <ConnectionStatus showLabel size="md" />
            {isConnected && latestBlock && (
              <div className="hidden sm:flex items-center gap-2 px-3 py-1.5 rounded-lg bg-synor-500/10 border border-synor-500/30 text-synor-400 text-xs">
                <Radio size={12} className="animate-pulse" />
                <span>Block #{latestBlock.blueScore.toLocaleString()}</span>
              </div>
            )}
          </div>
        </div>
      </section>

      {/* Network Stats */}
      <section>
        {statsLoading && !mergedStats ? (
          <StatsCardsSkeleton />
        ) : statsError ? (
          <ErrorCard message={statsError.message} />
        ) : mergedStats ? (
          <StatsCards stats={mergedStats} />
        ) : null}
      </section>

      {/* Circulating Supply - Modern Design */}
      {mergedStats && (
        <CirculatingSupplyCard
          circulatingSupply={mergedStats.circulatingSupply}
          maxSupply={mergedStats.maxSupply}
          circulatingSupplyHuman={mergedStats.circulatingSupplyHuman}
        />
      )}

      {/* Recent Blocks */}
      <section>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-semibold flex items-center gap-2">
            <div className="w-2 h-2 rounded-full bg-green-500 animate-pulse" />
            Recent Blocks
          </h2>
        </div>
        {blocksLoading && !mergedBlocks.length ? (
          <BlockListSkeleton count={10} />
        ) : blocksError ? (
          <ErrorCard message={blocksError.message} />
        ) : mergedBlocks.length ? (
          <BlockList blocks={mergedBlocks} highlightHash={flashBlock} />
        ) : null}
      </section>
    </div>
  );
}

/**
 * Modern circulating supply visualization with animated progress
 */
function CirculatingSupplyCard({
  circulatingSupply,
  maxSupply,
  circulatingSupplyHuman,
}: {
  circulatingSupply: number;
  maxSupply: number;
  circulatingSupplyHuman: string;
}) {
  const [mounted, setMounted] = useState(false);
  const percentage = (circulatingSupply / maxSupply) * 100;
  const animatedPercentage = useAnimatedNumber(mounted ? percentage : 0, {
    duration: 2000,
    decimals: 2,
  });

  useEffect(() => {
    setMounted(true);
  }, []);

  // Milestone markers
  const milestones = [25, 50, 75];

  return (
    <section className="relative group">
      {/* Glassmorphism card */}
      <div className="relative overflow-hidden rounded-2xl border border-gray-700/50 bg-gray-900/40 backdrop-blur-xl p-6">
        {/* Background gradient */}
        <div className="absolute inset-0 bg-gradient-to-br from-synor-500/5 via-transparent to-violet-500/5" />

        {/* Glow effect on hover */}
        <div className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-500">
          <div className="absolute inset-0 bg-gradient-to-r from-synor-500/10 via-transparent to-violet-500/10" />
        </div>

        <div className="relative">
          {/* Header */}
          <div className="flex flex-col md:flex-row md:items-start justify-between gap-6 mb-6">
            <div className="flex items-start gap-4">
              <div className="p-3 rounded-xl bg-gradient-to-br from-synor-500/20 to-violet-500/20 border border-synor-500/30">
                <Coins className="w-6 h-6 text-synor-400" />
              </div>
              <div>
                <h2 className="text-sm text-gray-400 mb-1 flex items-center gap-2">
                  Circulating Supply
                  <span className="inline-flex items-center gap-1 text-xs text-green-400">
                    <TrendingUp size={12} />
                    Active
                  </span>
                </h2>
                <p className="text-3xl font-bold bg-gradient-to-r from-white to-gray-300 bg-clip-text text-transparent">
                  {circulatingSupplyHuman}
                </p>
              </div>
            </div>

            {/* Percentage display */}
            <div className="flex items-center gap-3 px-4 py-2 rounded-xl bg-gray-800/50 border border-gray-700/50">
              <Target className="w-5 h-5 text-synor-400" />
              <div>
                <p className="text-xs text-gray-500">of Max Supply</p>
                <p className="text-xl font-bold text-synor-400">
                  {animatedPercentage.toFixed(2)}%
                </p>
              </div>
            </div>
          </div>

          {/* Progress bar container */}
          <div className="relative">
            {/* Milestone markers */}
            <div className="absolute inset-x-0 -top-6 flex justify-between px-1">
              {milestones.map((milestone) => (
                <div
                  key={milestone}
                  className="flex flex-col items-center"
                  style={{ left: `${milestone}%`, position: 'absolute', transform: 'translateX(-50%)' }}
                >
                  <span className="text-xs text-gray-500">{milestone}%</span>
                </div>
              ))}
            </div>

            {/* Progress track */}
            <div className="relative h-4 bg-gray-800/80 rounded-full overflow-hidden border border-gray-700/50">
              {/* Milestone lines */}
              {milestones.map((milestone) => (
                <div
                  key={milestone}
                  className="absolute top-0 bottom-0 w-px bg-gray-600/50"
                  style={{ left: `${milestone}%` }}
                />
              ))}

              {/* Animated progress fill */}
              <div
                className="absolute inset-y-0 left-0 rounded-full transition-all duration-1000 ease-out"
                style={{ width: `${animatedPercentage}%` }}
              >
                {/* Gradient fill */}
                <div className="absolute inset-0 bg-gradient-to-r from-synor-600 via-synor-500 to-violet-500" />

                {/* Shine effect */}
                <div className="absolute inset-0 bg-gradient-to-b from-white/20 to-transparent" />

                {/* Animated glow at edge */}
                <div className="absolute right-0 top-1/2 -translate-y-1/2 w-4 h-4 bg-white rounded-full blur-md animate-pulse" />
              </div>
            </div>

            {/* Labels below */}
            <div className="flex justify-between mt-3 text-sm">
              <span className="text-gray-500">0 SYN</span>
              <span className="text-gray-400 font-medium">
                Max: {formatMaxSupply(maxSupply)}
              </span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/**
 * Format max supply with appropriate units (assumes sompi units: 10^8 sompi = 1 SYN)
 */
function formatMaxSupply(maxSupply: number): string {
  const synValue = maxSupply / 100_000_000; // Convert from sompi
  if (synValue >= 1_000_000_000) {
    return `${(synValue / 1_000_000_000).toFixed(1)}B SYN`;
  }
  if (synValue >= 1_000_000) {
    return `${(synValue / 1_000_000).toFixed(0)}M SYN`;
  }
  if (synValue >= 1_000) {
    return `${(synValue / 1_000).toFixed(0)}K SYN`;
  }
  return `${synValue.toLocaleString()} SYN`;
}

function ErrorCard({ message }: { message: string }) {
  return (
    <div className="card p-6 border-red-900/50">
      <div className="flex items-center gap-3 text-red-400">
        <AlertCircle size={24} />
        <div>
          <p className="font-medium">Error loading data</p>
          <p className="text-sm text-red-400/80">{message}</p>
        </div>
      </div>
    </div>
  );
}
