'use client';

import React, { useState, useEffect, useRef } from 'react';
import { useEnhancedProducts, useInfiniteProducts } from '@/hooks/useEnhancedProducts';
import { OptimizedLazyLoad } from '@/components/ui/optimized-lazy-load';
import { ProductCardSkeleton } from '@/components/ui/loading-skeletons';
import ProductCard from '@/components/ProductCard';
import { redisCache } from '@/lib/redis-cache';
import { dataChunkManager } from '@/lib/data-chunking';

interface LargeDataHandlerProps {
  mode: 'pagination' | 'infinite' | 'virtual';
  category?: string;
  search?: string;
  enableCache?: boolean;
  enableChunking?: boolean;
  itemsPerPage?: number;
  className?: string;
}

interface CacheStats {
  hitRate?: number;
  totalMemory?: number;
}

interface ChunkStats {
  totalChunks?: number;
}

interface PerformanceStats {
  cache: CacheStats;
  chunks: ChunkStats;
  memory: string;
  renderTime: number;
}

export function LargeDataHandler({
  mode = 'infinite',
  category,
  search,
  enableCache = true,
  enableChunking = true,
  itemsPerPage = 20,
  className = '',
}: LargeDataHandlerProps) {
  const [viewMode, setViewMode] = useState(mode);
  const [showStats, setShowStats] = useState(false);
  const observerRef = useRef<HTMLDivElement>(null);

  // Choose appropriate hook based on mode
  const hookOptions = {
    category,
    search,
    enableCache,
    enableChunking,
    limit: itemsPerPage,
    chunkSize: itemsPerPage,
  };

  // Use hooks consistently
  const infiniteResult = useInfiniteProducts(hookOptions);
  const enhancedResult = useEnhancedProducts(hookOptions);
  
  const [state, actions] = mode === 'infinite' ? infiniteResult : enhancedResult;

  // Performance monitoring
  const [performanceStats, setPerformanceStats] = useState<PerformanceStats | null>(null);

  // Update stats periodically
  useEffect(() => {
    const updateStats = () => {
      const stats = actions.getStats();
      const renderStart = performance.now();
      
      // Measure render time
      requestAnimationFrame(() => {
        const renderTime = performance.now() - renderStart;
        setPerformanceStats({
          cache: stats.cache as CacheStats,
          chunks: stats.chunks as ChunkStats,
          memory: stats.memory,
          renderTime,
        });
      });
    };

    updateStats();
    const interval = setInterval(updateStats, 5000); // Every 5 seconds
    return () => clearInterval(interval);
  }, [actions]);

  // Intersection observer for infinite scroll optimization
  useEffect(() => {
    if (mode !== 'infinite' || !observerRef.current) return;

    const observer = new IntersectionObserver(
      (entries) => {
        const target = entries[0];
        if (target.isIntersecting && !state.loading && state.hasMore) {
          actions.loadMore();
        }
      },
      { rootMargin: '100px' }
    );

    observer.observe(observerRef.current);
    return () => observer.disconnect();
  }, [mode, state.loading, state.hasMore, actions]);

  // Render product grid
  const renderProducts = () => {
    if (state.error) {
      return (
        <div className="text-center py-12">
          <div className="text-red-600 mb-4">
            <svg className="w-16 h-16 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <h3 className="text-lg font-semibold">Error Loading Products</h3>
            <p className="text-gray-600 mt-2">{state.error}</p>
          </div>
          <button
            onClick={actions.refresh}
            className="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition-colors"
          >
            Try Again
          </button>
        </div>
      );
    }

    if (state.products.length === 0 && !state.loading) {
      return (
        <div className="text-center py-12">
          <div className="text-gray-400 mb-4">
            <svg className="w-16 h-16 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-2.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 009.586 13H7" />
            </svg>
            <h3 className="text-lg font-semibold">No Products Found</h3>
            <p className="text-gray-600 mt-2">Try adjusting your search or filters</p>
          </div>
        </div>
      );
    }

    return (
      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6">
        {state.products.map((product, index) => (
          <OptimizedLazyLoad
            key={`${product.id}-${index}`}
            rootMargin="200px"
            fallback={<ProductCardSkeleton />}
            delay={index > 8 ? 100 : 0} // Delay loading for items after first row
          >
            <ProductCard
              id={product.id}
              title={product.title}
              price={product.price}
              imageSrc={product.imageSrc || '/images/placeholder-product.jpg'}
              description={product.description}
              slug={product.slug}
              rating={product.rating}
              ratingCount={product.ratingCount}
              saleLabel={product.saleLabel}
              oldPrice={product.oldPrice}
            />
          </OptimizedLazyLoad>
        ))}
        
        {/* Loading skeletons while fetching more */}
        {state.loading && Array.from({ length: itemsPerPage }).map((_, index) => (
          <ProductCardSkeleton key={`skeleton-${index}`} />
        ))}
      </div>
    );
  };

  // Render pagination controls
  const renderPagination = () => {
    if (mode === 'infinite' || state.totalPages <= 1) return null;

    const currentPage = state.currentPage;
    const totalPages = state.totalPages;
    const pages = [];

    // Calculate visible page range
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, currentPage + 2);

    for (let i = startPage; i <= endPage; i++) {
      pages.push(i);
    }

    return (
      <div className="flex justify-center items-center gap-2 mt-8">
        <button
          onClick={() => actions.loadPage(currentPage - 1)}
          disabled={currentPage <= 1 || state.loading}
          className="px-3 py-2 border rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
        >
          Previous
        </button>
        
        {startPage > 1 && (
          <>
            <button
              onClick={() => actions.loadPage(1)}
              className="px-3 py-2 border rounded-lg hover:bg-gray-50"
            >
              1
            </button>
            {startPage > 2 && <span className="px-2">...</span>}
          </>
        )}
        
        {pages.map(page => (
          <button
            key={page}
            onClick={() => actions.loadPage(page)}
            className={`px-3 py-2 border rounded-lg ${
              page === currentPage
                ? 'bg-blue-600 text-white border-blue-600'
                : 'hover:bg-gray-50'
            }`}
          >
            {page}
          </button>
        ))}
        
        {endPage < totalPages && (
          <>
            {endPage < totalPages - 1 && <span className="px-2">...</span>}
            <button
              onClick={() => actions.loadPage(totalPages)}
              className="px-3 py-2 border rounded-lg hover:bg-gray-50"
            >
              {totalPages}
            </button>
          </>
        )}
        
        <button
          onClick={() => actions.loadPage(currentPage + 1)}
          disabled={currentPage >= totalPages || state.loading}
          className="px-3 py-2 border rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
        >
          Next
        </button>
      </div>
    );
  };

  // Render performance stats
  const renderStats = () => {
    if (!showStats || !performanceStats) return null;

    return (
      <div className="fixed bottom-4 right-4 bg-white border border-gray-200 rounded-lg shadow-lg p-4 text-sm z-50 max-w-sm">
        <div className="flex justify-between items-center mb-2">
          <h4 className="font-semibold">Performance Stats</h4>
          <button
            onClick={() => setShowStats(false)}
            className="text-gray-500 hover:text-gray-700"
          >
            ×
          </button>
        </div>
        
        <div className="space-y-1">
          <div>Cache Hit Rate: {performanceStats.cache.hitRate?.toFixed(1) || 0}%</div>
          <div>Memory Usage: {performanceStats.memory}</div>
          <div>Total Items: {state.products.length}</div>
          <div>Cache Hits: {state.cacheHit ? '✅' : '❌'}</div>
          <div>Render Time: {performanceStats.renderTime.toFixed(2)}ms</div>
          
          {enableChunking && (
            <div>Chunks: {performanceStats.chunks.totalChunks || 0}</div>
          )}
        </div>
        
        <div className="mt-3 space-y-1">
          <button
            onClick={actions.refresh}
            className="w-full text-xs bg-blue-600 text-white px-2 py-1 rounded hover:bg-blue-700"
          >
            Refresh Data
          </button>
          <button
            onClick={() => {
              redisCache.flushall();
              dataChunkManager.clearChunks();
              actions.refresh();
            }}
            className="w-full text-xs bg-red-600 text-white px-2 py-1 rounded hover:bg-red-700"
          >
            Clear Cache
          </button>
        </div>
      </div>
    );
  };

  return (
    <div className={`large-data-handler ${className}`}>
      {/* Controls */}
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center gap-4">
          <h2 className="text-2xl font-bold">
            Products {category && `in ${category}`}
          </h2>
          
          {state.totalCount > 0 && (
            <span className="text-gray-600">
              ({state.totalCount.toLocaleString()} items)
            </span>
          )}
        </div>
        
        <div className="flex items-center gap-4">
          {/* Mode switcher */}
          <select
            value={viewMode}
            onChange={(e) => setViewMode(e.target.value as typeof mode)}
            className="border border-gray-300 rounded-lg px-3 py-2 text-sm"
          >
            <option value="infinite">Infinite Scroll</option>
            <option value="pagination">Pagination</option>
          </select>
          
          {/* Stats toggle */}
          <button
            onClick={() => setShowStats(!showStats)}
            className="text-sm bg-gray-100 hover:bg-gray-200 px-3 py-2 rounded-lg transition-colors"
          >
            📊 Stats
          </button>
        </div>
      </div>

      {/* Products grid */}
      {renderProducts()}

      {/* Pagination */}
      {renderPagination()}

      {/* Infinite scroll trigger */}
      {mode === 'infinite' && state.hasMore && (
        <div ref={observerRef} className="flex justify-center py-8">
          {state.loading ? (
            <div className="flex items-center gap-2 text-gray-600">
              <div className="w-5 h-5 border-2 border-gray-300 border-t-blue-600 rounded-full animate-spin" />
              Loading more products...
            </div>
          ) : (
            <button
              onClick={actions.loadMore}
              className="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition-colors"
            >
              Load More Products
            </button>
          )}
        </div>
      )}

      {/* Performance stats panel */}
      {renderStats()}
    </div>
  );
}

export default LargeDataHandler;