import { useState, useEffect, useCallback } from "react";
import PageMeta from "../../components/common/PageMeta";
import ComponentCard from "../../components/common/ComponentCard";
import { API_BASE_URL, fetchContentImages, fetchUsageLimits, fetchAPI } from "../../services/api";

interface EndpointStatus {
  endpoint: string;
  method: string;
  status: 'healthy' | 'warning' | 'error' | 'checking';
  responseTime?: number;
  lastChecked?: string;
  error?: string;
  apiStatus?: 'healthy' | 'warning' | 'error'; // API endpoint status
  dataStatus?: 'healthy' | 'warning' | 'error'; // Page data population status
}

interface EndpointGroup {
  name: string;
  endpoints: {
    path: string;
    method: string;
    description: string;
    pageFetchFunction?: () => Promise<any>; // Optional: function to test page data population
    dataValidator?: (data: any) => boolean; // Optional: function to validate data is populated
  }[];
}

const endpointGroups: EndpointGroup[] = [
  {
    name: "Core Health & Auth",
    endpoints: [
      { path: "/v1/system/status/", method: "GET", description: "System status" },
      { path: "/v1/auth/login/", method: "POST", description: "Login" },
      { path: "/v1/auth/me/", method: "GET", description: "Current user" },
      { path: "/v1/auth/register/", method: "POST", description: "Registration" },
    ],
  },
  {
    name: "Auth & User Management",
    endpoints: [
      { path: "/v1/auth/users/", method: "GET", description: "List users" },
      { path: "/v1/auth/accounts/", method: "GET", description: "List accounts" },
      { path: "/v1/auth/sites/", method: "GET", description: "List sites" },
      { path: "/v1/auth/sectors/", method: "GET", description: "List sectors" },
      { path: "/v1/auth/plans/", method: "GET", description: "List plans" },
      { path: "/v1/auth/industries/", method: "GET", description: "List industries" },
      { path: "/v1/auth/seed-keywords/", method: "GET", description: "Seed keywords" },
      { path: "/v1/auth/site-access/", method: "GET", description: "Site access" },
    ],
  },
  {
    name: "Planner Module",
    endpoints: [
      { path: "/v1/planner/keywords/", method: "GET", description: "List keywords" },
      { path: "/v1/planner/keywords/auto_cluster/", method: "POST", description: "AI clustering" },
      { path: "/v1/planner/keywords/bulk_delete/", method: "POST", description: "Bulk delete" },
      { path: "/v1/planner/clusters/", method: "GET", description: "List clusters" },
      { path: "/v1/planner/clusters/auto_generate_ideas/", method: "POST", description: "AI ideas" },
      { path: "/v1/planner/ideas/", method: "GET", description: "List ideas" },
    ],
  },
  {
    name: "Writer Module",
    endpoints: [
      { path: "/v1/writer/tasks/", method: "GET", description: "List tasks" },
      { path: "/v1/writer/tasks/auto_generate_content/", method: "POST", description: "AI content" },
      { path: "/v1/writer/tasks/bulk_update/", method: "POST", description: "Bulk update" },
      { path: "/v1/writer/content/", method: "GET", description: "List content" },
      { path: "/v1/writer/content/generate_image_prompts/", method: "POST", description: "Image prompts" },
      { path: "/v1/writer/images/", method: "GET", description: "List images" },
      { 
        path: "/v1/writer/images/content_images/", 
        method: "GET", 
        description: "Content images",
        pageFetchFunction: async () => {
          const data = await fetchContentImages({});
          return data;
        },
        dataValidator: (data: any) => {
          // Check if data has results array with content
          return data && data.results && Array.isArray(data.results) && data.results.length > 0;
        }
      },
      { path: "/v1/writer/images/generate_images/", method: "POST", description: "AI images" },
    ],
  },
  {
    name: "System & Billing",
    endpoints: [
      { path: "/v1/system/prompts/", method: "GET", description: "List prompts" },
      { 
        path: "/v1/system/prompts/by_type/clustering/", 
        method: "GET", 
        description: "Get prompt by type",
        pageFetchFunction: async () => {
          const response = await fetchAPI('/v1/system/prompts/by_type/clustering/');
          const data = response?.data || response;
          return data;
        },
        dataValidator: (data: any) => {
          // Check if prompt data exists and has prompt_value
          return data && data.prompt_type && (data.prompt_value !== null && data.prompt_value !== undefined);
        }
      },
      { path: "/v1/system/prompts/save/", method: "POST", description: "Save prompt" },
      { path: "/v1/system/author-profiles/", method: "GET", description: "List author profiles" },
      { path: "/v1/system/strategies/", method: "GET", description: "List strategies" },
      { path: "/v1/system/settings/integrations/openai/test/", method: "POST", description: "Test integration (OpenAI)" },
      { path: "/v1/system/settings/account/", method: "GET", description: "Account settings" },
      { path: "/v1/billing/credits/balance/", method: "GET", description: "Credit balance" },
      { path: "/v1/billing/credits/usage/", method: "GET", description: "Usage logs" },
      { path: "/v1/billing/credits/transactions/", method: "GET", description: "Transactions" },
      { path: "/v1/billing/credits/usage/summary/", method: "GET", description: "Usage summary" },
      { 
        path: "/v1/billing/credits/usage/limits/", 
        method: "GET", 
        description: "Usage limits",
        pageFetchFunction: async () => {
          const data = await fetchUsageLimits();
          return data;
        },
        dataValidator: (data: any) => {
          // Check if limits array exists and has content
          return data && data.limits && Array.isArray(data.limits) && data.limits.length > 0;
        }
      },
      { path: "/v1/billing/credits/transactions/", method: "GET", description: "Transactions" },
    ],
  },
  {
    name: "Billing (Customer)",
    endpoints: [
      { path: "/v1/billing/credit-packages/", method: "GET", description: "List credit packages" },
      { path: "/v1/billing/invoices/", method: "GET", description: "List invoices" },
      { path: "/v1/billing/payments/", method: "GET", description: "List payments" },
      { path: "/v1/billing/payment-methods/", method: "GET", description: "List payment methods" },
      { path: "/v1/billing/payment-methods/available/", method: "GET", description: "Available payment methods" },
      { path: "/v1/billing/payments/manual/", method: "POST", description: "Submit manual payment" },
      { path: "/v1/billing/payments/available_methods/", method: "GET", description: "Payment methods (available_methods)" },
      { path: "/v1/billing/payment-methods/1/set_default/", method: "POST", description: "Set default payment method (sample id)" },
      { path: "/v1/billing/payment-methods/1/", method: "PATCH", description: "Update payment method (sample id)" },
      { path: "/v1/billing/payment-methods/1/", method: "DELETE", description: "Delete payment method (sample id)" },
    ],
  },
  {
    name: "Admin Billing",
    endpoints: [
      { path: "/v1/admin/billing/stats/", method: "GET", description: "Admin billing stats" },
      { path: "/v1/admin/billing/invoices/", method: "GET", description: "Admin invoices" },
      { path: "/v1/admin/billing/payments/", method: "GET", description: "Admin payments" },
      { path: "/v1/admin/billing/pending_payments/", method: "GET", description: "Pending manual payments" },
      { path: "/v1/admin/billing/1/approve_payment/", method: "POST", description: "Approve manual payment (sample id)" },
      { path: "/v1/admin/billing/1/reject_payment/", method: "POST", description: "Reject manual payment (sample id)" },
      { path: "/v1/admin/credit-costs/", method: "GET", description: "Credit cost configs" },
      { path: "/v1/admin/credit-costs/", method: "POST", description: "Update credit cost configs" },
      { path: "/v1/admin/users/", method: "GET", description: "Admin users with credits" },
      { path: "/v1/admin/users/1/adjust-credits/", method: "POST", description: "Adjust credits (sample id)" },
    ],
  },
  {
    name: "CRUD Operations - Planner",
    endpoints: [
      { path: "/v1/planner/keywords/", method: "GET", description: "List keywords (READ)" },
      { path: "/v1/planner/keywords/", method: "POST", description: "Create keyword (CREATE)" },
      { path: "/v1/planner/keywords/1/", method: "GET", description: "Get keyword (READ)" },
      { path: "/v1/planner/keywords/1/", method: "PUT", description: "Update keyword (UPDATE)" },
      { path: "/v1/planner/keywords/1/", method: "DELETE", description: "Delete keyword (DELETE)" },
      { path: "/v1/planner/clusters/", method: "GET", description: "List clusters (READ)" },
      { path: "/v1/planner/clusters/", method: "POST", description: "Create cluster (CREATE)" },
      { path: "/v1/planner/clusters/1/", method: "GET", description: "Get cluster (READ)" },
      { path: "/v1/planner/clusters/1/", method: "PUT", description: "Update cluster (UPDATE)" },
      { path: "/v1/planner/clusters/1/", method: "DELETE", description: "Delete cluster (DELETE)" },
      { path: "/v1/planner/ideas/", method: "GET", description: "List ideas (READ)" },
      { path: "/v1/planner/ideas/", method: "POST", description: "Create idea (CREATE)" },
      { path: "/v1/planner/ideas/1/", method: "GET", description: "Get idea (READ)" },
      { path: "/v1/planner/ideas/1/", method: "PUT", description: "Update idea (UPDATE)" },
      { path: "/v1/planner/ideas/1/", method: "DELETE", description: "Delete idea (DELETE)" },
    ],
  },
  {
    name: "CRUD Operations - Writer",
    endpoints: [
      { path: "/v1/writer/tasks/", method: "GET", description: "List tasks (READ)" },
      { path: "/v1/writer/tasks/", method: "POST", description: "Create task (CREATE)" },
      { path: "/v1/writer/tasks/1/", method: "GET", description: "Get task (READ)" },
      { path: "/v1/writer/tasks/1/", method: "PUT", description: "Update task (UPDATE)" },
      { path: "/v1/writer/tasks/1/", method: "DELETE", description: "Delete task (DELETE)" },
      { path: "/v1/writer/content/", method: "GET", description: "List content (READ)" },
      { path: "/v1/writer/content/", method: "POST", description: "Create content (CREATE)" },
      { path: "/v1/writer/content/1/", method: "GET", description: "Get content (READ)" },
      { path: "/v1/writer/content/1/", method: "PUT", description: "Update content (UPDATE)" },
      { path: "/v1/writer/content/1/", method: "DELETE", description: "Delete content (DELETE)" },
      { path: "/v1/writer/images/", method: "GET", description: "List images (READ)" },
      { path: "/v1/writer/images/", method: "POST", description: "Create image (CREATE)" },
      { path: "/v1/writer/images/1/", method: "GET", description: "Get image (READ)" },
      { path: "/v1/writer/images/1/", method: "PUT", description: "Update image (UPDATE)" },
      { path: "/v1/writer/images/1/", method: "DELETE", description: "Delete image (DELETE)" },
    ],
  },
];

