import { useState, useEffect, useCallback, useMemo } from 'react';
import PageMeta from '../../components/common/PageMeta';
import IntegrationCard from '../../components/common/IntegrationCard';
import ValidationCard from '../../components/common/ValidationCard';
import ImageGenerationCard from '../../components/common/ImageGenerationCard';
import ImageResultCard from '../../components/common/ImageResultCard';
import ImageServiceCard from '../../components/common/ImageServiceCard';
import { Modal } from '../../components/ui/modal';
import FormModal, { FormField } from '../../components/common/FormModal';
import Button from '../../components/ui/button/Button';
import Checkbox from '../../components/form/input/Checkbox';
import Label from '../../components/form/Label';
import SelectDropdown from '../../components/form/SelectDropdown';
import { useToast } from '../../components/ui/toast/ToastContainer';
import Alert from '../../components/ui/alert/Alert';
import { fetchAPI } from '../../services/api';

// OpenAI Icon SVG
const OpenAIIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40" fill="none">
    <path d="M12.321 24.9775C11.9035 24.3455 12.9535 23.389 12.5264 22.5859C12.2802 22.1227 11.8779 21.8341 11.3946 21.7735C10.9308 21.7153 10.4531 21.8851 10.1486 22.2169C9.66775 22.7401 9.59299 23.4523 9.68599 23.7043C9.72002 23.7967 9.77351 23.8219 9.81181 23.8273C10.0737 23.8618 10.221 23.1897 10.3115 23.0497C10.5614 22.6639 11.129 22.5471 11.5211 22.8007C12.2643 23.2814 11.6198 24.0584 11.6754 24.7147C11.7295 25.3537 12.1277 25.6105 12.4851 25.6375C12.8328 25.6507 13.0759 25.4575 13.1373 25.3165C13.2845 24.9799 12.6644 25.4975 12.321 24.9775Z" fill="#0C111D"></path>
    <path d="M27.8512 19.1761C27.6563 19.1492 27.4432 19.1498 27.2215 19.1761C27.0532 18.9637 26.9024 18.6199 26.8173 18.2185C26.6659 17.5045 26.6817 16.9873 27.1042 16.9201C27.5266 16.8529 27.7309 17.2849 27.8822 17.9989C27.9837 18.4789 27.9643 18.9199 27.8512 19.1761Z" fill="#0C111D"></path>
    <path d="M23.2243 19.6009C23.241 19.7626 23.2469 19.9262 23.2422 20.0769C23.6509 20.1009 23.9405 20.295 24.0175 20.4182C24.0571 20.4818 24.0412 20.5232 24.0285 20.5424C23.9862 20.6082 23.8955 20.598 23.7055 20.5767C23.5396 20.5581 23.3609 20.5417 23.1752 20.5503C23.0742 20.8602 22.7745 20.8892 22.564 20.66C22.417 20.7048 22.1281 20.8892 22.0421 20.6888C22.0413 20.5893 22.1453 20.4447 22.3337 20.317C22.2051 20.0718 22.1189 19.8092 22.068 19.5373C21.801 19.5854 21.5607 19.6602 21.3725 19.7188C21.284 19.7464 20.9343 19.9044 20.8933 19.7263C20.8659 19.6033 21.0574 19.4005 21.2598 19.2541C21.486 19.0935 21.7369 18.9794 21.997 18.9135C21.9914 18.5263 22.0902 18.2561 22.3716 18.2113C22.7204 18.1558 22.9366 18.4244 23.0863 18.9218C23.5079 19.0389 23.9289 19.3294 24.1148 19.6297C24.1871 19.7461 24.2011 19.8361 24.1543 19.8835C24.0375 20.0046 23.3901 19.6535 23.2243 19.6009Z" fill="#0C111D"></path>
    <path d="M25.9967 21.3415C26.2641 21.4711 26.5583 21.4201 26.6544 21.2275C26.7504 21.0349 26.6112 20.7739 26.3438 20.6443C26.0763 20.5147 25.7821 20.5657 25.6861 20.7583C25.5901 20.9509 25.7292 21.2119 25.9967 21.3415Z" fill="#0C111D"></path>
    <path d="M27.3132 20.3851C27.3181 20.0905 27.4986 19.8553 27.7156 19.8589C27.9326 19.8631 28.1046 20.1043 28.0998 20.3983C28.0949 20.6923 27.9144 20.9275 27.6974 20.9239C27.4804 20.9203 27.3084 20.6791 27.3132 20.3851Z" fill="#0C111D"></path>
    <path fillRule="evenodd" clipRule="evenodd" d="M33.1978 23.9929C33.196 23.9868 33.202 24.0079 33.1978 23.9929C33.6336 23.9929 34.318 24.4873 34.318 25.6819C34.318 26.8705 33.8184 28.2169 33.7004 28.5157C31.9006 32.7733 27.605 35.1433 22.4882 34.9933C17.7179 34.8535 13.6497 32.3689 11.8693 28.3183C10.7928 28.3195 9.68291 27.8521 8.83923 27.1141C7.94996 26.3365 7.40169 25.3303 7.29471 24.2809C7.21144 23.4637 7.31294 22.7035 7.57249 22.0405L6.5726 21.2041C1.99679 17.3906 16.3084 1.68861 20.8854 5.6294C20.9085 5.6492 22.4427 7.13479 22.4463 7.13839C24.6532 6.21344 30.5665 4.45236 30.5731 8.55199C30.5755 9.91338 29.6966 11.501 28.2882 12.9416C29.9158 14.4315 29.4867 16.5479 29.7458 18.4897L30.3111 18.6445C31.3888 18.9427 32.1553 19.3405 32.5303 19.7293C32.9054 20.1175 33.0914 20.4937 33.1589 20.9347C33.2221 21.2905 33.2136 21.9187 32.7382 22.6213C32.9094 23.0746 33.0656 23.5264 33.1978 23.9929ZM11.7885 27.2137C11.9483 27.2173 12.107 27.2071 12.2626 27.1807C13.9347 26.8993 14.3724 25.1065 14.097 23.3461C13.7858 21.3583 12.4237 20.6575 11.4991 20.6077C11.242 20.5945 11.0031 20.6173 10.8062 20.6563C9.15591 20.9845 8.22409 22.3705 8.40766 24.1705C8.5736 25.7995 10.2427 27.1729 11.7885 27.2137ZM8.05086 21.1447C8.6046 20.3509 9.50967 19.7767 10.5369 19.5793C11.8444 16.115 14.0277 12.923 16.9174 10.7264C19.0619 8.96058 21.3747 7.69399 21.3747 7.69399C21.3747 7.69399 20.1292 6.26839 19.753 6.16339C17.4389 5.5466 12.4413 8.94858 9.25013 13.4438C7.95908 15.2624 6.11064 18.4831 6.99444 20.1397C7.10324 20.3449 7.7202 20.8723 8.05086 21.1447ZM26.8118 26.4181C26.8154 26.4553 26.7924 26.4937 26.7589 26.5075C26.7589 26.5075 24.8995 27.3613 21.9461 26.4595C22.0523 27.3448 23.1259 27.6803 23.8759 27.8017C27.5357 28.4233 30.9573 26.3575 31.7274 25.8373C31.8596 25.748 31.7258 25.9776 31.7019 26.0113C30.7591 27.2119 28.2244 28.6021 24.9269 28.6015C23.4888 28.6009 22.0512 28.1011 21.5236 27.3325C20.7048 26.1403 21.4829 24.3997 22.8475 24.5809C25.1541 24.838 27.5188 24.6448 29.6541 23.6665C31.5159 22.8133 32.2191 21.8749 32.1134 21.1147C31.9493 19.9366 30.2026 19.7524 29.3197 19.4659C28.9356 19.3405 28.7459 19.2403 28.7028 18.5269C28.6839 18.2155 28.6292 17.129 28.6092 16.6796C28.5739 15.893 28.4779 14.8172 27.802 14.3732C27.6257 14.2574 27.43 14.2016 27.2239 14.1908C27.0596 14.1829 26.9622 14.2055 26.9098 14.2176C26.8981 14.2204 26.8886 14.2226 26.8811 14.2238C26.5161 14.285 26.2925 14.4697 26.0287 14.6874C26.0135 14.7 25.9982 14.7126 25.9827 14.7254C25.1396 15.419 24.4279 15.5324 23.6358 15.4988C23.3892 15.4884 23.135 15.4638 22.8668 15.4378C22.6201 15.4139 22.3617 15.3889 22.0865 15.3728L21.7503 15.3536C20.424 15.2864 19.0017 16.4168 18.7652 18.0223C18.5011 19.8145 19.5028 20.9122 20.1542 21.6261C20.3152 21.8025 20.4548 21.9555 20.5486 22.0897C20.6088 22.1707 20.6787 22.2847 20.6787 22.3933C20.6787 22.5229 20.5936 22.6255 20.5103 22.7131C19.1573 24.0865 18.7245 26.2687 19.2345 28.0873C19.2983 28.3141 19.3792 28.5313 19.4746 28.7389C20.6708 31.4983 24.3823 32.7835 28.0074 31.6147C30.5481 30.7955 32.7929 28.8159 33.25 26.0851C33.3588 25.3735 33.199 25.0987 32.9814 24.9661C32.751 24.8263 32.475 24.8749 32.475 24.8749C32.475 24.8749 32.3492 24.0247 31.993 23.2519C30.936 24.0751 29.5756 24.6535 28.5399 24.9469C26.8804 25.4168 25.0879 25.5998 23.373 25.3782C22.6775 25.2883 22.2102 25.228 22.0099 25.8703C24.2972 26.6971 26.7182 26.3431 26.7182 26.3431C26.765 26.3383 26.8069 26.3719 26.8118 26.4181ZM20.2125 10.3736C18.9616 11.0054 17.5648 12.1304 16.4305 13.4246C16.3904 13.4708 16.45 13.5344 16.4992 13.499C17.479 12.7952 18.8224 12.1412 20.5821 11.7176C22.5533 11.243 24.451 11.4422 25.6101 11.7044C25.6685 11.7176 25.7049 11.6186 25.6533 11.5898C24.8874 11.1656 23.7118 10.8776 22.8779 10.8716C22.8371 10.871 22.814 10.8242 22.8384 10.7918C22.9824 10.6004 23.18 10.4114 23.3605 10.2746C23.4006 10.2434 23.3763 10.1792 23.3252 10.1822C22.2878 10.2451 19.9183 11.3255 19.9268 11.2862C19.9876 10.9982 20.1791 10.6178 20.2781 10.4402C20.3019 10.3982 20.2557 10.352 20.2125 10.3736Z" fill="#0C111D"></path>
  </svg>
);

