import React, { useState, useEffect, useCallback } from 'react';
import { 
  CheckCircle, 
  XCircle, 
  AlertTriangle, 
  Loader2, 
  Activity, 
  Clock,
  Globe,
  RefreshCw,
  TestTube,
  Wrench
} from 'lucide-react';
import { useSiteStore } from '../../store/siteStore';
import { useToast } from '../../components/ui/toast/ToastContainer';
import { API_BASE_URL, fetchAPI } from '../../services/api';

// Types for WordPress integration debugging
interface IntegrationHealth {
  api_status: 'healthy' | 'error';
  api_message: string;
  last_api_check: string;
  plugin_active: boolean;
  plugin_version: string;
  debug_mode: boolean;
  sync_healthy: boolean;
  pending_syncs: number;
  last_sync: string | null;
}

interface SyncEvent {
  type: 'sync' | 'error' | 'webhook' | 'debug';
  action: string;
  description: string;
  timestamp: string;
  details?: any;
}

interface DataValidation {
  field_name: string;
  igny8_value: string;
  wp_value: string;
  matches: boolean;
  error?: string;
}

export default function WordPressIntegrationDebug() {
  // State
  const [debugEnabled, setDebugEnabled] = useState(false);
  const [loading, setLoading] = useState(false);
  const [initializing, setInitializing] = useState(true);
  const [pollingInterval, setPollingInterval] = useState<any>(null);
  const [integrationHealth, setIntegrationHealth] = useState<IntegrationHealth | null>(null);
  const [syncEvents, setSyncEvents] = useState<SyncEvent[]>([]);
  const [dataValidation, setDataValidation] = useState<DataValidation[]>([]);
  const [integrationId, setIntegrationId] = useState<number | null>(null);

  // Get active site from store
  const { activeSite } = useSiteStore();
  const toast = useToast();

  // Check if integration exists for the active site
  useEffect(() => {
    const checkIntegration = async () => {
      if (!activeSite) {
        setInitializing(false);
        return;
      }

      try {
        setInitializing(true);
        const data = await fetchAPI(`/v1/integration/integrations/?site_id=${activeSite.id}`);
        const integrations = data.results || [];
        
        if (integrations.length > 0) {
          const wpIntegration = integrations.find((i: any) => i.platform === 'wordpress');
          if (wpIntegration) {
            setIntegrationId(wpIntegration.id);
            setDebugEnabled(wpIntegration.credentials_json?.debug_enabled || false);
          }
        }
      } catch (error) {
        console.error('[WP-DEBUG] Failed to check integration:', error);
      } finally {
        setInitializing(false);
      }
    };

    checkIntegration();
  }, [activeSite]);

  // Helper to make authenticated API calls with debug awareness
  const apiCall = async (path: string, method: string = 'GET', body?: any) => {
    // Always allow debug-status calls to check if integration exists
    if (!integrationId && !path.includes('/integrations/?')) {
      console.log('[WP-DEBUG] Skipping API call - no integration configured:', path);
      return { response: { ok: false, status: 0 } as Response, data: null };
    }

    const options: RequestInit = {
      method,
    };

    if (body && method !== 'GET') {
      options.body = JSON.stringify(body);
    }

    try {
      if (debugEnabled) {
        console.log('[WP-DEBUG] API Call:', method, path, body ? { body } : {});
      }
      
      const data = await fetchAPI(path, options);
      
      if (debugEnabled) {
        console.log('[WP-DEBUG] API Response:', data);
      }
      
      return { response: { ok: true, status: 200 } as Response, data };
    } catch (error: any) {
      if (debugEnabled) {
        console.error('[WP-DEBUG] API Error:', error);
      }
      const errorData = error.response || { detail: error.message || 'Request failed' };
      return { response: { ok: false, status: error.status || 500 } as Response, data: errorData };
    }
  };

  // Toggle debug mode
  const toggleDebugMode = async (enabled: boolean) => {
    if (!activeSite) {
      toast.error('Please select a site first');
      return;
    }

    if (!integrationId) {
      toast.error('No WordPress integration found for this site');
      return;
    }

    try {
      setLoading(true);
      
      // Set local debug state first for immediate UI response
      setDebugEnabled(enabled);
      
      if (enabled) {
        console.log('[WP-DEBUG] 🎯 WordPress Debug mode ENABLED for site:', activeSite.name);
        toast.success('WordPress debug mode enabled - verbose logging started');
        
        // Start polling for updates
        startPolling();
        
        // Trigger debug mode on WordPress plugin if integrated
        await apiCall(`/v1/integration/integrations/${integrationId}/trigger-debug/`, 'POST', {
          debug_enabled: true
        });
        
        // Load initial debug data
        await loadDebugData();
      } else {
        console.log('[WP-DEBUG] 🔒 WordPress Debug mode DISABLED');
        toast.info('WordPress debug mode disabled - reduced logging');
        
        // Stop polling
        stopPolling();
        
        // Disable debug on WordPress
        await apiCall(`/v1/integration/integrations/${integrationId}/trigger-debug/`, 'POST', {
          debug_enabled: false
        });
      }
    } catch (error) {
      console.error('[WP-DEBUG] Failed to toggle debug mode:', error);
      toast.error('Failed to toggle WordPress debug mode');
      setDebugEnabled(!enabled); // Revert
    } finally {
      setLoading(false);
    }
  };

  // Start polling for debug data
  const startPolling = () => {
    if (pollingInterval) return;
    
    const interval = setInterval(() => {
      if (debugEnabled && activeSite) {
        loadDebugData();
      }
    }, 5000); // Poll every 5 seconds when debug is enabled
    
    setPollingInterval(interval);
    console.log('[WP-DEBUG] ⏰ Started polling for WordPress debug updates');
  };

  // Stop polling
  const stopPolling = () => {
    if (pollingInterval) {
      clearInterval(pollingInterval);
      setPollingInterval(null);
      console.log('[WP-DEBUG] ⏸️ Stopped polling');
    }
  };

  // Load all debug data
  const loadDebugData = useCallback(async () => {
    if (!activeSite || !integrationId) {
      console.log('[WP-DEBUG] Skipping load - no site or integration');
      return;
    }
    
    try {
      setLoading(true);
      console.log('[WP-DEBUG] 📊 Loading WordPress debug data for site:', activeSite.name);
      
      // Load integration health
      await loadIntegrationHealth();
      
      // Load sync events if debug is enabled
      if (debugEnabled) {
        await loadSyncEvents();
        await loadDataValidation();
      }
      
      console.log('[WP-DEBUG] ✅ WordPress debug data loaded successfully');
    } catch (error) {
      console.error('[WP-DEBUG] ❌ Failed to load WordPress debug data:', error);
      // Don't show toast error on initial load
    } finally {
      setLoading(false);
    }
  }, [activeSite, integrationId, debugEnabled]);

  // Load integration health
  const loadIntegrationHealth = async () => {
    if (!integrationId) return;
    
    try {
      const { data } = await apiCall(`/v1/integration/integrations/${integrationId}/debug-status/`);
      
      if (data?.health) {
        setIntegrationHealth(data.health);
        console.log('[WP-DEBUG] 💚 Integration health loaded');
      }
    } catch (error) {
      console.error('[WP-DEBUG] Failed to load integration health:', error);
    }
  };

  // Load sync events
  const loadSyncEvents = async () => {
    if (!integrationId) return;
    
    try {
      const { data } = await apiCall(`/v1/integration/integrations/${integrationId}/debug-status/?include_events=true`);
      
      if (data?.events) {
        setSyncEvents(data.events);
        console.log('[WP-DEBUG] 📜 Loaded', data.events.length, 'WordPress sync events');
      }
    } catch (error) {
      console.error('[WP-DEBUG] Failed to load sync events:', error);
    }
  };

  // Load data validation matrix
  const loadDataValidation = async () => {
    if (!integrationId) return;
    
    try {
      const { data } = await apiCall(`/v1/integration/integrations/${integrationId}/debug-status/?include_validation=true`);
      
      if (data?.validation) {
        setDataValidation(data.validation);
        console.log('[WP-DEBUG] 🧩 Loaded WordPress data validation matrix');
      }
    } catch (error) {
      console.error('[WP-DEBUG] Failed to load data validation:', error);
    }
  };

  // Interactive tools
  const testConnection = async () => {
    if (!integrationId) {
      toast.error('No WordPress integration found');
      return;
    }
    
    try {
      setLoading(true);
      console.log('[WP-DEBUG] 🔧 Testing connection to WordPress...');
      
      const { data } = await apiCall(`/v1/integration/integrations/${integrationId}/test-connection/`, 'POST');
      
      if (data?.success) {
        toast.success('WordPress connection test successful');
        await loadIntegrationHealth(); // Refresh health data
      } else {
        toast.error('WordPress connection test failed: ' + (data?.message || 'Unknown error'));
      }
    } catch (error) {
      console.error('[WP-DEBUG] Connection test error:', error);
      toast.error('WordPress connection test failed');
    } finally {
      setLoading(false);
    }
  };

  // Load initial data when component mounts or integration changes
  useEffect(() => {
    if (!initializing && integrationId) {
      loadDebugData();
    }
  }, [integrationId, initializing]);

  // Start/stop polling based on debug state
  useEffect(() => {
    if (debugEnabled && integrationId) {
      startPolling();
    } else {
      stopPolling();
    }
    
    return () => stopPolling();
  }, [debugEnabled, integrationId]);

  // Effects - Load initial data when site changes or integration found
  useEffect(() => {
    if (activeSite && integrationId && !initializing) {
      loadDebugData();
      // Auto-start polling for real-time updates if debug enabled
      if (debugEnabled) {
        startPolling();
      }
    }
    
    return () => {
      stopPolling();
    };
  }, [activeSite, integrationId, initializing]);

  // Show loading state while initializing
  if (initializing) {
    return (
      <div className="p-8 text-center">
        <Loader2 className="h-8 w-8 animate-spin mx-auto text-blue-600 dark:text-blue-400" />
        <p className="text-sm text-gray-500 dark:text-gray-400 mt-2">Loading WordPress integration...</p>
      </div>
    );
  }

  // Show message if no integration is configured
  if (!integrationId) {
    return (
      <div className="p-8">
        <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-900/50 rounded-lg p-6 text-center">
          <AlertTriangle className="h-12 w-12 text-yellow-600 dark:text-yellow-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
            No WordPress Integration Found
          </h3>
          <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
            This site doesn't have a WordPress integration configured yet.
          </p>
          <p className="text-sm text-gray-600 dark:text-gray-400">
            Please configure a WordPress integration in the <strong>Settings → Integration</strong> page first.
          </p>
        </div>
      </div>
    );
  }

  const resyncSiteMetadata = async () => {
    if (!activeSite) return;
    
    try {
      setLoading(true);
      console.log('[WP-DEBUG] 🔄 Re-syncing WordPress site metadata...');
      
      const { data } = await apiCall(`/integration/integrations/${activeSite.id}/resync-metadata/`, 'POST');
      
      if (data?.success) {
        toast.success('WordPress site metadata re-synced successfully');
        await loadDebugData(); // Refresh all data
      } else {
        toast.error('WordPress re-sync failed: ' + data?.message);
      }
    } catch (error) {
      console.error('[WP-DEBUG] Metadata resync error:', error);
      toast.error('WordPress metadata re-sync failed');
    } finally {
      setLoading(false);
    }
  };

  const validatePostSync = async (taskId?: number) => {
    if (!activeSite) return;
    
    const id = taskId || prompt('Enter Task ID to validate WordPress sync:');
    if (!id) return;
    
    try {
      setLoading(true);
      console.log('[WP-DEBUG] 🔍 Validating WordPress post sync for task:', id);
      
      const { data } = await apiCall(`/integration/integrations/${activeSite.id}/validate-content/${id}/`);
      
      if (data) {
        toast.success('WordPress post validation completed');
        setDataValidation(data.validation || []);
      } else {
        toast.error('WordPress validation failed: ' + data?.message);
      }
    } catch (error) {
      console.error('[WP-DEBUG] Post validation error:', error);
      toast.error('WordPress post validation failed');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      {/* No WordPress Integration Found */}
      {initializing ? (
        <div className="bg-white dark:bg-gray-800 shadow rounded-lg p-6 text-center">
          <Loader2 className="h-8 w-8 animate-spin mx-auto text-gray-400 mb-2" />
          <p className="text-gray-600 dark:text-gray-400">Checking for WordPress integration...</p>
        </div>
      ) : !integrationId && activeSite ? (
        <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-900/50 rounded-lg p-6">
          <div className="flex items-start space-x-3">
            <AlertTriangle className="h-8 w-8 text-yellow-500 mt-0.5" />
            <div>
              <p className="text-lg font-semibold text-yellow-800 dark:text-yellow-200">No WordPress Integration Found</p>
              <p className="text-sm text-yellow-600 dark:text-yellow-300 mt-2">
                This site doesn't have a WordPress integration configured yet.
              </p>
              <p className="text-xs text-yellow-600 dark:text-yellow-400 mt-2">
                Please configure a WordPress integration in <span className="font-medium">Settings → Integration</span> page first.
              </p>
            </div>
          </div>
        </div>
      ) : !activeSite ? (
        <div className="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
          <div className="text-center py-12">
            <Globe className="h-12 w-12 mx-auto text-gray-400 mb-4" />
            <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">No Site Selected</h3>
            <p className="text-gray-500 dark:text-gray-400">
              Please select a site to view WordPress integration debug data.
            </p>
          </div>
        </div>
      ) : (
        <>
          {/* Integration Health Summary */}
          <div className="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-medium text-gray-900 dark:text-white">WordPress Bridge Health</h3>
              <div className="flex space-x-2">
                <button
                  onClick={testConnection}
                  disabled={loading}
                  className="inline-flex items-center px-3 py-1 text-xs bg-blue-100 hover:bg-blue-200 text-blue-700 rounded-md disabled:opacity-50"
                >
                  <TestTube className="h-3 w-3 mr-1" />
                  Test Connection
                </button>
                <button
                  onClick={resyncSiteMetadata}
                  disabled={loading}
                  className="inline-flex items-center px-3 py-1 text-xs bg-yellow-100 hover:bg-yellow-200 text-yellow-700 rounded-md disabled:opacity-50"
                >
                  <RefreshCw className="h-3 w-3 mr-1" />
                  Re-sync Metadata
                </button>
                <button
                  onClick={() => validatePostSync()}
                  disabled={loading}
                  className="inline-flex items-center px-3 py-1 text-xs bg-purple-100 hover:bg-purple-200 text-purple-700 rounded-md disabled:opacity-50"
                >
                  <Wrench className="h-3 w-3 mr-1" />
                  Validate Content
                </button>
              </div>
            </div>

            {integrationHealth ? (
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm font-medium">API Connection</span>
                    {integrationHealth.api_status === 'healthy' ? (
                      <CheckCircle className="h-4 w-4 text-green-500" />
                    ) : (
                      <XCircle className="h-4 w-4 text-red-500" />
                    )}
                  </div>
                  <p className="text-xs text-gray-600 dark:text-gray-400">{integrationHealth.api_message}</p>
                  <div className="text-xs text-gray-500 mt-1">
                    Last: {new Date(integrationHealth.last_api_check).toLocaleTimeString()}
                  </div>
                </div>

                <div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm font-medium">Plugin Status</span>
                    {integrationHealth.plugin_active ? (
                      <CheckCircle className="h-4 w-4 text-green-500" />
                    ) : (
                      <XCircle className="h-4 w-4 text-red-500" />
                    )}
                  </div>
                  <p className="text-xs text-gray-600 dark:text-gray-400">
                    Version: {integrationHealth.plugin_version || 'Unknown'}
                  </p>
                  <div className="text-xs text-gray-500 mt-1">
                    Debug: {integrationHealth.debug_mode ? 'Enabled' : 'Disabled'}
                  </div>
                </div>

                <div className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4">
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm font-medium">Sync Status</span>
                    {integrationHealth.sync_healthy ? (
                      <CheckCircle className="h-4 w-4 text-green-500" />
                    ) : (
                      <AlertTriangle className="h-4 w-4 text-yellow-500" />
                    )}
                  </div>
                  <p className="text-xs text-gray-600 dark:text-gray-400">
                    {integrationHealth.pending_syncs || 0} pending
                  </p>
                  <div className="text-xs text-gray-500 mt-1">
                    Last: {integrationHealth.last_sync ? 
                      new Date(integrationHealth.last_sync).toLocaleTimeString() : 'Never'}
                  </div>
                </div>
              </div>
            ) : (
              <div className="text-center py-4 text-gray-500">
                <Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />
                Loading WordPress integration health...
              </div>
            )}
          </div>

          {/* Live Action Logs */}
          <div className="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
            <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4">Live WordPress Sync Events</h3>
            
            {syncEvents.length > 0 ? (
              <div className="space-y-3 max-h-96 overflow-y-auto">
                {syncEvents.slice().reverse().map((event, idx) => (
                  <div key={idx} className="border-l-4 border-gray-200 dark:border-gray-600 pl-4 py-2">
                    <div className="flex items-start justify-between">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center space-x-2 text-sm">
                          <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                            event.type === 'sync' ? 'bg-blue-100 text-blue-700' :
                            event.type === 'error' ? 'bg-red-100 text-red-700' :
                            event.type === 'webhook' ? 'bg-green-100 text-green-700' :
                            'bg-gray-100 text-gray-700'
                          }`}>
                            {event.type}
                          </span>
                          <span className="font-medium truncate">{event.action}</span>
                        </div>
                        <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">{event.description}</p>
                        {event.details && (
                          <details className="mt-2">
                            <summary className="text-xs text-blue-600 cursor-pointer hover:underline">
                              View Details
                            </summary>
                            <pre className="mt-2 text-xs bg-gray-50 dark:bg-gray-700 p-2 rounded border overflow-x-auto">
                              {typeof event.details === 'string' ? event.details : JSON.stringify(event.details, null, 2)}
                            </pre>
                          </details>
                        )}
                      </div>
                      <div className="text-xs text-gray-500 whitespace-nowrap ml-4">
                        {new Date(event.timestamp).toLocaleTimeString()}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500">
                <Clock className="h-8 w-8 mx-auto mb-2 opacity-50" />
                <p>No WordPress sync events yet. Actions will appear here in real-time.</p>
                <p className="text-xs mt-2">Content publishing, metadata sync, and webhook calls will be logged here.</p>
              </div>
            )}
          </div>

          {/* Data Validation Matrix */}
          {dataValidation.length > 0 && (
            <div className="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4">Data Sync Validation</h3>
              
              <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                  <thead className="bg-gray-50 dark:bg-gray-700">
                    <tr>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        Field
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        IGNY8 Value
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        WordPress Value  
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                        Status
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                    {dataValidation.map((validation, idx) => (
                      <tr key={idx} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">
                          {validation.field_name}
                        </td>
                        <td className="px-6 py-4 text-sm text-gray-500 dark:text-gray-400 max-w-xs truncate">
                          {validation.igny8_value || <span className="text-gray-400 italic">empty</span>}
                        </td>
                        <td className="px-6 py-4 text-sm text-gray-500 dark:text-gray-400 max-w-xs truncate">
                          {validation.wp_value || <span className="text-gray-400 italic">empty</span>}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          {validation.matches ? (
                            <CheckCircle className="h-4 w-4 text-green-500" />
                          ) : (
                            <div className="flex items-center space-x-1">
                              <XCircle className="h-4 w-4 text-red-500" />
                              {validation.error && (
                                <span className="text-xs text-red-600">{validation.error}</span>
                              )}
                            </div>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
}