/**
 * CacheStatus Component
 * 
 * Displays cache health status in FilterBar with icon and percentage
 */

import React from 'react';
import { useState, useEffect } from 'react';
import React from 'react';
import { CheckCircle, AlertCircle, XCircle, Play } from 'lucide-react';
import React from 'react';
import { api } from '../../services/api';

interface CacheStats {
  health: {
    cache_count: number;
    actual_count: number;
  };
  sync: {
    is_running: boolean;
    processed: number;
    total: number;
  };
}

export default function CacheStatus() {
  const [stats, setStats] = useState<CacheStats | null>(null);

  const loadStats = async () => {
    try {
      const response = await api.get('/cache/stats');
      setStats(response.data.data);
    } catch (error) {
      console.error('[CacheStatus] Failed to load stats:', error);
    }
  };

  useEffect(() => {
    // Initial load
    loadStats();

    // Refresh every batch (2 seconds per batch, so check every 3 seconds)
    const interval = setInterval(loadStats, 3000);

    return () => clearInterval(interval);
  }, []);

  if (!stats) {
    return null; // Don't show anything until loaded
  }

  const isSyncing = stats.sync.is_running;
  
  // Calculate percentage
  let percentage = 0;
  if (isSyncing && stats.sync.total > 0) {
    // Sync progress (round down to show real progress)
    percentage = Math.floor((stats.sync.processed / stats.sync.total) * 100);
  } else if (stats.health.actual_count > 0) {
    // Cache completeness (round down - only 100% if truly complete)
    percentage = Math.floor((stats.health.cache_count / stats.health.actual_count) * 100);
  }

  // Determine icon and color
  const getIcon = () => {
    if (isSyncing) {
      return <Play className="w-4 h-4" />;
    }
    
    if (percentage === 100) {
      return <CheckCircle className="w-4 h-4" />;
    } else if (percentage >= 95) {
      return <AlertCircle className="w-4 h-4" />;
    } else {
      return <XCircle className="w-4 h-4" />;
    }
  };

  const getColorClasses = () => {
    if (isSyncing) {
      return 'text-blue-600 bg-blue-50 border-blue-200';
    }
    
    if (percentage === 100) {
      return 'text-green-600 bg-green-50 border-green-200';
    } else if (percentage >= 95) {
      return 'text-yellow-600 bg-yellow-50 border-yellow-200';
    } else {
      return 'text-red-600 bg-red-50 border-red-200';
    }
  };

  return (
    <div 
      className={`flex items-center gap-1.5 px-2 py-1 rounded border ${getColorClasses()} text-xs font-medium`}
      title={isSyncing ? `Szinkronizálás: ${stats.sync.processed} / ${stats.sync.total}` : `Cache: ${stats.health.cache_count} / ${stats.health.actual_count}`}
    >
      {getIcon()}
      <span>{percentage}%</span>
    </div>
  );
}