// Runware Icon SVG (simplified placeholder - replace with actual)
const RunwareIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40" fill="none">
    <rect width="40" height="40" rx="8" fill="#625DF5"/>
    <path d="M20 12L28 20L20 28L12 20L20 12Z" fill="white"/>
  </svg>
);

// GSC Icon SVG (Google Search Console)
const GSCIcon = () => (
  <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40" fill="none">
    <rect width="40" height="40" rx="8" fill="#4285F4"/>
    <path d="M20 12L26 18L20 24L14 18L20 12Z" fill="white"/>
  </svg>
);

interface IntegrationConfig {
  id: string;
  enabled: boolean;
  apiKey?: string;
  clientId?: string;
  clientSecret?: string;
  authBaseUri?: string;
  appName?: string;
  model?: string;
  // Image generation service settings (separate from API integrations)
  service?: string; // 'openai' or 'runware'
  provider?: string; // Alias for service (used in backend)
  imageModel?: string; // OpenAI model: 'dall-e-3', 'dall-e-2', etc.
  runwareModel?: string; // Runware model: 'runware:97@1', etc.
  // Image generation settings
  image_type?: string; // 'realistic', 'artistic', 'cartoon'
  max_in_article_images?: number; // 1-5
  image_format?: string; // 'webp', 'jpg', 'png'
  desktop_enabled?: boolean;
  mobile_enabled?: boolean;
}

