/**
 * @ai-summary Enhanced debugging panel for mobile token flow and performance monitoring
 */

import React, { useState, useEffect } from 'react';
import { useAuth0 } from '@auth0/auth0-react';
import { useQueryClient } from '@tanstack/react-query';
import { useNavigationStore, useUserStore } from '../store';

interface DebugInfo {
  timestamp: string;
  type: 'auth' | 'query' | 'navigation' | 'network';
  message: string;
  data?: any;
}

export const MobileDebugPanel: React.FC<{ visible: boolean }> = ({ visible }) => {
  const { isAuthenticated, getAccessTokenSilently } = useAuth0();
  const queryClient = useQueryClient();
  const navigationStore = useNavigationStore();
  const userStore = useUserStore();

  const [debugLogs, setDebugLogs] = useState<DebugInfo[]>([]);
  const [tokenInfo, setTokenInfo] = useState<{
    hasToken: boolean;
    tokenPreview?: string;
    lastRefresh?: string;
    cacheMode?: string;
  }>({
    hasToken: false,
  });

  const [expanded, setExpanded] = useState(false);

  // Monitor token status
  useEffect(() => {
    if (!isAuthenticated) return;

    const checkToken = async () => {
      try {
        const token = await getAccessTokenSilently({ cacheMode: 'cache-only' });
        setTokenInfo({
          hasToken: !!token,
          tokenPreview: token ? token.substring(0, 20) + '...' : undefined,
          lastRefresh: new Date().toLocaleTimeString(),
          cacheMode: 'cache-only',
        });

        addDebugLog('auth', 'Token check successful', {
          hasToken: !!token,
          cacheMode: 'cache-only',
        });
      } catch (error) {
        addDebugLog('auth', 'Token check failed', { error: error instanceof Error ? error.message : 'Unknown error' });
        setTokenInfo({ hasToken: false });
      }
    };

    checkToken();
    const interval = setInterval(checkToken, 10000); // Check every 10 seconds

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

  const addDebugLog = (type: DebugInfo['type'], message: string, data?: any) => {
    const logEntry: DebugInfo = {
      timestamp: new Date().toLocaleTimeString(),
      type,
      message,
      data,
    };

    setDebugLogs(prev => [...prev.slice(-19), logEntry]); // Keep last 20 entries
  };

  // Monitor navigation changes
  useEffect(() => {
    addDebugLog('navigation', `Navigated to ${navigationStore.activeScreen}`, {
      screen: navigationStore.activeScreen,
      subScreen: navigationStore.vehicleSubScreen,
      selectedVehicleId: navigationStore.selectedVehicleId,
      isNavigating: navigationStore.isNavigating,
      historyLength: navigationStore.navigationHistory.length,
    });
  }, [navigationStore.activeScreen, navigationStore.vehicleSubScreen, navigationStore.selectedVehicleId, navigationStore.isNavigating]);

  // Monitor navigation errors
  useEffect(() => {
    if (navigationStore.navigationError) {
      addDebugLog('navigation', `Navigation Error: ${navigationStore.navigationError}`, {
        error: navigationStore.navigationError,
        screen: navigationStore.activeScreen,
      });
    }
  }, [navigationStore.navigationError]);

  // Monitor network status
  useEffect(() => {
    const handleOnline = () => addDebugLog('network', 'Network: Online');
    const handleOffline = () => addDebugLog('network', 'Network: Offline');

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, []);

  const getQueryCacheStats = () => {
    const cache = queryClient.getQueryCache();
    const queries = cache.getAll();

    return {
      total: queries.length,
      stale: queries.filter(q => q.isStale()).length,
      loading: queries.filter(q => q.state.status === 'pending').length,
      error: queries.filter(q => q.state.status === 'error').length,
    };
  };

  const testTokenRefresh = async () => {
    try {
      addDebugLog('auth', 'Testing token refresh...');
      const token = await getAccessTokenSilently({ cacheMode: 'off' });
      addDebugLog('auth', 'Token refresh successful', {
        hasToken: !!token,
        length: token?.length,
      });
      setTokenInfo(prev => ({
        ...prev,
        hasToken: !!token,
        tokenPreview: token ? token.substring(0, 20) + '...' : undefined,
        lastRefresh: new Date().toLocaleTimeString(),
        cacheMode: 'off',
      }));
    } catch (error) {
      addDebugLog('auth', 'Token refresh failed', {
        error: error instanceof Error ? error.message : 'Unknown error'
      });
    }
  };

  if (!visible) return null;

  const cacheStats = getQueryCacheStats();
  const isMobile = window.innerWidth <= 768;

  return (
    <div className={`fixed ${expanded ? 'inset-4' : 'bottom-4 right-4'} bg-black/90 text-white text-xs font-mono rounded-lg transition-all duration-300 z-50`}>
      <div className="flex items-center justify-between p-2 border-b border-white/20">
        <span className="font-semibold">Debug Panel</span>
        <button
          onClick={() => setExpanded(!expanded)}
          className="text-white/70 hover:text-white"
        >
          {expanded ? '−' : '+'}
        </button>
      </div>

      {expanded ? (
        <div className="p-3 max-h-[80vh] overflow-y-auto">
          {/* System Info */}
          <div className="mb-4">
            <div className="text-yellow-400 font-semibold mb-1">System Status</div>
            <div>Mode: {isMobile ? 'Mobile' : 'Desktop'} | Auth: {isAuthenticated ? 'Yes' : 'No'}</div>
            <div>Screen: {navigationStore.activeScreen} | Sub: {navigationStore.vehicleSubScreen}</div>
            <div>Online: {userStore.isOnline ? 'Yes' : 'No'} | Width: {window.innerWidth}px</div>
          </div>

          {/* Navigation Info */}
          <div className="mb-4">
            <div className="text-cyan-400 font-semibold mb-1">Navigation State</div>
            <div>Current: {navigationStore.activeScreen} → {navigationStore.vehicleSubScreen}</div>
            <div>Navigating: {navigationStore.isNavigating ? 'Yes' : 'No'}</div>
            <div>History: {navigationStore.navigationHistory.length} entries</div>
            <div>Selected Vehicle: {navigationStore.selectedVehicleId || 'None'}</div>
            {navigationStore.navigationError && (
              <div className="text-red-300">Error: {navigationStore.navigationError}</div>
            )}
            <div className="mt-2 flex gap-1 flex-wrap">
              {['Dashboard', 'Vehicles', 'Log Fuel', 'Settings'].map((screen) => (
                <button
                  key={screen}
                  onClick={() => {
                    addDebugLog('navigation', `Debug navigation to ${screen}`);
                    navigationStore.navigateToScreen(screen as any);
                  }}
                  className={`text-xs px-2 py-1 rounded ${
                    navigationStore.activeScreen === screen
                      ? 'bg-cyan-600 text-white'
                      : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                  }`}
                >
                  {screen.slice(0, 3)}
                </button>
              ))}
            </div>
          </div>

          {/* Token Info */}
          <div className="mb-4">
            <div className="flex items-center justify-between mb-1">
              <span className="text-green-400 font-semibold">Token Status</span>
              <button
                onClick={testTokenRefresh}
                className="text-xs bg-blue-600 px-2 py-1 rounded hover:bg-blue-700"
              >
                Test Refresh
              </button>
            </div>
            <div>Has Token: {tokenInfo.hasToken ? 'Yes' : 'No'}</div>
            {tokenInfo.tokenPreview && <div>Preview: {tokenInfo.tokenPreview}</div>}
            {tokenInfo.lastRefresh && <div>Last Refresh: {tokenInfo.lastRefresh}</div>}
            {tokenInfo.cacheMode && <div>Cache Mode: {tokenInfo.cacheMode}</div>}
          </div>

          {/* Query Cache Stats */}
          <div className="mb-4">
            <div className="text-blue-400 font-semibold mb-1">Query Cache</div>
            <div>Total: {cacheStats.total} | Stale: {cacheStats.stale}</div>
            <div>Loading: {cacheStats.loading} | Error: {cacheStats.error}</div>
          </div>

          {/* Debug Logs */}
          <div>
            <div className="text-purple-400 font-semibold mb-1">Recent Events</div>
            <div className="space-y-1 max-h-40 overflow-y-auto">
              {debugLogs.slice(-10).reverse().map((log, index) => (
                <div key={index} className="text-xs">
                  <span className="text-white/50">[{log.timestamp}]</span>{' '}
                  <span className={
                    log.type === 'auth' ? 'text-green-300' :
                    log.type === 'query' ? 'text-blue-300' :
                    log.type === 'navigation' ? 'text-yellow-300' :
                    'text-purple-300'
                  }>
                    {log.type.toUpperCase()}
                  </span>:{' '}
                  <span>{log.message}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      ) : (
        <div className="p-2">
          <div>
            {isMobile ? 'M' : 'D'} | {isAuthenticated ? '🔐' : '🔓'} |
            {navigationStore.activeScreen.substring(0, 3)} |
            T:{tokenInfo.hasToken ? '✅' : '❌'}
          </div>
        </div>
      )}
    </div>
  );
};