/**
 * WordPress Integration Form Component
 * Inline form for WordPress integration with API key generation and plugin download
 */
import React, { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import Button from '../ui/button/Button';
import Label from '../form/Label';
import Input from '../form/input/InputField';
import Checkbox from '../form/input/Checkbox';
import { useToast } from '../ui/toast/ToastContainer';
import { integrationApi, SiteIntegration } from '../../services/integration.api';
import { fetchAPI } from '../../services/api';
import { 
  CheckCircleIcon,
  AlertIcon,
  DownloadIcon,
  PlusIcon,
  CopyIcon,
  TrashBinIcon
} from '../../icons';
import { Globe, Key, RefreshCw } from 'lucide-react';

interface WordPressIntegrationFormProps {
  siteId: number;
  integration: SiteIntegration | null;
  siteName?: string;
  siteUrl?: string;
  onIntegrationUpdate?: (integration: SiteIntegration) => void;
}

export default function WordPressIntegrationForm({
  siteId,
  integration,
  siteName,
  siteUrl,
  onIntegrationUpdate,
}: WordPressIntegrationFormProps) {
  const toast = useToast();
  const [loading, setLoading] = useState(false);
  const [generatingKey, setGeneratingKey] = useState(false);
  const [apiKey, setApiKey] = useState<string>('');
  const [apiKeyVisible, setApiKeyVisible] = useState(false);

  // Load API key from site settings on mount
  useEffect(() => {
    loadApiKeyFromSite();
  }, [siteId]);

  const loadApiKeyFromSite = async () => {
    try {
      const siteData = await fetchAPI(`/v1/auth/sites/${siteId}/`);
      if (siteData?.wp_api_key) {
        setApiKey(siteData.wp_api_key);
      } else {
        // Clear API key if it doesn't exist in the backend
        setApiKey('');
      }
    } catch (error) {
      // API key might not exist yet, that's okay
      setApiKey('');
    }
  };

  const handleGenerateApiKey = async () => {
    try {
      setGeneratingKey(true);
      // Generate API key - format: igny8_site_{siteId}_{timestamp}_{random}
      const timestamp = Date.now();
      const random = Math.random().toString(36).substring(2, 15);
      const token = `igny8_site_${siteId}_${timestamp}_${random}`;
      setApiKey(token);
      setApiKeyVisible(true);
      
      // Save API key to site settings immediately
      await saveApiKeyToSite(token);
      
      // Reload the API key from backend to ensure consistency
      await loadApiKeyFromSite();
      
      toast.success('API key generated and saved 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);
      // Generate new API key
      const timestamp = Date.now();
      const random = Math.random().toString(36).substring(2, 15);
      const token = `igny8_site_${siteId}_${timestamp}_${random}`;
      setApiKey(token);
      setApiKeyVisible(true);
      
      // Save new API key to site settings
      await saveApiKeyToSite(token);
      
      // Reload the API key from backend to ensure consistency
      await loadApiKeyFromSite();
      
      toast.success('API key regenerated and saved 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);
      // Clear API key from site settings by setting it to empty string
      await fetchAPI(`/v1/auth/sites/${siteId}/`, {
        method: 'PATCH',
        body: JSON.stringify({ wp_api_key: '' }),
      });
      
      setApiKey('');
      setApiKeyVisible(false);
      
      // Trigger integration update to reload the integration state
      if (onIntegrationUpdate && integration) {
        await loadApiKeyFromSite();
        // Reload integration to reflect changes
        const integrations = await integrationApi.getSiteIntegrations(siteId);
        const wp = integrations.find(i => i.platform === 'wordpress');
        if (wp) {
          onIntegrationUpdate(wp);
        }
      }
      
      toast.success('API key revoked successfully');
    } catch (error: any) {
      toast.error(`Failed to revoke API key: ${error.message}`);
    } finally {
      setGeneratingKey(false);
    }
  };

  const saveApiKeyToSite = async (key: string) => {
    try {
      await fetchAPI(`/v1/auth/sites/${siteId}/`, {
        method: 'PATCH',
        body: JSON.stringify({ wp_api_key: key }),
      });
    } catch (error: any) {
      console.error('Failed to save API key to site:', error);
      throw error;
    }
  };

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

  const handleDownloadPlugin = () => {
    const pluginUrl = `https://github.com/igny8/igny8-wp-bridge/releases/latest/download/igny8-wp-bridge.zip`;
    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);
  };

  // Toggle integration enabled status
  const [integrationEnabled, setIntegrationEnabled] = useState(integration?.is_active ?? true);

  const handleToggleIntegration = async (enabled: boolean) => {
    try {
      setIntegrationEnabled(enabled);
      
      if (integration) {
        // Update existing integration
        await integrationApi.updateIntegration(integration.id, {
          is_active: enabled,
        } as any);
        toast.success(enabled ? 'Integration enabled' : 'Integration disabled');
        
        // Reload integration
        const updated = await integrationApi.getWordPressIntegration(siteId);
        if (onIntegrationUpdate && updated) {
          onIntegrationUpdate(updated);
        }
      } else if (enabled && apiKey) {
        // Create integration when enabling for first time
        // Use API key-only authentication (no username/password required)
        await integrationApi.saveWordPressIntegration(siteId, {
          url: siteUrl || '',
          username: '', // Optional when using API key
          app_password: '', // Optional when using API key
          api_key: apiKey,
          is_active: enabled,
          sync_enabled: true,
        });
        toast.success('Integration created and enabled');
        
        // Reload integration
        const updated = await integrationApi.getWordPressIntegration(siteId);
        if (onIntegrationUpdate && updated) {
          onIntegrationUpdate(updated);
        }
      } else if (enabled && !apiKey) {
        // Toggle enabled but no API key - show error
        toast.error('API key is required to enable WordPress integration');
        setIntegrationEnabled(false);
      }
    } catch (error: any) {
      toast.error(`Failed to update integration: ${error.message}`);
      // Revert on error
      setIntegrationEnabled(!enabled);
    }
  };

  useEffect(() => {
    if (integration) {
      setIntegrationEnabled(integration.is_active ?? true);
    }
  }, [integration]);

  return (
    <div className="space-y-6">
      {/* Header with Toggle */}
      <div className="flex items-center justify-between gap-3">
        <div className="flex items-center gap-3">
          <div className="p-3 bg-indigo-100 dark:bg-indigo-900/30 rounded-lg">
            <Globe className="w-6 h-6 text-indigo-600 dark:text-indigo-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>
        
        {/* Toggle Switch */}
        {apiKey && (
          <div className="flex items-center gap-3">
            <span className="text-sm font-medium text-gray-700 dark:text-gray-300">
              {integrationEnabled ? 'Enabled' : 'Disabled'}
            </span>
            <button
              type="button"
              onClick={() => handleToggleIntegration(!integrationEnabled)}
              className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-2 ${
                integrationEnabled ? 'bg-brand-600' : 'bg-gray-300 dark:bg-gray-600'
              }`}
              role="switch"
              aria-checked={integrationEnabled}
            >
              <span
                className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                  integrationEnabled ? 'translate-x-6' : 'translate-x-1'
                }`}
              />
            </button>
          </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}
              >
                {generatingKey ? (
                  <>
                    <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                    Generating...
                  </>
                ) : (
                  <>
                    <PlusIcon className="w-4 h-4 mr-2" />
                    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
                            id="api-key"
                            className="dark:bg-dark-900 shadow-theme-xs focus:border-brand-300 focus:ring-brand-500/10 dark:focus:border-brand-800 h-11 w-full min-w-[360px] rounded-lg border border-gray-300 bg-transparent py-3 pr-[90px] pl-4 text-sm text-gray-800 placeholder:text-gray-400 focus:ring-3 focus:outline-hidden dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:placeholder:text-white/30 font-mono"
                            readOnly
                            type={apiKeyVisible ? 'text' : 'password'}
                            value={apiKeyVisible ? apiKey : maskApiKey(apiKey)}
                          />
                          <button
                            onClick={handleCopyApiKey}
                            className="absolute top-1/2 right-0 inline-flex h-11 -translate-y-1/2 cursor-pointer items-center gap-1 rounded-r-lg border border-gray-300 py-3 pr-3 pl-3.5 text-sm font-medium text-gray-700 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700"
                          >
                            <CopyIcon className="w-4 h-4 fill-current" />
                            <span>Copy</span>
                          </button>
                        </div>
                        <div className="group relative inline-block">
                          <button
                            onClick={handleRegenerateApiKey}
                            disabled={generatingKey}
                            className="inline-flex h-11 w-11 items-center justify-center rounded-lg border border-gray-300 text-gray-700 dark:border-gray-700 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50"
                            title="Regenerate"
                          >
                            <RefreshCw className={`w-5 h-5 ${generatingKey ? 'animate-spin' : ''}`} />
                          </button>
                          <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-[#1E2634] 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-[#1E2634]"></div>
                            </div>
                          </div>
                        </div>
                        <button
                          onClick={() => setApiKeyVisible(!apiKeyVisible)}
                          className="inline-flex h-11 w-11 items-center justify-center rounded-lg border border-gray-300 text-gray-700 dark:border-gray-700 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700"
                        >
                          {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>
                          )}
                        </button>
                      </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-green-50 text-green-600 dark:bg-green-500/15 dark:text-green-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">
                      <button
                        onClick={handleRegenerateApiKey}
                        disabled={generatingKey}
                        className="text-gray-500 hover:text-brand-500 dark:text-gray-400 dark:hover:text-brand-400 disabled:opacity-50 transition-colors"
                        title="Regenerate API key"
                      >
                        <RefreshCw className={`w-5 h-5 ${generatingKey ? 'animate-spin' : ''}`} />
                      </button>
                      <button
                        onClick={handleRevokeApiKey}
                        disabled={generatingKey}
                        className="text-gray-500 hover:text-error-500 dark:text-gray-400 dark:hover:text-error-400 disabled:opacity-50 transition-colors"
                        title="Revoke API key"
                      >
                        <TrashBinIcon className="w-5 h-5" />
                      </button>
                    </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="flex items-center justify-between">
            <div>
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                <DownloadIcon className="w-5 h-5 text-indigo-600 dark:text-indigo-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"
            >
              <DownloadIcon className="w-4 h-4 mr-2" />
              Download Plugin
            </Button>
          </div>
        </Card>
      )}
    </div>
  );
}