const getStatusColor = (status: string) => {
  switch (status) {
    case 'healthy': return 'text-green-600 dark:text-green-400';
    case 'warning': return 'text-yellow-600 dark:text-yellow-400';
    case 'error': return 'text-red-600 dark:text-red-400';
    case 'checking': return 'text-blue-600 dark:text-blue-400';
    default: return 'text-gray-600 dark:text-gray-400';
  }
};

const getStatusBadge = (status: string) => {
  switch (status) {
    case 'healthy': return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400';
    case 'warning': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400';
    case 'error': return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400';
    case 'checking': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400';
    default: return 'bg-gray-100 text-gray-800 dark:bg-gray-900/30 dark:text-gray-400';
  }
};

const getStatusIcon = (status: string) => {
  switch (status) {
    case 'healthy': return '✓';
    case 'warning': return '⚠';
    case 'error': return '✗';
    case 'checking': return '⟳';
    default: return '?';
  }
};

export default function ApiMonitor() {
  const [endpointStatuses, setEndpointStatuses] = useState<Record<string, EndpointStatus>>({});
  const [loading, setLoading] = useState(false);
  const [autoRefresh, setAutoRefresh] = useState(() => {
    // Load from localStorage
    const saved = localStorage.getItem('api-monitor-auto-refresh');
    return saved !== null ? saved === 'true' : true;
  });
  const [refreshInterval, setRefreshInterval] = useState(() => {
    // Load from localStorage, default to 30 seconds
    const saved = localStorage.getItem('api-monitor-refresh-interval');
    return saved ? parseInt(saved, 10) : 30;
  });

  const checkEndpoint = useCallback(async (path: string, method: string, endpointConfig?: { pageFetchFunction?: () => Promise<any>; dataValidator?: (data: any) => boolean }) => {
    const key = `${method}:${path}`;
    
    // Set checking status
    setEndpointStatuses(prev => ({
      ...prev,
      [key]: {
        endpoint: path,
        method,
        status: 'checking',
      },
    }));

    const startTime = Date.now();
    let apiStatus: 'healthy' | 'warning' | 'error' = 'healthy';
    let dataStatus: 'healthy' | 'warning' | 'error' = 'healthy';
    
    try {
      // Get token from auth store or localStorage
      const token = localStorage.getItem('auth_token') || 
                    (() => {
                      try {
                        const authStorage = localStorage.getItem('auth-storage');
                        if (authStorage) {
                          const parsed = JSON.parse(authStorage);
                          return parsed?.state?.token || '';
                        }
                      } catch (e) {
                        // Ignore parsing errors
                      }
                      return '';
                    })();
      
      const headers: HeadersInit = {
        'Content-Type': 'application/json',
      };
      
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }

      // Determine if this is an expensive AI endpoint that should use OPTIONS
      const isExpensiveAIEndpoint = 
        path.includes('/auto_generate_content') ||
        path.includes('/auto_cluster') ||
        path.includes('/auto_generate_ideas') ||
        path.includes('/generate_image_prompts') ||
        path.includes('/generate_images');

      let actualMethod = method;
      let fetchOptions: RequestInit = {
        method: actualMethod,
        headers,
        credentials: 'include',
      };

      // For expensive AI POST endpoints, use OPTIONS to check existence without triggering function
      // If OPTIONS fails, we'll fall back to POST with empty IDs (which fails validation before triggering AI)
      if (method === 'POST' && isExpensiveAIEndpoint) {
        actualMethod = 'OPTIONS';
        fetchOptions.method = 'OPTIONS';
        // OPTIONS doesn't need body - remove it if present
        delete (fetchOptions as any).body;
      } else if (method === 'POST') {
        // For non-expensive POST endpoints, send invalid data that fails validation early
        let body: any = {};
        
        if (path.includes('/test/')) {
          body = {}; // Test endpoint might accept empty body
        } else if (path.includes('/login/')) {
          body = { username: 'test', password: 'test' }; // Will fail validation but endpoint exists
        } else if (path.includes('/register/')) {
          body = { username: 'test', email: 'test@test.com', password: 'test' }; // Will fail validation but endpoint exists
        } else if (path.includes('/bulk_')) {
          // Bulk operations need ids array
          body = { ids: [] };
        } else {
          // CRUD CREATE operations - minimal valid body
          body = {};
        }
        
        fetchOptions.body = JSON.stringify(body);
      } else if (method === 'PUT') {
        // CRUD UPDATE operations - minimal valid body
        fetchOptions.body = JSON.stringify({});
      }

      let response: Response;
      try {
        response = await fetch(`${API_BASE_URL}${path}`, fetchOptions);
      } catch (error: any) {
        // Network error or fetch failed
        const responseTime = Date.now() - startTime;
        setEndpointStatuses(prev => ({
          ...prev,
          [key]: {
            endpoint: path,
            method,
            status: 'error',
            responseTime,
            error: error.message || 'Network error',
            apiStatus: 'error',
            dataStatus: 'error',
          },
        }));
        return;
      }
      
      const responseTime = Date.now() - startTime;
      
      // Determine status based on response
      let status: 'healthy' | 'warning' | 'error' = 'healthy';
      let responseText = '';
      let responseData: any = null;
      
      // Read response body for debugging and content validation
      try {
        responseText = await response.text();
        // Try to parse JSON to check unified API response format
        if (responseText && responseText.trim().startsWith('{')) {
          try {
            responseData = JSON.parse(responseText);
          } catch (e) {
            // Not JSON, ignore
          }
        }
      } catch (e) {
        // Ignore body read errors
      }
      
      if (actualMethod === 'OPTIONS') {
        // OPTIONS: 200 with Allow header = healthy, anything else = error
        if (response.status === 200) {
          const allowHeader = response.headers.get('Allow') || response.headers.get('allow');
          if (allowHeader && (allowHeader.includes('POST') || allowHeader.includes('post'))) {
            status = 'healthy';
          } else {
            // If we can't read Allow header (CORS issue), but got 200, assume it's healthy
            // OPTIONS 200 generally means endpoint exists
            status = 'healthy';
          }
        } else if (response.status === 404) {
          status = 'error'; // Endpoint doesn't exist
        } else if (response.status >= 500) {
          status = 'error';
        } else {
          status = 'warning';
        }
      } else if (method === 'GET') {
        // GET: 2xx = healthy, 401/403 = warning (needs auth), 404 = error, 429 = warning (rate limit), 5xx = error
        if (response.status >= 200 && response.status < 300) {
          // Check unified API response format for errors or empty data
          if (responseData) {
            // Check if response has success: false (unified format error)
            if (responseData.success === false) {
              status = 'error'; // API returned an error in unified format
            } else if (responseData.success === true) {
              // Check for paginated response format (success: true, count: X, results: [...])
              // or single object response format (success: true, data: {...})
              const isPaginatedResponse = 'results' in responseData && 'count' in responseData;
              const isSingleObjectResponse = 'data' in responseData;
              
              if (isPaginatedResponse) {
                // Paginated response - check results at top level
                if (!Array.isArray(responseData.results)) {
                  status = 'warning'; // Missing or invalid results array
                } else if (responseData.results.length === 0 && responseData.count === 0) {
                  // Empty results with count 0 is OK for list endpoints
                  // Only warn for critical endpoints that should have data
                  if (path.includes('/content_images/') || path.includes('/prompts/by_type/')) {
                    status = 'warning'; // No data available - might indicate configuration issue
                  }
                }
              } else if (isSingleObjectResponse) {
                // Single object response - check data field
                const shouldHaveData = 
                  path.includes('/content_images/') ||
                  path.includes('/prompts/by_type/') ||
                  path.includes('/usage/limits/');
                
                if (shouldHaveData) {
                  if (responseData.data === null || responseData.data === undefined) {
                    status = 'warning'; // Missing data field
                  } else if (Array.isArray(responseData.data) && responseData.data.length === 0) {
                    if (path.includes('/content_images/') || path.includes('/prompts/by_type/')) {
                      status = 'warning'; // Empty data - might indicate configuration issue
                    }
                  } else if (typeof responseData.data === 'object' && responseData.data !== null) {
                    // Check if it's a nested paginated response
                    if (responseData.data.results && Array.isArray(responseData.data.results) && responseData.data.results.length === 0) {
                      if (path.includes('/content_images/') || path.includes('/prompts/by_type/')) {
                        status = 'warning'; // Empty results - might indicate data issue
                      }
                    } else if (responseData.data.count !== undefined && responseData.data.count === 0) {
                      if (path.includes('/content_images/') || path.includes('/prompts/by_type/')) {
                        status = 'warning'; // No data available - might indicate configuration issue
                      }
                    }
                  }
                }
              } else if (!isPaginatedResponse && !isSingleObjectResponse) {
                // Response has success: true but no data or results
                // For paginated list endpoints, this is a problem
                if (path.includes('/prompts/') && !path.includes('/save/') && !path.includes('/by_type/')) {
                  status = 'warning'; // Paginated endpoint missing results field
                }
              }
            }
          }
          
          // If status is still healthy after content checks, keep it healthy
          if (status === 'healthy') {
            status = 'healthy'; // HTTP 2xx and valid response = healthy
          }
        } else if (response.status === 429) {
          status = 'warning'; // Rate limited - endpoint exists but temporarily throttled
        } else if (response.status === 401 || response.status === 403) {
          status = 'warning'; // Endpoint exists, needs authentication
        } else if (response.status === 404) {
          // For GET requests to specific resource IDs (e.g., /v1/planner/keywords/1/),
          // 404 is expected and healthy (resource doesn't exist, but endpoint works correctly)
          // For other GET requests (like list endpoints), 404 means endpoint doesn't exist
          const isResourceByIdRequest = /\/\d+\/?$/.test(path); // Path ends with /number/ or /number
          if (method === 'GET' && isResourceByIdRequest) {
            status = 'healthy'; // GET to specific ID returning 404 is healthy (endpoint exists, resource doesn't)
          } else {
            status = 'error'; // Endpoint doesn't exist
          }
        } else if (response.status >= 500) {
          status = 'error';
        } else {
          status = 'warning';
        }
      } else if (method === 'POST') {
        // POST: 400 = healthy (endpoint exists and validates), 401/403 = warning, 404 = error, 429 = warning (rate limit), 5xx = error
        if (response.status === 400) {
          // 400 means endpoint exists and validation works - this is healthy for monitoring
          // But check if it's a unified format error response
          if (responseData && responseData.success === false) {
            // This is expected for validation errors, so still healthy
            status = 'healthy';
          } else {
            status = 'healthy';
          }
        } else if (response.status >= 200 && response.status < 300) {
          // Check unified API response format for errors
          if (responseData && responseData.success === false) {
            status = 'error'; // API returned an error in unified format
          } else {
            status = 'healthy';
          }
        } else if (response.status === 429) {
          status = 'warning'; // Rate limited - endpoint exists but temporarily throttled
        } else if (response.status === 401 || response.status === 403) {
          status = 'warning'; // Endpoint exists, needs authentication
        } else if (response.status === 404) {
          status = 'error'; // Endpoint doesn't exist
        } else if (response.status >= 500) {
          status = 'error';
        } else {
          status = 'warning';
        }
      } else if (method === 'PUT') {
        // UPDATE operations
        if (response.status === 400 || response.status === 404) {
          // 400/404 expected for test requests (validation/not found) - endpoint is working
          status = 'healthy';
        } else if (response.status >= 200 && response.status < 300) {
          status = 'healthy';
        } else if (response.status === 429) {
          status = 'warning'; // Rate limited
        } else if (response.status === 401 || response.status === 403) {
          status = 'warning'; // Needs authentication
        } else if (response.status >= 500) {
          status = 'error';
        } else {
          status = 'warning';
        }
      } else if (method === 'DELETE') {
        // DELETE operations
        if (response.status === 204 || response.status === 200) {
          // 204 No Content or 200 OK - successful delete
          status = 'healthy';
        } else if (response.status === 404) {
          // 404 expected for test requests (resource not found) - endpoint is working
          status = 'healthy';
        } else if (response.status === 429) {
          status = 'warning'; // Rate limited
        } else if (response.status === 401 || response.status === 403) {
          status = 'warning'; // Needs authentication
        } else if (response.status >= 500) {
          status = 'error';
        } else {
          status = 'warning';
        }
      }
      
      // Store API status
      apiStatus = status;
      
      // Now check page data population if pageFetchFunction is configured
      if (endpointConfig?.pageFetchFunction) {
        try {
          const pageData = await endpointConfig.pageFetchFunction();
          
          // Validate data using validator if provided
          if (endpointConfig.dataValidator) {
            const isValid = endpointConfig.dataValidator(pageData);
            if (!isValid) {
              dataStatus = 'warning'; // Data exists but doesn't pass validation (e.g., empty)
            } else {
              dataStatus = 'healthy'; // Data is valid and populated
            }
          } else {
            // If no validator, just check if data exists
            if (pageData === null || pageData === undefined) {
              dataStatus = 'error';
            } else {
              dataStatus = 'healthy';
            }
          }
        } catch (error: any) {
          // Page fetch function failed
          dataStatus = 'error';
          console.warn(`[API Monitor] Page data fetch failed for ${path}:`, error.message);
        }
      } else {
        // No page fetch function configured, data status matches API status
        dataStatus = apiStatus;
      }
      
      // Combine API and data statuses - both must be healthy for overall healthy
      // If either is error, overall is error
      // If either is warning, overall is warning
      if (apiStatus === 'error' || dataStatus === 'error') {
        status = 'error';
      } else if (apiStatus === 'warning' || dataStatus === 'warning') {
        status = 'warning';
      } else {
        status = 'healthy';
      }
      
      // Log warnings/errors for issues detected in response content
      // Skip logging for expected 400 responses on POST (validation errors are expected)
      const isExpected400Post = method === 'POST' && response.status === 400;
      if ((status === 'warning' || status === 'error') && !isExpected400Post) {
        if (responseData) {
          if (responseData.success === false) {
            console.warn(`[API Monitor] ${method} ${path}: Unified format error - ${responseData.error || 'Unknown error'}`);
          } else {
            // Check for paginated response format
            const isPaginated = 'results' in responseData && 'count' in responseData;
            const isSingleObject = 'data' in responseData;
            
            if (isPaginated) {
              // Paginated response - check results at top level
              if (!Array.isArray(responseData.results)) {
                console.warn(`[API Monitor] ${method} ${path}: Missing or invalid results array in paginated response`);
              } else if (responseData.results.length === 0 && responseData.count === 0 && 
                        (path.includes('/prompts/') && !path.includes('/save/') && !path.includes('/by_type/'))) {
                console.warn(`[API Monitor] ${method} ${path}: Empty paginated response (count: 0, results: [])`);
              }
            } else if (isSingleObject) {
              // Single object response - check data field
              if (responseData.data === null || responseData.data === undefined) {
                console.warn(`[API Monitor] ${method} ${path}: Missing data field in response`);
              } else if (Array.isArray(responseData.data) && responseData.data.length === 0) {
                console.warn(`[API Monitor] ${method} ${path}: Empty data array returned`);
              } else if (responseData.data?.results && Array.isArray(responseData.data.results) && responseData.data.results.length === 0) {
                console.warn(`[API Monitor] ${method} ${path}: Empty results array returned`);
              } else if (responseData.data?.count === 0) {
                console.warn(`[API Monitor] ${method} ${path}: No data available (count: 0)`);
              }
            } else if (responseData.success === true && !isPaginated && !isSingleObject) {
              // Response has success: true but no data or results
              if (path.includes('/prompts/') && !path.includes('/save/') && !path.includes('/by_type/')) {
                console.warn(`[API Monitor] ${method} ${path}: Paginated endpoint missing results field`);
              }
            }
          }
        }
      }
      
      // Suppress console errors for expected monitoring responses
      // Only log real errors (5xx, network errors, or unexpected 4xx for GET endpoints)
      // Don't log expected 400s for POST endpoints (they indicate validation is working)
      // Don't log expected 404s for GET requests to specific resource IDs (they indicate endpoint works correctly)
      const isResourceByIdRequest = /\/\d+\/?$/.test(path); // Path ends with /number/ or /number
      const isExpectedResponse = 
        (method === 'POST' && response.status === 400) || // Expected validation error
        (actualMethod === 'OPTIONS' && response.status === 200) || // Expected OPTIONS success
        (method === 'GET' && response.status >= 200 && response.status < 300 && status === 'healthy') || // Expected GET success with valid data
        (method === 'GET' && response.status === 404 && isResourceByIdRequest); // Expected 404 for GET to non-existent resource ID
      
      if (!isExpectedResponse && (response.status >= 500 || 
          (method === 'GET' && response.status === 404 && !isResourceByIdRequest) ||
          (actualMethod === 'OPTIONS' && response.status !== 200))) {
        // These are real errors worth logging
        console.warn(`[API Monitor] ${method} ${path}: ${response.status}`, responseText.substring(0, 100));
      }

      setEndpointStatuses(prev => ({
        ...prev,
        [key]: {
          endpoint: path,
          method,
          status,
          responseTime,
          lastChecked: new Date().toISOString(),
          apiStatus,
          dataStatus,
        },
      }));
    } catch (err: any) {
      const responseTime = Date.now() - startTime;
      
      // Network errors or timeouts are real errors
      setEndpointStatuses(prev => ({
        ...prev,
        [key]: {
          endpoint: path,
          method,
          status: 'error',
          responseTime,
          lastChecked: new Date().toISOString(),
          error: err instanceof Error ? err.message : 'Network error',
        },
      }));
    }
  }, []);

  const checkAllEndpoints = useCallback(async () => {
    setLoading(true);
    
    // Check all endpoints in parallel (but limit concurrency)
    const allChecks = endpointGroups.flatMap(group =>
      group.endpoints.map(ep => checkEndpoint(ep.path, ep.method, {
        pageFetchFunction: ep.pageFetchFunction,
        dataValidator: ep.dataValidator
      }))
    );

    // Check in batches of 5 to avoid overwhelming the server
    const batchSize = 5;
    for (let i = 0; i < allChecks.length; i += batchSize) {
      const batch = allChecks.slice(i, i + batchSize);
      await Promise.all(batch);
      // Small delay between batches
      if (i + batchSize < allChecks.length) {
        await new Promise(resolve => setTimeout(resolve, 100));
      }
    }

    setLoading(false);
  }, [checkEndpoint]);

  useEffect(() => {
    // Only check when component is mounted (page is visible)
    checkAllEndpoints();

    // Set up auto-refresh if enabled
    if (autoRefresh) {
      const interval = setInterval(() => {
        checkAllEndpoints();
      }, refreshInterval * 1000);

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

  const getEndpointStatus = (path: string, method: string): EndpointStatus => {
    const key = `${method}:${path}`;
    return endpointStatuses[key] || {
      endpoint: path,
      method,
      status: 'checking',
    };
  };

  const getGroupHealth = (group: EndpointGroup) => {
    const statuses = group.endpoints.map(ep => getEndpointStatus(ep.path, ep.method).status);
    const healthy = statuses.filter(s => s === 'healthy').length;
    const warning = statuses.filter(s => s === 'warning').length;
    const error = statuses.filter(s => s === 'error').length;
    const total = statuses.length;
    return { healthy, warning, error, total };
  };

  const getGroupStatus = (group: EndpointGroup): 'error' | 'warning' | 'healthy' => {
    const health = getGroupHealth(group);
    if (health.error > 0) return 'error';
    if (health.warning > 0) return 'warning';
    return 'healthy';
  };

  const getStatusPriority = (status: 'error' | 'warning' | 'healthy'): number => {
    switch (status) {
      case 'error': return 0;
      case 'warning': return 1;
      case 'healthy': return 2;
      default: return 3;
    }
  };

  // Sort endpoint groups by status (error > warning > healthy)
  const sortedEndpointGroups = [...endpointGroups].sort((a, b) => {
    const statusA = getGroupStatus(a);
    const statusB = getGroupStatus(b);
    const priorityA = getStatusPriority(statusA);
    const priorityB = getStatusPriority(statusB);
    
    // If same priority, sort by name
    if (priorityA === priorityB) {
      return a.name.localeCompare(b.name);
    }
    
    return priorityA - priorityB;
  });

  return (
    <>
      <PageMeta title="API Monitor - IGNY8" description="API endpoint monitoring" />
      
      <div className="space-y-6">
        {/* Header Controls */}
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-2xl font-semibold text-gray-800 dark:text-white/90">API Monitor</h1>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
              Monitor API endpoint health and response times
            </p>
          </div>
          <div className="flex items-center gap-4">
            <label className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400">
              <input
                type="checkbox"
                checked={autoRefresh}
                onChange={(e) => {
                  const newValue = e.target.checked;
                  setAutoRefresh(newValue);
                  localStorage.setItem('api-monitor-auto-refresh', String(newValue));
                }}
                className="rounded border-gray-300"
              />
              Auto-refresh
            </label>
            {autoRefresh && (
              <select
                value={refreshInterval}
                onChange={(e) => {
                  const newValue = Number(e.target.value);
                  setRefreshInterval(newValue);
                  localStorage.setItem('api-monitor-refresh-interval', String(newValue));
                  // Dispatch custom event to notify sidebar component
                  window.dispatchEvent(new Event('api-monitor-interval-changed'));
                }}
                className="text-sm rounded border-gray-300 dark:bg-gray-800 dark:border-gray-700"
              >
                <option value={30}>30s</option>
                <option value={60}>1min</option>
                <option value={300}>5min</option>
              </select>
            )}
            <button
              onClick={checkAllEndpoints}
              disabled={loading}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed text-sm"
            >
              {loading ? 'Checking...' : 'Refresh All'}
            </button>
          </div>
        </div>

        {/* Monitoring Tables - 3 per row */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {sortedEndpointGroups.map((group, groupIndex) => {
            const groupHealth = getGroupHealth(group);
            const groupStatus = getGroupStatus(group);
            return (
              <ComponentCard
                key={groupIndex}
                title={
                  <div className="flex items-center gap-2">
                    <span>{group.name}</span>
                    <span className={`text-xs px-2 py-0.5 rounded ${getStatusBadge(groupStatus)}`}>
                      {getStatusIcon(groupStatus)}
                    </span>
                  </div>
                }
                desc={
                  groupStatus === 'error' 
                    ? `${groupHealth.error} error${groupHealth.error !== 1 ? 's' : ''}, ${groupHealth.warning} warning${groupHealth.warning !== 1 ? 's' : ''}, ${groupHealth.healthy} healthy`
                    : groupStatus === 'warning'
                    ? `${groupHealth.warning} warning${groupHealth.warning !== 1 ? 's' : ''}, ${groupHealth.healthy} healthy`
                    : `${groupHealth.healthy}/${groupHealth.total} healthy`
                }
              >
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead>
                      <tr>
                        <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
                          Endpoint
                        </th>
                        <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
                          Status
                        </th>
                        <th className="px-3 py-2 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
                          Time
                        </th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
                      {group.endpoints
                        .map((endpoint, epIndex) => ({
                          endpoint,
                          epIndex,
                          status: getEndpointStatus(endpoint.path, endpoint.method),
                        }))
                        .sort((a, b) => {
                          const priorityA = getStatusPriority(a.status.status);
                          const priorityB = getStatusPriority(b.status.status);
                          // If same priority, sort by method then path
                          if (priorityA === priorityB) {
                            const methodCompare = a.endpoint.method.localeCompare(b.endpoint.method);
                            if (methodCompare !== 0) return methodCompare;
                            return a.endpoint.path.localeCompare(b.endpoint.path);
                          }
                          return priorityA - priorityB;
                        })
                        .map(({ endpoint, epIndex, status }) => {
                        return (
                          <tr key={epIndex} className="hover:bg-gray-50 dark:hover:bg-gray-800/50">
                            <td className="px-3 py-2">
                              <div className="text-xs">
                                <span className="font-mono text-gray-600 dark:text-gray-400">
                                  {endpoint.method}
                                </span>
                                <div className="text-xs text-gray-500 dark:text-gray-500 mt-0.5 truncate max-w-[200px]">
                                  {endpoint.path}
                                </div>
                                <div className="text-xs text-gray-400 dark:text-gray-600 mt-0.5">
                                  {endpoint.description}
                                </div>
                              </div>
                            </td>
                            <td className="px-3 py-2">
                              <div className="flex flex-col gap-1">
                                <span
                                  className={`inline-flex items-center gap-1 text-xs px-2 py-1 rounded ${getStatusBadge(status.status)}`}
                                  title={status.error || status.status}
                                >
                                  <span>{getStatusIcon(status.status)}</span>
                                  <span className="capitalize">{status.status}</span>
                                </span>
                                {status.apiStatus && status.dataStatus && endpoint.pageFetchFunction && status.apiStatus !== status.dataStatus && (
                                  <div className="text-xs space-y-0.5 mt-1">
                                    <div className={`${getStatusColor(status.apiStatus)}`}>
                                      API: {status.apiStatus}
                                    </div>
                                    <div className={`${getStatusColor(status.dataStatus)}`}>
                                      Data: {status.dataStatus}
                                    </div>
                                  </div>
                                )}
                              </div>
                            </td>
                            <td className="px-3 py-2">
                              {status.responseTime ? (
                                <span className="text-xs text-gray-600 dark:text-gray-400">
                                  {status.responseTime}ms
                                </span>
                              ) : (
                                <span className="text-xs text-gray-400 dark:text-gray-600">-</span>
                              )}
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </ComponentCard>
            );
          })}
        </div>

        {/* Summary Stats */}
        <ComponentCard title="Summary" desc="Overall API health statistics">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            {sortedEndpointGroups.map((group, index) => {
              const groupHealth = getGroupHealth(group);
              const groupStatus = getGroupStatus(group);
              const percentage = groupHealth.total > 0 
                ? Math.round((groupHealth.healthy / groupHealth.total) * 100) 
                : 0;
              
              return (
                <div key={index} className="text-center">
                  <div className={`text-2xl font-semibold ${getStatusColor(groupStatus)}`}>
                    {percentage}%
                  </div>
                  <div className="text-sm text-gray-600 dark:text-gray-400 mt-1 flex items-center justify-center gap-1">
                    <span>{group.name}</span>
                    <span className={getStatusColor(groupStatus)}>{getStatusIcon(groupStatus)}</span>
                  </div>
                  <div className="text-xs text-gray-500 dark:text-gray-500 mt-1">
                    {groupHealth.healthy}/{groupHealth.total} healthy
                    {groupHealth.error > 0 && ` • ${groupHealth.error} error${groupHealth.error !== 1 ? 's' : ''}`}
                    {groupHealth.warning > 0 && ` • ${groupHealth.warning} warning${groupHealth.warning !== 1 ? 's' : ''}`}
                  </div>
                </div>
              );
            })}
          </div>
        </ComponentCard>
      </div>
    </>
  );
}

