"use client";

import React, { useEffect, useState } from 'react';
import { cache } from '@/lib/cache';

interface PerformanceStats {
  cacheHits: number;
  cacheMisses: number;
  totalRequests: number;
  cacheSize: number;
  loadTime: number;
}

// Performance monitoring hook
export function usePerformanceMonitor() {
  const [stats, setStats] = useState<PerformanceStats>({
    cacheHits: 0,
    cacheMisses: 0,
    totalRequests: 0,
    cacheSize: 0,
    loadTime: 0,
  });

  useEffect(() => {
    const startTime = performance.now();
    
    // Get cache statistics
    const cacheStats = cache.getStats();
    
    setStats(prev => ({
      ...prev,
      cacheSize: cacheStats.totalSize,
      loadTime: performance.now() - startTime,
    }));

    // Listen for performance entries
    const observer = new PerformanceObserver((list) => {
      const entries = list.getEntries();
      entries.forEach((entry) => {
        if (entry.entryType === 'navigation') {
          const navEntry = entry as PerformanceNavigationTiming;
          setStats(prev => ({
            ...prev,
            loadTime: navEntry.loadEventEnd - navEntry.loadEventStart,
          }));
        }
      });
    });

    observer.observe({ entryTypes: ['navigation'] });

    return () => observer.disconnect();
  }, []);

  const trackCacheHit = () => {
    setStats(prev => ({
      ...prev,
      cacheHits: prev.cacheHits + 1,
      totalRequests: prev.totalRequests + 1,
    }));
  };

  const trackCacheMiss = () => {
    setStats(prev => ({
      ...prev,
      cacheMisses: prev.cacheMisses + 1,
      totalRequests: prev.totalRequests + 1,
    }));
  };

  return {
    stats,
    trackCacheHit,
    trackCacheMiss,
    hitRate: stats.totalRequests > 0 ? (stats.cacheHits / stats.totalRequests) * 100 : 0,
  };
}

// Development-only performance panel
export function PerformancePanel() {
  const { stats, hitRate } = usePerformanceMonitor();
  const [isVisible, setIsVisible] = useState(false);

  // Only show in development
  if (process.env.NODE_ENV !== 'development') {
    return null;
  }

  return (
    <div className="fixed bottom-4 right-4 z-50">
      <button
        onClick={() => setIsVisible(!isVisible)}
        className="bg-blue-600 text-white px-3 py-2 rounded-lg text-sm font-medium shadow-lg hover:bg-blue-700 transition-colors"
      >
        Perf
      </button>
      
      {isVisible && (
        <div className="absolute bottom-12 right-0 bg-white border border-gray-300 rounded-lg shadow-lg p-4 w-64 text-sm">
          <div className="font-semibold mb-2">Performance Stats</div>
          
          <div className="space-y-1">
            <div className="flex justify-between">
              <span>Cache Hit Rate:</span>
              <span className={hitRate > 50 ? 'text-green-600' : 'text-red-600'}>
                {hitRate.toFixed(1)}%
              </span>
            </div>
            
            <div className="flex justify-between">
              <span>Cache Hits:</span>
              <span className="text-green-600">{stats.cacheHits}</span>
            </div>
            
            <div className="flex justify-between">
              <span>Cache Misses:</span>
              <span className="text-red-600">{stats.cacheMisses}</span>
            </div>
            
            <div className="flex justify-between">
              <span>Total Requests:</span>
              <span>{stats.totalRequests}</span>
            </div>
            
            <div className="flex justify-between">
              <span>Cache Size:</span>
              <span>{(stats.cacheSize / 1024).toFixed(1)} KB</span>
            </div>
            
            <div className="flex justify-between">
              <span>Load Time:</span>
              <span>{stats.loadTime.toFixed(1)} ms</span>
            </div>
          </div>
          
          <div className="mt-3 pt-2 border-t border-gray-200">
            <button
              onClick={() => {
                cache.clear();
                window.location.reload();
              }}
              className="text-red-600 text-xs hover:text-red-800"
            >
              Clear Cache & Reload
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// Web Vitals monitoring (simplified version)
export function useWebVitals() {
  const [vitals, setVitals] = useState<{
    fcp?: number;
    lcp?: number;
    fid?: number;
    cls?: number;
  }>({});

  useEffect(() => {
    // Basic performance monitoring using Performance API
    if (typeof window !== 'undefined' && 'performance' in window) {
      try {
        // Monitor navigation timing
        const navigation = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming;
        if (navigation) {
          const fcp = navigation.loadEventEnd - navigation.fetchStart;
          setVitals(prev => ({ ...prev, fcp }));
        }
      } catch (error) {
        console.warn('Performance monitoring not available:', error);
      }
    }
  }, []);

  return vitals;
}