export default function Integration() {
  const toast = useToast();
  const [integrations, setIntegrations] = useState<Record<string, IntegrationConfig>>({
    openai: {
      id: 'openai',
      enabled: false,
      apiKey: '',
      model: 'gpt-4.1',
    },
    runware: {
      id: 'runware',
      enabled: false,
      apiKey: '',
    },
    image_generation: {
      id: 'image_generation',
      enabled: false,
      service: 'openai', // 'openai' or 'runware'
      provider: 'openai', // Alias for backend
      model: 'dall-e-3', // OpenAI model if service is 'openai'
      runwareModel: 'runware:97@1', // Runware model if service is 'runware'
      image_type: 'realistic', // 'realistic', 'artistic', 'cartoon'
      max_in_article_images: 2, // 1-5
      image_format: 'webp', // 'webp', 'jpg', 'png'
      desktop_enabled: true,
      mobile_enabled: true,
    },
  });

  const [selectedIntegration, setSelectedIntegration] = useState<string | null>(null);
  const [showDetailsModal, setShowDetailsModal] = useState(false);
  const [showSettingsModal, setShowSettingsModal] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [isTesting, setIsTesting] = useState(false);
  
  // Validation status for each integration: 'not_configured' | 'pending' | 'success' | 'error'
  const [validationStatuses, setValidationStatuses] = useState<Record<string, 'not_configured' | 'pending' | 'success' | 'error'>>({
    openai: 'not_configured',
    runware: 'not_configured',
    image_generation: 'not_configured',
  });

  /**
   * Validate a single integration's status
   * This is the core validation function that checks enabled state and API availability
   */
  const validateIntegration = useCallback(async (
    integrationId: string,
    enabled: boolean,
    apiKey?: string,
    model?: string
  ) => {
    const API_BASE_URL = import.meta.env.VITE_BACKEND_URL || 'https://api.igny8.com/api';
    
    // Only validate OpenAI and Runware (GSC doesn't have validation endpoint)
    if (!['openai', 'runware'].includes(integrationId)) {
      return;
    }
    
    // Check if integration is enabled and has API key configured
    const hasApiKey = apiKey && apiKey.trim() !== '';
    
    if (!hasApiKey || !enabled) {
      // Not configured or disabled - set status accordingly
      setValidationStatuses(prev => ({
        ...prev,
        [integrationId]: 'not_configured',
      }));
      return;
    }
    
    // Set pending status
    setValidationStatuses(prev => ({
      ...prev,
      [integrationId]: 'pending',
    }));
    
    // Test connection asynchronously
    try {
      // Build request body based on integration type
      const requestBody: any = {
        apiKey: apiKey,
      };
      
      // OpenAI needs model in config, Runware doesn't
      if (integrationId === 'openai') {
        requestBody.config = {
          model: model || 'gpt-4.1',
          with_response: false, // Simple connection test for status validation
        };
      }
      
      const response = await fetch(
        `${API_BASE_URL}/v1/system/settings/integrations/${integrationId}/test/`,
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          credentials: 'include',
          body: JSON.stringify(requestBody),
        }
      );
      
      const data = await response.json();
      
      if (response.ok && data.success) {
        // Validation successful
        setValidationStatuses(prev => ({
          ...prev,
          [integrationId]: 'success',
        }));
      } else {
        // Validation failed
        console.error(`Validation failed for ${integrationId}:`, data.error || data.message);
        setValidationStatuses(prev => ({
          ...prev,
          [integrationId]: 'error',
        }));
      }
    } catch (error: any) {
      console.error(`Error validating ${integrationId}:`, error);
      setValidationStatuses(prev => ({
        ...prev,
        [integrationId]: 'error',
      }));
    }
  }, []);

  /**
   * Validate all enabled and configured integrations
   * Used on page load to validate all integrations
   */
  const validateEnabledIntegrations = useCallback(async () => {
    // Use functional update to read latest state without adding dependencies
    setIntegrations((currentIntegrations) => {
      // Validate each integration
      ['openai', 'runware'].forEach((id) => {
        const integration = currentIntegrations[id];
        if (!integration) return;
        
        const enabled = integration.enabled === true;
        const apiKey = integration.apiKey;
        const model = integration.model;
        
        // Validate with current state (fire and forget - don't await)
        validateIntegration(id, enabled, apiKey, model);
      });
      
      // Return unchanged - we're just reading state
      return currentIntegrations;
    });
  }, [validateIntegration]);

  // Load integration settings on mount
  useEffect(() => {
    loadIntegrationSettings();
  }, []);

  // Validate integrations after settings are loaded or changed (debounced to prevent excessive validation)
  useEffect(() => {
    // Only validate if integrations have been loaded (not initial empty state)
    const hasLoadedData = Object.values(integrations).some(integ => 
      integ.apiKey !== undefined || integ.enabled !== undefined
    );
    if (!hasLoadedData) return;
    
    // Debounce validation to prevent excessive API calls
    const timeoutId = setTimeout(() => {
      validateEnabledIntegrations();
    }, 500); // Wait 500ms after last change
    
    return () => clearTimeout(timeoutId);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [integrations.openai.enabled, integrations.runware.enabled, integrations.openai.apiKey, integrations.runware.apiKey]);

  const loadIntegrationSettings = async () => {
    try {
      const API_BASE_URL = import.meta.env.VITE_BACKEND_URL || 'https://api.igny8.com/api';
      const integrationIds = ['openai', 'runware', 'image_generation'];
      
      const promises = integrationIds.map(async (id) => {
        try {
          const response = await fetch(
            `${API_BASE_URL}/v1/system/settings/integrations/${id}/`,
            { credentials: 'include' }
          );
          if (response.ok) {
            const data = await response.json();
            if (data.success && data.data) {
              return { id, config: data.data };
            }
          }
          return { id, config: null };
        } catch (error) {
          console.error(`Error loading ${id} settings:`, error);
          return { id, config: null };
        }
      });
      
      const results = await Promise.all(promises);
      
      // Use functional update to avoid stale closure issues
      setIntegrations((prevIntegrations) => {
        const updatedIntegrations = { ...prevIntegrations };
        
        results.forEach(({ id, config }) => {
          if (config && prevIntegrations[id]) {
            updatedIntegrations[id] = {
              ...prevIntegrations[id],
              ...config,
              enabled: config.enabled !== undefined ? config.enabled : prevIntegrations[id].enabled,
            };
          }
        });
        
        return updatedIntegrations;
      });
    } catch (error) {
      console.error('Error loading integration settings:', error);
    }
  };

  // Note: handleToggle removed - now using built-in persistence via IntegrationCard
  // The IntegrationCard component with integrationId prop handles toggle persistence automatically

  const handleSettings = (integrationId: string) => {
    setSelectedIntegration(integrationId);
    setShowSettingsModal(true);
  };

  const handleDetails = (integrationId: string) => {
    setSelectedIntegration(integrationId);
    setShowDetailsModal(true);
  };

  const handleTestConnection = async () => {
    if (!selectedIntegration) return;
    
    // Only OpenAI and Runware support testing
    if (selectedIntegration !== 'openai' && selectedIntegration !== 'runware') {
      toast.warning('Connection testing is only available for OpenAI and Runware');
      return;
    }
    
    const config = integrations[selectedIntegration];
    const apiKey = config.apiKey;
    
    if (!apiKey) {
      toast.error('Please enter an API key first');
      return;
    }
    
    setIsTesting(true);
    
    // Set validation status to pending
    if (selectedIntegration) {
      setValidationStatuses(prev => ({
        ...prev,
        [selectedIntegration]: 'pending',
      }));
    }
    
    try {
      const data = await fetchAPI(`/v1/system/settings/integrations/${selectedIntegration}/test/`, {
        method: 'POST',
        body: JSON.stringify({
          apiKey,
          config: config,
        }),
      });

      if (data.success) {
        toast.success(data.message || 'API connection test successful!');
        if (data.response) {
          toast.info(`Response: ${data.response}`);
        }
        if (data.tokens_used) {
          toast.info(`Tokens used: ${data.tokens_used}`);
        }
        
        // Update validation status to success
        if (selectedIntegration) {
          setValidationStatuses(prev => ({
            ...prev,
            [selectedIntegration]: 'success',
          }));
        }
      } else {
        throw new Error(data.error || 'Connection test failed');
      }
    } catch (error: any) {
      console.error('Error testing connection:', error);
      toast.error(`Connection test failed: ${error.message || 'Unknown error'}`);
      
      // Update validation status to error
      if (selectedIntegration) {
        setValidationStatuses(prev => ({
          ...prev,
          [selectedIntegration]: 'error',
        }));
      }
    } finally {
      setIsTesting(false);
    }
  };

  const handleSaveSettings = async () => {
    if (!selectedIntegration) return;
    
    setIsSaving(true);
    try {
      const config = integrations[selectedIntegration];
      
      // For image_generation, map service to provider and ensure all settings are included
      let configToSave = { ...config };
      if (selectedIntegration === 'image_generation') {
        configToSave = {
          ...config,
          provider: config.service || config.provider || 'openai', // Map service to provider for backend
          // Ensure model is set correctly based on service
          model: config.service === 'openai' ? (config.model || 'dall-e-3') : (config.service === 'runware' ? (config.runwareModel || 'runware:97@1') : config.model),
          // Ensure all image settings have defaults
          image_type: config.image_type || 'realistic',
          max_in_article_images: config.max_in_article_images || 2,
          image_format: config.image_format || 'webp',
          desktop_enabled: config.desktop_enabled !== undefined ? config.desktop_enabled : true,
          mobile_enabled: config.mobile_enabled !== undefined ? config.mobile_enabled : true,
        };
      }
      
      const API_BASE_URL = import.meta.env.VITE_BACKEND_URL || 'https://api.igny8.com/api';
      const endpoint = `${API_BASE_URL}/v1/system/settings/integrations/${selectedIntegration}/save/`;
      
      const response = await fetch(endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify(configToSave),
      });

      // Check if response is HTML (error page)
      const contentType = response.headers.get('content-type') || '';
      if (!contentType.includes('application/json')) {
        const text = await response.text();
        if (text.trim().startsWith('<!DOCTYPE') || text.trim().startsWith('<html')) {
          throw new Error(`Server returned HTML instead of JSON. This usually means the endpoint doesn't exist (404). Response: ${text.substring(0, 200)}`);
        }
      }
      
      let data;
      try {
        const responseText = await response.text();
        data = responseText ? JSON.parse(responseText) : {};
      } catch (parseError: any) {
        const text = await response.text();
        throw new Error(`Failed to parse response as JSON. Response was: ${text.substring(0, 200)}`);
      }
      
      if (!response.ok) {
        throw new Error(data.error || `HTTP ${response.status}: ${response.statusText}`);
      }

      if (data.success) {
        toast.success(data.message || 'Settings saved successfully');
        setShowSettingsModal(false);
        // Reload settings - use setTimeout to avoid state update during render
        setTimeout(() => {
          loadIntegrationSettings().then(() => {
            // Trigger validation after settings are reloaded
            setTimeout(() => validateEnabledIntegrations(), 300);
          }).catch(err => {
            console.error('Error reloading settings after save:', err);
          });
        }, 100);
      } else {
        throw new Error(data.error || 'Failed to save settings');
      }
    } catch (error: any) {
      console.error('Error saving integration settings:', error);
      toast.error(`Failed to save settings: ${error.message || 'Unknown error'}`);
    } finally {
      setIsSaving(false);
    }
  };

  const getDetailsData = (integrationId: string) => {
    const config = integrations[integrationId];
    if (integrationId === 'openai') {
      return [
        { label: 'App Name', value: 'OpenAI API' },
        { label: 'API Key', value: config.apiKey ? `${config.apiKey.substring(0, 20)}...` : 'Not configured' },
        { label: 'Model', value: config.model || 'Not set' },
      ];
    } else if (integrationId === 'runware') {
      return [
        { label: 'App Name', value: 'Runware API' },
        { label: 'API Key', value: config.apiKey ? `${config.apiKey.substring(0, 20)}...` : 'Not configured' },
      ];
    } else if (integrationId === 'image_generation') {
      const service = config.service || 'openai';
      const modelDisplay = service === 'openai' 
        ? (config.model || 'Not set')
        : (config.runwareModel || 'Not set');
      
      return [
        { label: 'Service', value: service === 'openai' ? 'OpenAI' : 'Runware' },
        { label: 'Model', value: modelDisplay },
      ];
    }
    return [];
  };

  const getSettingsFields = useCallback((integrationId: string): FormField[] => {
    const config = integrations[integrationId];
    
    if (integrationId === 'openai') {
      return [
        {
          key: 'apiKey',
          label: 'OpenAI API Key',
          type: 'password',
          value: config.apiKey || '',
          onChange: (value) => {
            setIntegrations({
              ...integrations,
              [integrationId]: { ...config, apiKey: value },
            });
          },
          placeholder: 'Enter your OpenAI API key',
          required: true,
        },
        {
          key: 'model',
          label: 'AI Model',
          type: 'select',
          value: config.model || 'gpt-4.1',
          onChange: (value) => {
            setIntegrations({
              ...integrations,
              [integrationId]: { ...config, model: value },
            });
          },
          options: [
            { value: 'gpt-4.1', label: 'GPT-4.1 - $2.00 / $8.00 per 1M tokens' },
            { value: 'gpt-4o-mini', label: 'GPT-4o mini - $0.15 / $0.60 per 1M tokens' },
            { value: 'gpt-4o', label: 'GPT-4o - $2.50 / $10.00 per 1M tokens' },
          ],
        },
      ];
    } else if (integrationId === 'runware') {
      return [
        {
          key: 'apiKey',
          label: 'Runware API Key',
          type: 'password',
          value: config.apiKey || '',
          onChange: (value) => {
            setIntegrations({
              ...integrations,
              [integrationId]: { ...config, apiKey: value },
            });
          },
          placeholder: 'Enter your Runware API key',
          required: true,
        },
      ];
    } else if (integrationId === 'image_generation') {
      const service = config.service || 'openai';
      
      const fields: FormField[] = [
        {
          key: 'service',
          label: 'Image Generation Service',
          type: 'select',
          value: service,
          onChange: (value) => {
            setIntegrations({
              ...integrations,
              [integrationId]: { 
                ...config, 
                service: value,
                // Reset model when service changes
                model: value === 'openai' ? 'dall-e-3' : undefined,
                runwareModel: value === 'runware' ? 'runware:97@1' : undefined,
              },
            });
          },
          options: [
            { value: 'openai', label: 'OpenAI - Multiple models available' },
            { value: 'runware', label: 'Runware - $0.009 per image' },
          ],
        },
      ];
      
      // Add provider-specific model selector
      if (service === 'openai') {
        fields.push({
          key: 'model',
          label: 'OpenAI Image Model',
          type: 'select',
          value: config.model || 'dall-e-3',
          onChange: (value) => {
            setIntegrations({
              ...integrations,
              [integrationId]: { ...config, model: value },
            });
          },
          options: [
            { value: 'dall-e-3', label: 'DALL·E 3 - $0.040 per image' },
            { value: 'dall-e-2', label: 'DALL·E 2 - $0.020 per image' },
            // Note: gpt-image-1 and gpt-image-1-mini are not valid for OpenAI's /v1/images/generations endpoint
            // They are not currently supported by OpenAI's image generation API
            // Only dall-e-3 and dall-e-2 are supported
          ],
        });
      } else if (service === 'runware') {
        fields.push({
          key: 'runwareModel',
          label: 'Runware Model',
          type: 'select',
          value: config.runwareModel || 'runware:97@1',
          onChange: (value) => {
            setIntegrations({
              ...integrations,
              [integrationId]: { ...config, runwareModel: value },
            });
          },
          options: [
            { value: 'runware:97@1', label: 'HiDream-I1 Full - $0.009 per image' },
            { value: 'runware:gen3a_turbo', label: 'Gen3a Turbo - $0.009 per image' },
            { value: 'runware:gen3a', label: 'Gen3a - $0.009 per image' },
          ],
        });
      }
      
      // Note: API key is configured in OpenAI/Runware integration cards, not here
      // Add Image Generation Settings fields (no API key field)
      fields.push(
        {
          key: 'image_type',
          label: 'Image Type',
          type: 'select',
          value: config.image_type || 'realistic',
          onChange: (value) => {
            setIntegrations({
              ...integrations,
              [integrationId]: { ...config, image_type: value },
            });
          },
          options: [
            { value: 'realistic', label: 'Realistic' },
            { value: 'artistic', label: 'Artistic' },
            { value: 'cartoon', label: 'Cartoon' },
          ],
        },
        {
          key: 'max_in_article_images',
          label: 'Max In-Article Images',
          type: 'select',
          value: String(config.max_in_article_images || 2),
          onChange: (value) => {
            setIntegrations({
              ...integrations,
              [integrationId]: { ...config, max_in_article_images: parseInt(value) },
            });
          },
          options: [
            { value: '1', label: '1 Image' },
            { value: '2', label: '2 Images' },
            { value: '3', label: '3 Images' },
            { value: '4', label: '4 Images' },
            { value: '5', label: '5 Images' },
          ],
        },
        {
          key: 'image_format',
          label: 'Image Format',
          type: 'select',
          value: config.image_format || 'webp',
          onChange: (value) => {
            setIntegrations({
              ...integrations,
              [integrationId]: { ...config, image_format: value },
            });
          },
          options: [
            { value: 'webp', label: 'WEBP' },
            { value: 'jpg', label: 'JPG' },
            { value: 'png', label: 'PNG' },
          ],
        }
      );
      
      return fields;
    }
    return [];
  }, [integrations]);

  // Memoize custom body for image generation modal to prevent infinite loops
  const imageGenerationCustomBody = useMemo(() => {
    if (selectedIntegration !== 'image_generation' || !showSettingsModal) return undefined;
    
    try {
      const fields = getSettingsFields(selectedIntegration);
      const serviceField = fields.find(f => f.key === 'service');
      const service = integrations[selectedIntegration]?.service || 'openai';
      const modelField = fields.find(f => {
        return service === 'openai' ? f.key === 'model' : f.key === 'runwareModel';
      });
      const maxImagesField = fields.find(f => f.key === 'max_in_article_images');
      const imageTypeField = fields.find(f => f.key === 'image_type');
      const imageFormatField = fields.find(f => f.key === 'image_format');
      
      return (
        <div className="space-y-4">
          {/* Row 1: Image Generation Service & Model Selector (2 columns) */}
          <div className="grid grid-cols-2 gap-4">
            {/* Service Selector */}
            {serviceField && (
              <div>
                <Label className="mb-2">
                  {serviceField.label}
                  {serviceField.required && <span className="text-error-500 ml-1">*</span>}
                </Label>
                <SelectDropdown
                  options={serviceField.options || []}
                  placeholder={serviceField.placeholder || serviceField.label}
                  value={serviceField.value || ''}
                  onChange={(value) => serviceField.onChange(value)}
                  className="w-full"
                />
              </div>
            )}
            
            {/* Model Selector */}
            {modelField && (
              <div>
                <Label className="mb-2">
                  {modelField.label}
                  {modelField.required && <span className="text-error-500 ml-1">*</span>}
                </Label>
                <SelectDropdown
                  options={modelField.options || []}
                  placeholder={modelField.placeholder || modelField.label}
                  value={modelField.value || ''}
                  onChange={(value) => modelField.onChange(value)}
                  className="w-full"
                />
              </div>
            )}
          </div>

          {/* Max Images Section */}
          <div className="space-y-3">
            <Label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
              Max Images
            </Label>
            
            {/* Featured Image (full width) */}
            <div className="p-3 rounded-lg border border-gray-200 dark:border-gray-700 bg-gradient-to-r from-purple-500 to-blue-500 text-white">
              <div className="flex items-center justify-between">
                <div>
                  <div className="font-medium">Featured Image</div>
                  <div className="text-xs opacity-90">1280×832 pixels</div>
                </div>
                <div className="text-xs bg-white/20 px-2 py-1 rounded">
                  Always Enabled
                </div>
              </div>
            </div>
          </div>

          {/* Row 2: Desktop & Mobile Images (2 columns) */}
          <div className="grid grid-cols-2 gap-4">
            {/* Desktop Images Checkbox */}
            <div className="flex items-center gap-3 p-3 rounded-lg border border-gray-200 dark:border-gray-700">
              <Checkbox
                checked={integrations[selectedIntegration]?.desktop_enabled !== false}
                onChange={(checked) => {
                  setIntegrations({
                    ...integrations,
                    [selectedIntegration]: {
                      ...integrations[selectedIntegration],
                      desktop_enabled: checked,
                    },
                  });
                }}
              />
              <div>
                <Label className="font-medium text-gray-700 dark:text-gray-300">
                  Desktop Images
                </Label>
                <div className="text-xs text-gray-500 dark:text-gray-400">
                  1024×1024 pixels
                </div>
              </div>
            </div>
            
            {/* Mobile Images Checkbox */}
            <div className="flex items-center gap-3 p-3 rounded-lg border border-gray-200 dark:border-gray-700">
              <Checkbox
                checked={integrations[selectedIntegration]?.mobile_enabled !== false}
                onChange={(checked) => {
                  setIntegrations({
                    ...integrations,
                    [selectedIntegration]: {
                      ...integrations[selectedIntegration],
                      mobile_enabled: checked,
                    },
                  });
                }}
              />
              <div>
                <Label className="font-medium text-gray-700 dark:text-gray-300">
                  Mobile Images
                </Label>
                <div className="text-xs text-gray-500 dark:text-gray-400">
                  960×1280 pixels
                </div>
              </div>
            </div>
          </div>

          {/* Row 3: Max In-Article Images, Image Type & Image Format (3 columns) */}
          <div className="grid grid-cols-3 gap-4">
            {/* Max In-Article Images */}
            {maxImagesField && (
              <div>
                <Label className="mb-2">
                  {maxImagesField.label}
                  {maxImagesField.required && <span className="text-error-500 ml-1">*</span>}
                </Label>
                <SelectDropdown
                  options={maxImagesField.options || []}
                  placeholder={maxImagesField.placeholder || maxImagesField.label}
                  value={maxImagesField.value || ''}
                  onChange={(value) => maxImagesField.onChange(value)}
                  className="w-full"
                />
              </div>
            )}
            
            {/* Image Type */}
            {imageTypeField && (
              <div>
                <Label className="mb-2">
                  {imageTypeField.label}
                  {imageTypeField.required && <span className="text-error-500 ml-1">*</span>}
                </Label>
                <SelectDropdown
                  options={imageTypeField.options || []}
                  placeholder={imageTypeField.placeholder || imageTypeField.label}
                  value={imageTypeField.value || ''}
                  onChange={(value) => imageTypeField.onChange(value)}
                  className="w-full"
                />
              </div>
            )}
            
            {/* Image Format */}
            {imageFormatField && (
              <div>
                <Label className="mb-2">
                  {imageFormatField.label}
                  {imageFormatField.required && <span className="text-error-500 ml-1">*</span>}
                </Label>
                <SelectDropdown
                  options={imageFormatField.options || []}
                  placeholder={imageFormatField.placeholder || imageFormatField.label}
                  value={imageFormatField.value || ''}
                  onChange={(value) => imageFormatField.onChange(value)}
                  className="w-full"
                />
              </div>
            )}
          </div>
        </div>
      );
    } catch (error) {
      console.error('Error rendering image generation form:', error);
      return <div className="text-error-500">Error loading form. Please refresh the page.</div>;
    }
  }, [selectedIntegration, integrations, showSettingsModal, getSettingsFields]);

  return (
    <>
      <PageMeta title="API Integration - IGNY8" description="External integrations" />
      
      <div className="space-y-8">
        {/* Integration Cards with Validation Cards */}
        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 xl:grid-cols-3">
          {/* OpenAI Integration + Validation */}
          <div className="space-y-5">
            <IntegrationCard
              icon={<OpenAIIcon />}
              title="OpenAI"
              description="AI-powered content generation and analysis with DALL-E image generation"
              validationStatus={validationStatuses.openai}
              integrationId="openai"
              onToggleSuccess={(enabled, data) => {
                // Refresh status circle when toggle changes
                // Use API key from hook's data (most up-to-date) or fallback to integrations state
                const apiKey = data?.apiKey || integrations.openai.apiKey;
                const model = data?.model || integrations.openai.model;
                
                // Validate with current enabled state and API key
                validateIntegration('openai', enabled, apiKey, model);
              }}
              onSettings={() => handleSettings('openai')}
              onDetails={() => handleDetails('openai')}
            />
            <ValidationCard
              title="OpenAI API Validation"
              description="Two-way response validation with actual request and response testing"
              integrationId="openai"
              icon={<OpenAIIcon />}
            />
          </div>

          {/* Runware Integration + Validation */}
          <div className="space-y-5">
            <IntegrationCard
              icon={<RunwareIcon />}
              title="Runware"
              description="High-quality AI image generation with Runware's models ($0.009 per image)"
              validationStatus={validationStatuses.runware}
              integrationId="runware"
              modelName={
                integrations.image_generation?.service === 'runware' && integrations.image_generation.runwareModel
                  ? (() => {
                      // Map model ID to display name
                      const modelDisplayNames: Record<string, string> = {
                        'runware:97@1': 'HiDream-I1 Full',
                        'runware:gen3a_turbo': 'Gen3a Turbo',
                        'runware:gen3a': 'Gen3a',
                      };
                      return modelDisplayNames[integrations.image_generation.runwareModel] || integrations.image_generation.runwareModel;
                    })()
                  : undefined
              }
              onToggleSuccess={(enabled, data) => {
                // Refresh status circle when toggle changes
                // Use API key from hook's data (most up-to-date) or fallback to integrations state
                const apiKey = data?.apiKey || integrations.runware.apiKey;
                
                // Validate with current enabled state and API key
                validateIntegration('runware', enabled, apiKey);
              }}
              onSettings={() => handleSettings('runware')}
              onDetails={() => handleDetails('runware')}
            />
            <ValidationCard
              title="Runware API Validation"
              description="Using 128x128 image generation request for connection testing"
              integrationId="runware"
              icon={<RunwareIcon />}
            />
            
          </div>

          {/* Image Generation Service Card */}
          <div className="space-y-5">
            <ImageServiceCard
              icon={
                <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40" fill="none">
                  <rect width="40" height="40" rx="8" fill="#9333EA"/>
                  <path d="M12 16L20 10L28 16V28C28 28.5304 27.7893 29.0391 27.4142 29.4142C27.0391 29.7893 26.5304 30 26 30H14C13.4696 30 12.9609 29.7893 12.5858 29.4142C12.2107 29.0391 12 28.5304 12 28V16Z" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                  <path d="M16 30V20H24V30" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              }
              title="Image Generation Service"
              description="Default image generation service and model selection for app-wide use"
              validationStatus={validationStatuses.image_generation}
              onSettings={() => handleSettings('image_generation')}
              onDetails={() => handleDetails('image_generation')}
            />
          {/* AI Integration & Image Generation Testing Info Card */}
          <Alert
              variant="info"
              title="AI Integration & Image Generation Testing"
              message="Configure and test your AI integrations on this page.
              Set up OpenAI and Runware API keys, validate connections, and test image generation with different models and parameters.
              Before you start, please read the documentation for each integration.
              
              Make sure to use the correct API keys and models for each integration."
            />
          </div>
        </div>

        {/* Image Generation Testing Cards - 50/50 Split */}
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
          <ImageGenerationCard
            title="Generate Image"
            description="Configure image generation parameters"
            integrationId="openai"
            icon={<OpenAIIcon />}
          />
          <ImageResultCard
            title="Generated Image"
            description="AI-generated image results"
            icon={
              <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40" fill="none">
                <rect width="40" height="40" rx="8" fill="#10B981"/>
                <path d="M12 16L20 10L28 16V28C28 28.5304 27.7893 29.0391 27.4142 29.4142C27.0391 29.7893 26.5304 30 26 30H14C13.4696 30 12.9609 29.7893 12.5858 29.4142C12.2107 29.0391 12 28.5304 12 28V16Z" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                <path d="M16 30V20H24V30" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            }
          />
        </div>
      </div>

      {/* Details Modal */}
      <Modal
        isOpen={showDetailsModal}
        onClose={() => setShowDetailsModal(false)}
        className="max-w-2xl"
      >
        <div className="p-6">
          <h3 className="text-lg font-semibold mb-2 text-gray-800 dark:text-white">
            Integration details
          </h3>
          <p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
            Check the credentials and settings for your connected app.
          </p>
          
          <div className="space-y-4">
            {selectedIntegration && getDetailsData(selectedIntegration).map((item, index) => (
              <div key={index} className="flex justify-between items-start border-b border-gray-200 dark:border-gray-700 pb-3">
                <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  {item.label}
                </span>
                <span className="text-sm text-gray-900 dark:text-white text-right max-w-xs break-words">
                  {item.value}
                </span>
              </div>
            ))}
          </div>

          <div className="flex justify-end mt-6">
            <Button variant="outline" onClick={() => setShowDetailsModal(false)}>
              Close
            </Button>
          </div>
        </div>
      </Modal>

      {/* Settings Modal */}
      {selectedIntegration && (
        <>
          <FormModal
            isOpen={showSettingsModal}
            onClose={() => setShowSettingsModal(false)}
            onSubmit={handleSaveSettings}
            title="Integration settings"
            fields={getSettingsFields(selectedIntegration)}
            submitLabel="Save Changes"
            cancelLabel="Close"
            isLoading={isSaving}
            customBody={imageGenerationCustomBody}
            customFooter={
              (selectedIntegration === 'openai' || selectedIntegration === 'runware') ? (
                <div className="flex justify-between items-center pt-4">
                  <Button
                    type="button"
                    variant="secondary"
                    onClick={() => {
                      handleTestConnection();
                    }}
                    disabled={isTesting || isSaving || !integrations[selectedIntegration]?.apiKey}
                    className="flex items-center gap-2"
                  >
                    {isTesting ? 'Testing...' : 'Test Connection'}
                  </Button>
                  <div className="flex gap-3">
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => setShowSettingsModal(false)}
                      disabled={isSaving || isTesting}
                    >
                      Close
                    </Button>
                    <Button
                      type="submit"
                      variant="primary"
                      disabled={isSaving || isTesting}
                    >
                      {isSaving ? 'Saving...' : 'Save Changes'}
                    </Button>
                  </div>
                </div>
              ) : undefined
            }
          />
        </>
      )}
    </>
  );
}
