/**
 * WordPress Integration Form Component
 * Simplified - uses only Site.wp_api_key, no SiteIntegration model needed
 */
import React, { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import Button from '../ui/button/Button';
import IconButton from '../ui/button/IconButton';
import Label from '../form/Label';
import Input from '../form/input/InputField';
import Checkbox from '../form/input/Checkbox';
import Switch from '../form/switch/Switch';
import { useToast } from '../ui/toast/ToastContainer';
import { fetchAPI, API_BASE_URL } from '../../services/api';
import { 
  CheckCircleIcon,
  AlertIcon,
  DownloadIcon,
  PlusIcon,
  CopyIcon,
  TrashBinIcon,
  GlobeIcon,
  KeyIcon,
  RefreshCwIcon,
  InfoIcon
} from '../../icons';

interface WordPressIntegrationFormProps {
  siteId: number;
  siteName?: string;
  siteUrl?: string;
  wpApiKey?: string; // API key from Site.wp_api_key
  onApiKeyUpdate?: (apiKey: string | null) => void;
}

export default function WordPressIntegrationForm({
  siteId,
  siteName,
  siteUrl,
  wpApiKey,
  onApiKeyUpdate,
}: WordPressIntegrationFormProps) {
  const toast = useToast();
  const [loading, setLoading] = useState(false);
  const [generatingKey, setGeneratingKey] = useState(false);
  const [apiKey, setApiKey] = useState<string>('');
  const [apiKeyVisible, setApiKeyVisible] = useState(false);
  const [pluginInfo, setPluginInfo] = useState<any>(null);
  const [loadingPlugin, setLoadingPlugin] = useState(false);
  
  // Connection status state
  const [connectionStatus, setConnectionStatus] = useState<'unknown' | 'testing' | 'connected' | 'api_key_pending' | 'plugin_missing' | 'error'>('unknown');
  const [connectionMessage, setConnectionMessage] = useState<string>('');
  const [testingConnection, setTestingConnection] = useState(false);

  // Load API key from wpApiKey prop (from Site.wp_api_key) on mount or when it changes
  useEffect(() => {
    if (wpApiKey) {
      setApiKey(wpApiKey);
    } else {
      setApiKey('');
    }
  }, [wpApiKey]);

  // Fetch plugin information
  useEffect(() => {
    const fetchPluginInfo = async () => {
      try {
        setLoadingPlugin(true);
        const response = await fetchAPI('/plugins/wordpress/latest/');
        setPluginInfo(response);
      } catch (error) {
        console.error('Failed to fetch plugin info:', error);
      } finally {
        setLoadingPlugin(false);
      }
    };

    fetchPluginInfo();
  }, []);

  // Test connection when API key exists
  const testConnection = async () => {
    if (!apiKey || !siteUrl) {
      setConnectionStatus('unknown');
      setConnectionMessage('API key or site URL missing');
      return;
    }

    try {
      setTestingConnection(true);
      setConnectionStatus('testing');
      setConnectionMessage('Testing connection...');

      // Call backend to test connection to WordPress
      // Backend reads API key from Site.wp_api_key (single source of truth)
      const response = await fetchAPI('/v1/integration/integrations/test-connection/', {
        method: 'POST',
        body: JSON.stringify({
          site_id: siteId,
        }),
      });

      if (response.success) {
        // Check the health checks from response
        const healthChecks = response.health_checks || {};
        
        // CRITICAL: api_key_verified confirms WordPress accepts our API key
        if (healthChecks.api_key_verified) {
          setConnectionStatus('connected');
          setConnectionMessage('WordPress is connected and API key verified');
          toast.success('WordPress connection verified!');
        } else if (healthChecks.plugin_has_api_key && !healthChecks.api_key_verified) {
          // WordPress has A key, but it's NOT the same as IGNY8's key
          setConnectionStatus('api_key_pending');
          setConnectionMessage('API key mismatch - copy the key from IGNY8 to WordPress plugin');
          toast.warning('WordPress has different API key. Please update WordPress with the key shown above.');
        } else if (healthChecks.plugin_installed && !healthChecks.plugin_has_api_key) {
          setConnectionStatus('api_key_pending');
          setConnectionMessage('Plugin installed - please add API key in WordPress');
          toast.warning('Plugin found but API key not configured in WordPress');
        } else if (!healthChecks.plugin_installed) {
          setConnectionStatus('plugin_missing');
          setConnectionMessage('IGNY8 plugin not installed on WordPress site');
          toast.warning('WordPress site reachable but plugin not found');
        } else {
          setConnectionStatus('error');
          setConnectionMessage(response.message || 'Connection verification incomplete');
          toast.error(response.message || 'Connection test incomplete');
        }
      } else {
        setConnectionStatus('error');
        setConnectionMessage(response.message || 'Connection test failed');
        toast.error(response.message || 'Connection test failed');
      }
    } catch (error: any) {
      setConnectionStatus('error');
      setConnectionMessage(error.message || 'Connection test failed');
      toast.error(`Connection test failed: ${error.message}`);
    } finally {
      setTestingConnection(false);
    }
  };

  // DON'T auto-test - only test when user clicks Test button
  // Just set status based on whether key exists
  useEffect(() => {
    if (apiKey && siteUrl) {
      // Key exists - show as configured, but not yet tested/connected
      setConnectionStatus('unknown');
      setConnectionMessage('Click Test to verify connection');
    } else {
      setConnectionStatus('unknown');
      setConnectionMessage('');
    }
  }, [apiKey, siteUrl]);

  const handleGenerateApiKey = async () => {
    try {
      setGeneratingKey(true);
      
      // Call the simplified generate-api-key endpoint
      const response = await fetchAPI('/v1/integration/integrations/generate-api-key/', {
        method: 'POST',
        body: JSON.stringify({ site_id: siteId }),
      });
      
      const newKey = response.api_key;
      setApiKey(newKey);
      setApiKeyVisible(true);
      
      // Notify parent component
      if (onApiKeyUpdate) {
        onApiKeyUpdate(newKey);
      }
      
      toast.success('API key generated successfully');
    } catch (error: any) {
      toast.error(`Failed to generate API key: ${error.message}`);
    } finally {
      setGeneratingKey(false);
    }
  };

  const handleRegenerateApiKey = async () => {
    if (!confirm('Are you sure you want to regenerate the API key? The old key will no longer work.')) {
      return;
    }
    try {
      setGeneratingKey(true);
      
      // Call the generate-api-key endpoint to create a new key
      const response = await fetchAPI('/v1/integration/integrations/generate-api-key/', {
        method: 'POST',
        body: JSON.stringify({ site_id: siteId }),
      });
      
      const newKey = response.api_key;
      setApiKey(newKey);
      setApiKeyVisible(true);
      
      // Notify parent component
      if (onApiKeyUpdate) {
        onApiKeyUpdate(newKey);
      }
      
      toast.success('API key regenerated successfully');
    } catch (error: any) {
      toast.error(`Failed to regenerate API key: ${error.message}`);
    } finally {
      setGeneratingKey(false);
    }
  };

  const handleRevokeApiKey = async () => {
    if (!confirm('Are you sure you want to revoke the API key? Your WordPress plugin will stop working until you generate a new key.')) {
      return;
    }
    try {
      setGeneratingKey(true);
      
      // Revoke API key via dedicated endpoint (single source of truth: Site.wp_api_key)
      await fetchAPI('/v1/integration/integrations/revoke-api-key/', {
        method: 'POST',
        body: JSON.stringify({ site_id: siteId }),
      });
      
      setApiKey('');
      setApiKeyVisible(false);
      setConnectionStatus('unknown');
      setConnectionMessage('');
      
      // Notify parent component
      if (onApiKeyUpdate) {
        onApiKeyUpdate(null);
      }
      
      toast.success('API key revoked successfully');
    } catch (error: any) {
      toast.error(`Failed to revoke API key: ${error.message}`);
    } finally {
      setGeneratingKey(false);
    }
  };

  const handleCopyApiKey = () => {
    if (apiKey) {
      navigator.clipboard.writeText(apiKey);
      toast.success('API key copied to clipboard');
    }
  };

  const handleDownloadPlugin = () => {
    // Use the backend API endpoint for plugin download (must use full API URL, not relative)
    const pluginUrl = `${API_BASE_URL}/plugins/igny8-wp-bridge/download/`;
    window.open(pluginUrl, '_blank');
    toast.success('Plugin download started');
  };

  const maskApiKey = (key: string) => {
    if (!key) return '';
    if (key.length <= 12) return key;
    return key.substring(0, 8) + '**********' + key.substring(key.length - 4);
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between gap-3">
        <div className="flex items-center gap-3">
          <div className="p-3 bg-purple-100 dark:bg-purple-900/30 rounded-lg">
            <GlobeIcon className="w-6 h-6 text-purple-600 dark:text-purple-400" />
          </div>
          <div>
            <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
              WordPress Integration
            </h2>
            <p className="text-sm text-gray-600 dark:text-gray-400">
              Connect your WordPress site using the IGNY8 WP Bridge plugin
            </p>
          </div>
        </div>
        
        {/* Connection Status & Test Button */}
        {apiKey && (
          <div className="flex items-center gap-3">
            {/* Status Indicator - Uses theme colors from design-system */}
            <div className={`flex items-center gap-2 px-3 py-1.5 rounded-lg border ${
              connectionStatus === 'connected' 
                ? 'bg-success-50 dark:bg-success-900/20 border-success-200 dark:border-success-800' 
                : connectionStatus === 'testing'
                ? 'bg-brand-50 dark:bg-brand-900/20 border-brand-200 dark:border-brand-800'
                : connectionStatus === 'api_key_pending'
                ? 'bg-warning-50 dark:bg-warning-900/20 border-warning-200 dark:border-warning-800'
                : connectionStatus === 'plugin_missing'
                ? 'bg-warning-50 dark:bg-warning-900/20 border-warning-200 dark:border-warning-800'
                : connectionStatus === 'error'
                ? 'bg-error-50 dark:bg-error-900/20 border-error-200 dark:border-error-800'
                : 'bg-gray-50 dark:bg-gray-800/50 border-gray-200 dark:border-gray-700'
            }`}>
              {connectionStatus === 'connected' && (
                <><CheckCircleIcon className="w-4 h-4 text-success-600 dark:text-success-400" />
                <span className="text-sm font-medium text-success-700 dark:text-success-300">Connected</span></>
              )}
              {connectionStatus === 'testing' && (
                <><RefreshCwIcon className="w-4 h-4 text-brand-600 dark:text-brand-400 animate-spin" />
                <span className="text-sm font-medium text-brand-700 dark:text-brand-300">Testing...</span></>
              )}
              {connectionStatus === 'api_key_pending' && (
                <><AlertIcon className="w-4 h-4 text-warning-600 dark:text-warning-400" />
                <span className="text-sm font-medium text-warning-700 dark:text-warning-300">Pending Setup</span></>
              )}
              {connectionStatus === 'plugin_missing' && (
                <><AlertIcon className="w-4 h-4 text-warning-600 dark:text-warning-400" />
                <span className="text-sm font-medium text-warning-700 dark:text-warning-300">Plugin Missing</span></>
              )}
              {connectionStatus === 'error' && (
                <><AlertIcon className="w-4 h-4 text-error-600 dark:text-error-400" />
                <span className="text-sm font-medium text-error-700 dark:text-error-300">Error</span></>
              )}
              {connectionStatus === 'unknown' && (
                <><InfoIcon className="w-4 h-4 text-gray-500 dark:text-gray-400" />
                <span className="text-sm font-medium text-gray-600 dark:text-gray-400">Not Tested</span></>
              )}
            </div>
            
            {/* Test Connection Button - IconButton only */}
            <IconButton
              onClick={testConnection}
              variant="outline"
              tone="brand"
              disabled={testingConnection || !apiKey}
              title="Test Connection"
              icon={<RefreshCwIcon className={`w-4 h-4 ${testingConnection ? 'animate-spin' : ''}`} />}
            />
          </div>
        )}
      </div>

      {/* API Keys Table */}
      <Card className="p-0">
        <div className="flex flex-col gap-5 sm:flex-row sm:items-center justify-between border-b border-gray-100 dark:border-gray-800 px-6 py-4">
          <div>
            <h3 className="text-lg font-semibold text-gray-800 dark:text-white/90">API Keys</h3>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              API keys are used to authenticate requests to the IGNY8 API
            </p>
          </div>
          {!apiKey && (
            <div>
              <Button
                onClick={handleGenerateApiKey}
                variant="solid"
                disabled={generatingKey}
                startIcon={generatingKey ? <RefreshCwIcon className="w-4 h-4 animate-spin" /> : <PlusIcon className="w-4 h-4" />}
              >
                {generatingKey ? 'Generating...' : 'Add API Key'}
              </Button>
            </div>
          )}
        </div>
        
        {apiKey ? (
          <div className="custom-scrollbar overflow-x-auto px-6 pb-4">
            <table className="min-w-full">
              <thead>
                <tr className="border-b border-gray-100 dark:border-gray-800">
                  <th className="py-3 pr-5 text-left text-xs font-medium text-gray-500 dark:text-gray-400">Name</th>
                  <th className="px-5 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400">Status</th>
                  <th className="px-5 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400">Created</th>
                  <th className="px-5 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400">Action</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
                <tr>
                  <td className="py-3 pr-5 whitespace-nowrap">
                    <div>
                      <label htmlFor="api-key" className="mb-2 inline-block text-sm text-gray-700 dark:text-gray-400">
                        WordPress Integration API Key
                      </label>
                      <div className="flex items-center gap-3">
                        <div className="relative">
                          <Input
                            className="w-full min-w-[360px] pr-[90px] font-mono"
                            readOnly
                            type={apiKeyVisible ? 'text' : 'password'}
                            value={apiKeyVisible ? apiKey : maskApiKey(apiKey)}
                            onChange={() => {}} // No-op to satisfy React
                          />
                          <IconButton
                            onClick={handleCopyApiKey}
                            variant="outline"
                            tone="neutral"
                            size="sm"
                            className="absolute top-1/2 right-0 -translate-y-1/2 rounded-l-none"
                            icon={<CopyIcon className="w-4 h-4" />}
                          />
                        </div>
                        <div className="group relative inline-block">
                          <IconButton
                            onClick={handleRegenerateApiKey}
                            disabled={generatingKey}
                            variant="outline"
                            title="Regenerate"
                            icon={<RefreshCwIcon className={`w-5 h-5 ${generatingKey ? 'animate-spin' : ''}`} />}
                          />
                          <div className="invisible absolute bottom-full left-1/2 z-50 mb-2.5 -translate-x-1/2 opacity-0 transition-opacity duration-300 group-hover:visible group-hover:opacity-100">
                            <div className="relative">
                              <div className="rounded-lg bg-white px-3 py-2 text-xs font-medium whitespace-nowrap text-gray-700 shadow-xs dark:bg-gray-800 dark:text-white">
                                Regenerate
                              </div>
                              <div className="absolute -bottom-1 left-1/2 h-3 w-4 -translate-x-1/2 rotate-45 bg-white dark:bg-gray-800"></div>
                            </div>
                          </div>
                        </div>
                        <IconButton
                          onClick={() => setApiKeyVisible(!apiKeyVisible)}
                          variant="outline"
                        >
                          {apiKeyVisible ? (
                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.29 3.29m0 0L3 9.88m3.29-3.29L9.88 3" />
                            </svg>
                          ) : (
                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                            </svg>
                          )}
                        </IconButton>
                      </div>
                    </div>
                  </td>
                  <td className="px-5 py-3 whitespace-nowrap">
                    <span className="inline-flex items-center justify-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium bg-success-50 text-success-600 dark:bg-success-500/15 dark:text-success-500">
                      Active
                    </span>
                  </td>
                  <td className="px-5 py-3 text-sm whitespace-nowrap text-gray-500 dark:text-gray-400">
                    {new Date().toLocaleDateString('en-US', { day: 'numeric', month: 'short', year: 'numeric' })}
                  </td>
                  <td className="px-5 py-3 whitespace-nowrap">
                    <div className="flex items-center gap-3">
                      <IconButton
                        onClick={handleRegenerateApiKey}
                        disabled={generatingKey}
                        variant="ghost"
                        title="Regenerate API key"
                        icon={<RefreshCwIcon className={`w-5 h-5 ${generatingKey ? 'animate-spin' : ''}`} />}
                      />
                      <IconButton
                        onClick={handleRevokeApiKey}
                        disabled={generatingKey}
                        variant="ghost"
                        tone="danger"
                        title="Revoke API key"
                        icon={<TrashBinIcon className="w-5 h-5" />}
                      />
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        ) : (
          <div className="px-6 py-8 text-center text-gray-500 dark:text-gray-400">
            <p className="text-sm">No API key generated yet. Click "Add API Key" to generate one.</p>
          </div>
        )}
      </Card>

      {/* Plugin Download Section */}
      {apiKey && (
        <Card className="p-6">
          <div className="space-y-4">
            <div className="flex items-start justify-between">
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                  <DownloadIcon className="w-5 h-5 text-purple-600 dark:text-purple-400" />
                  IGNY8 WP Bridge Plugin
                </h3>
                <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                  Download and install the plugin on your WordPress site
                </p>
              </div>
              <Button
                onClick={handleDownloadPlugin}
                variant="solid"
                startIcon={<DownloadIcon className="w-4 h-4" />}
                disabled={loadingPlugin}
              >
                Download Plugin
              </Button>
            </div>

            {/* Plugin Details */}
            {pluginInfo && (
              <div className="border-t border-gray-200 dark:border-gray-700 pt-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">Version</p>
                    <p className="text-sm font-medium text-gray-900 dark:text-white">
                      {pluginInfo.version}
                    </p>
                  </div>
                  <div>
                    <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">File Size</p>
                    <p className="text-sm font-medium text-gray-900 dark:text-white">
                      {(pluginInfo.file_size / 1024).toFixed(1)} KB
                    </p>
                  </div>
                  <div>
                    <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">WordPress Version</p>
                    <p className="text-sm font-medium text-gray-900 dark:text-white">
                      5.0+
                    </p>
                  </div>
                  <div>
                    <p className="text-xs text-gray-500 dark:text-gray-400 mb-1">PHP Version</p>
                    <p className="text-sm font-medium text-gray-900 dark:text-white">
                      7.4+
                    </p>
                  </div>
                </div>

                {/* Requirements & Instructions */}
                <div className="mt-4 p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
                  <div className="flex items-start gap-2">
                    <InfoIcon className="w-4 h-4 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0" />
                    <div className="flex-1">
                      <p className="text-xs font-medium text-blue-900 dark:text-blue-300 mb-1">
                        Installation Steps
                      </p>
                      <ol className="text-xs text-blue-800 dark:text-blue-400 space-y-1 list-decimal list-inside">
                        <li>Download the plugin ZIP file</li>
                        <li>Go to your WordPress admin → Plugins → Add New</li>
                        <li>Click "Upload Plugin" and select the ZIP file</li>
                        <li>Activate the plugin after installation</li>
                        <li>Configure plugin with your API key from above</li>
                      </ol>
                    </div>
                  </div>
                </div>

                {/* Changelog */}
                {pluginInfo.changelog && (
                  <div className="mt-3 text-xs text-gray-600 dark:text-gray-400">
                    <p className="font-medium text-gray-900 dark:text-white mb-1">What's New:</p>
                    <p className="whitespace-pre-line">{pluginInfo.changelog}</p>
                  </div>
                )}
              </div>
            )}

            {loadingPlugin && (
              <div className="border-t border-gray-200 dark:border-gray-700 pt-4">
                <p className="text-sm text-gray-500 dark:text-gray-400 text-center">
                  Loading plugin information...
                </p>
              </div>
            )}
          </div>
        </Card>
      )}
    </div>
  );
}
