/**
 * Advanced Settings Tab Component
 *
 * Modern React 19 component with React Query and Zod validation
 *
 * @module Support/AdvancedSettingsTab
 * @since 1.0.0
 */

import React, { useState, useCallback, useRef } from 'react';
import { Card, Button, Input, Select, Toggle, Alert } from '../../../components/ui';
import { __ } from '@wordpress/i18n';
import SettingsSnapshotUI from '../../../components/SettingsSnapshot';
import { useNotification } from '../../../contexts/NotificationContext';
import {
  useAdvancedSettings,
  useSaveAdvancedSettings,
  useClearCache,
  useExportSettings,
  useImportSettings,
  useImportFromCompetitor,
} from '../../../hooks/useAdvancedSettings';
import type {
  AdvancedSettings,
  TabComponentProps,
  CompetitorSource
} from '../../../types/advanced-settings';
import {
  advancedSettingsDefaults,
  logLevelOptions,
  competitorOptions
} from '../../../types/advanced-settings';

declare global {
  interface Window {
    prorankSeoAdmin?: {
      version?: string;
      buildFingerprint?: string;
      buildTimestamp?: number;
      buildCommit?: string;
    };
  }
}

const AdvancedSettingsTab: React.FC<TabComponentProps> = ({ addNotice = () => {} }) => {
  const { showNotification } = useNotification();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [localSettings, setLocalSettings] = useState<AdvancedSettings | null>(null);
  const [selectedCompetitor, setSelectedCompetitor] = useState<CompetitorSource>('yoast');

  // Use context notification as primary, fall back to prop if context is unavailable
  const notify = useCallback((type: 'success' | 'error' | 'warning' | 'info', message: string) => {
    showNotification(message, type);
    addNotice(type, message);
  }, [showNotification, addNotice]);

  // React Query hooks
  const { data: settings, isLoading, error } = useAdvancedSettings();
  const saveMutation = useSaveAdvancedSettings();
  const clearCacheMutation = useClearCache();
  const exportMutation = useExportSettings();
  const importMutation = useImportSettings();
  const competitorMutation = useImportFromCompetitor();

  // Use local state if modified, otherwise use fetched data
  const currentSettings = localSettings ?? settings ?? advancedSettingsDefaults;
  const buildTimestamp = Number(window.prorankSeoAdmin?.buildTimestamp ?? 0);
  const thirdPartyGovernance =
    currentSettings.third_party_governance ?? advancedSettingsDefaults.third_party_governance;

  const handleSettingChange = useCallback(<K extends keyof AdvancedSettings>(
    key: K,
    value: AdvancedSettings[K]
  ) => {
    setLocalSettings(prev => ({
      ...(prev ?? settings ?? advancedSettingsDefaults),
      [key]: value,
    }));
  }, [settings]);

  const handleSave = useCallback(async () => {
    try {
      await saveMutation.mutateAsync(currentSettings);
      setLocalSettings(null);
      notify('success', __('Advanced settings saved successfully!', 'prorank-seo'));
    } catch (err) {
      notify('error', (err as Error).message || __('Failed to save settings', 'prorank-seo'));
    }
  }, [currentSettings, saveMutation, notify]);

  const handleClearCache = useCallback(async () => {
    if (!confirm(__('Are you sure you want to clear all caches?', 'prorank-seo'))) {
      return;
    }

    try {
      await clearCacheMutation.mutateAsync();
      notify('success', __('All caches cleared successfully!', 'prorank-seo'));
    } catch (err) {
      notify('error', (err as Error).message || __('Failed to clear cache', 'prorank-seo'));
    }
  }, [clearCacheMutation, notify]);

  const handleExport = useCallback(async () => {
    try {
      await exportMutation.mutateAsync();
      notify('success', __('Settings exported successfully!', 'prorank-seo'));
    } catch (err) {
      notify('error', (err as Error).message || __('Failed to export settings', 'prorank-seo'));
    }
  }, [exportMutation, notify]);

  const handleImport = useCallback(async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    try {
      const text = await file.text();
      const importedData = JSON.parse(text);

      await importMutation.mutateAsync(importedData);
      notify('success', __('Settings imported successfully! Page will reload...', 'prorank-seo'));
      setTimeout(() => window.location.reload(), 2000);
    } catch (err) {
      notify('error', (err as Error).message || __('Failed to import settings', 'prorank-seo'));
    } finally {
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  }, [importMutation, notify]);

  const handleCompetitorImport = useCallback(async () => {
    if (!confirm(
      __(`Are you sure you want to import data from ${selectedCompetitor}? This will overwrite existing settings.`, 'prorank-seo')
    )) {
      return;
    }

    try {
      const result = await competitorMutation.mutateAsync({
        source: selectedCompetitor,
        types: ['meta', 'settings', 'redirects', 'schema', 'locations'],
      });

      if (result.success) {
        const stats = result.stats;
        const message = __('Import complete! ', 'prorank-seo') +
          (stats ? `Posts: ${stats.posts || 0}, Locations: ${stats.locations || 0}, Settings: ${stats.settings || 0}` : '');
        notify('success', message);
      } else {
        notify('error', result.message || __('Import failed', 'prorank-seo'));
      }
    } catch (err) {
      notify('error', (err as Error).message || __('Failed to import from competitor', 'prorank-seo'));
    }
  }, [selectedCompetitor, competitorMutation, notify]);

  if (isLoading) {
    return (
      <div className="prorank-advanced-settings-tab prorank-loading">
        <p>{__('Loading settings...', 'prorank-seo')}</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="prorank-advanced-settings-tab">
        <Alert variant="error">
          {__('Failed to load settings. Please refresh the page.', 'prorank-seo')}
        </Alert>
      </div>
    );
  }

  return (
    <div className="prorank-advanced-settings-tab">
      <div className="prorank-section-header">
        <h2 className="prorank-section-title">{__('Advanced Settings', 'prorank-seo')}</h2>
        <p className="prorank-section-description">
          {__('Fine-tune ProRank SEO with advanced configuration options for power users', 'prorank-seo')}
        </p>
      </div>

      <Alert variant="warning" className="advanced-warning">
        {__("Warning: These settings can affect your site's functionality. Only modify if you know what you're doing.", 'prorank-seo')}
      </Alert>

      <div className="prorank-support-grid">
        {/* Debug & Development */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('Debug & Development', 'prorank-seo')}</h3>
          </div>
          <div className="prorank-card-body">
            <Toggle
              label={__('Debug Mode', 'prorank-seo')}
              help={__('Enable detailed error logging and debug information', 'prorank-seo')}
              checked={currentSettings.debug_mode}
              onChange={(value) => handleSettingChange('debug_mode', value)}
            />

            <Select
              label={__('Log Level', 'prorank-seo')}
              value={currentSettings.log_level}
              options={logLevelOptions.map(opt => ({
                label: __(opt.label, 'prorank-seo'),
                value: opt.value
              }))}
              onChange={(value) => handleSettingChange('log_level', value as AdvancedSettings['log_level'])}
            />
          </div>
        </Card>

        {/* Performance */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('Performance', 'prorank-seo')}</h3>
          </div>
          <div className="prorank-card-body">
            <Input
              label={__('API Timeout (seconds)', 'prorank-seo')}
              type="number"
              value={String(currentSettings.api_timeout)}
              onChange={(value) => handleSettingChange('api_timeout', parseInt(value, 10) || 30)}
              help={__('Maximum time to wait for API responses (5-120)', 'prorank-seo')}
            />

            <Input
              label={__('Cache Duration (seconds)', 'prorank-seo')}
              type="number"
              value={String(currentSettings.cache_duration)}
              onChange={(value) => handleSettingChange('cache_duration', parseInt(value, 10) || 3600)}
              help={__('How long to cache API responses (60-86400)', 'prorank-seo')}
            />

            <Button
              variant="secondary"
              onClick={handleClearCache}
              disabled={clearCacheMutation.isPending}
            >
              {clearCacheMutation.isPending
                ? __('Clearing...', 'prorank-seo')
                : __('Clear All Caches', 'prorank-seo')}
            </Button>
          </div>
        </Card>

        {/* Security */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('Security', 'prorank-seo')}</h3>
          </div>
          <div className="prorank-card-body">
            <Toggle
              label={__('Disable XML-RPC', 'prorank-seo')}
              help={__('Disable XML-RPC to prevent brute force attacks', 'prorank-seo')}
              checked={currentSettings.disable_xmlrpc}
              onChange={(value) => handleSettingChange('disable_xmlrpc', value)}
            />

            <Toggle
              label={__('Disable REST API for non-authenticated users', 'prorank-seo')}
              help={__('Restrict REST API access to logged-in users only', 'prorank-seo')}
              checked={currentSettings.disable_rest_api_public}
              onChange={(value) => handleSettingChange('disable_rest_api_public', value)}
            />

            <Toggle
              label={__('Remove WordPress version strings', 'prorank-seo')}
              help={__('Hide WordPress version from HTML, RSS feeds, etc.', 'prorank-seo')}
              checked={currentSettings.remove_version_strings}
              onChange={(value) => handleSettingChange('remove_version_strings', value)}
            />

            <Toggle
              label={__('Disable file editing', 'prorank-seo')}
              help={__('Disable the theme and plugin file editor in admin', 'prorank-seo')}
              checked={currentSettings.disable_file_editing}
              onChange={(value) => handleSettingChange('disable_file_editing', value)}
            />
          </div>
        </Card>

        {/* WordPress Features */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('WordPress Features', 'prorank-seo')}</h3>
          </div>
          <div className="prorank-card-body">
            <Toggle
              label={__('Disable Emojis', 'prorank-seo')}
              help={__('Remove WordPress emoji scripts and styles', 'prorank-seo')}
              checked={currentSettings.disable_emojis}
              onChange={(value) => handleSettingChange('disable_emojis', value)}
            />

            <Toggle
              label={__('Disable Gutenberg Block Editor', 'prorank-seo')}
              help={__('Use the classic editor instead of Gutenberg', 'prorank-seo')}
              checked={currentSettings.disable_gutenberg}
              onChange={(value) => handleSettingChange('disable_gutenberg', value)}
            />
          </div>
        </Card>

        {/* Third-Party Governance */}
        <Card className="prorank-card--modern">
          <div className="prorank-card-header">
            <h3 className="prorank-card-title">{__('Third-Party Governance', 'prorank-seo')}</h3>
          </div>
          <div className="prorank-card-body">
            <Toggle
              label={__('Delay Google Services', 'prorank-seo')}
              help={__('Delay GTM, gtag, Analytics, Ads, and related Google measurement scripts until interaction.', 'prorank-seo')}
              checked={thirdPartyGovernance.delay_google_services}
              onChange={(value) => handleSettingChange('third_party_governance', {
                ...thirdPartyGovernance,
                delay_google_services: value,
              })}
            />

            <Toggle
              label={__('Delay Review Widgets', 'prorank-seo')}
              help={__('Delay review widget loaders like Trustindex until interaction.', 'prorank-seo')}
              checked={thirdPartyGovernance.delay_review_widgets}
              onChange={(value) => handleSettingChange('third_party_governance', {
                ...thirdPartyGovernance,
                delay_review_widgets: value,
              })}
            />

            <Toggle
              label={__('Keep Consent Scripts Non-Blocking', 'prorank-seo')}
              help={__('Apply ProRank non-blocking handling to consent managers like CookieYes and Cookiebot.', 'prorank-seo')}
              checked={thirdPartyGovernance.defer_consent_scripts}
              onChange={(value) => handleSettingChange('third_party_governance', {
                ...thirdPartyGovernance,
                defer_consent_scripts: value,
              })}
            />

            <Toggle
              label={__('Delay Identity Widgets', 'prorank-seo')}
              help={__('Delay sign-in clients like Google Sign-In until interaction.', 'prorank-seo')}
              checked={thirdPartyGovernance.delay_identity_widgets}
              onChange={(value) => handleSettingChange('third_party_governance', {
                ...thirdPartyGovernance,
                delay_identity_widgets: value,
              })}
            />
          </div>
        </Card>
      </div>

      {/* Debug Information */}
      <Card className="prorank-card--modern prorank-card--full-width">
        <div className="prorank-card-header">
          <h3 className="prorank-card-title">{__('Debug Information', 'prorank-seo')}</h3>
        </div>
        <div className="prorank-card-body">
          <div className="prorank-debug-info">
            <p>
              <strong>{__('Plugin Version:', 'prorank-seo')}</strong>{' '}
              {window.prorankSeoAdmin?.version || 'Unknown'}
            </p>
            <p>
              <strong>{__('Build Fingerprint:', 'prorank-seo')}</strong>{' '}
              {window.prorankSeoAdmin?.buildFingerprint || 'Not available'}
            </p>
            <p>
              <strong>{__('Build Timestamp:', 'prorank-seo')}</strong>{' '}
              {Number.isFinite(buildTimestamp) && buildTimestamp > 0
                ? new Date(buildTimestamp * 1000).toLocaleString()
                : 'Not available'}
            </p>
            <p>
              <strong>{__('Build Commit:', 'prorank-seo')}</strong>{' '}
              {window.prorankSeoAdmin?.buildCommit || 'Not available'}
            </p>
          </div>
        </div>
      </Card>

      {/* Import/Export */}
      <Card className="prorank-card--modern prorank-card--full-width">
        <div className="prorank-card-header">
          <h3 className="prorank-card-title">{__('Import/Export', 'prorank-seo')}</h3>
        </div>
        <div className="prorank-card-body">
          <p>{__('Backup your ProRank settings or transfer them to another site.', 'prorank-seo')}</p>

          <div className="import-export-buttons">
            <Button
              variant="secondary"
              onClick={handleExport}
              disabled={exportMutation.isPending}
            >
              {exportMutation.isPending
                ? __('Exporting...', 'prorank-seo')
                : __('Export Settings', 'prorank-seo')}
            </Button>

            <label className="import-button-wrapper">
              <Button
                variant="secondary"
                disabled={importMutation.isPending}
                as="span"
              >
                {importMutation.isPending
                  ? __('Importing...', 'prorank-seo')
                  : __('Import Settings', 'prorank-seo')}
              </Button>
              <input
                ref={fileInputRef}
                type="file"
                accept=".json"
                onChange={handleImport}
                style={{ display: 'none' }}
                disabled={importMutation.isPending}
              />
            </label>
          </div>
        </div>
      </Card>

      {/* Settings History */}
      <Card className="prorank-card--modern prorank-card--full-width">
        <div className="prorank-card-header">
          <h3 className="prorank-card-title">{__('Settings History', 'prorank-seo')}</h3>
        </div>
        <div className="prorank-card-body">
          <SettingsSnapshotUI embedded />
        </div>
      </Card>

      {/* Import from Competitors */}
      <Card className="prorank-card--modern prorank-card--full-width">
        <div className="prorank-card-header">
          <h3 className="prorank-card-title">{__('Import from Other SEO Plugins', 'prorank-seo')}</h3>
        </div>
        <div className="prorank-card-body">
          <p>{__('Import your SEO data from other popular SEO plugins.', 'prorank-seo')}</p>

          <div className="competitor-import-section">
            <Select
              label={__('Select SEO Plugin', 'prorank-seo')}
              value={selectedCompetitor}
              options={competitorOptions.map(opt => ({
                label: opt.label,
                value: opt.value
              }))}
              onChange={(value) => setSelectedCompetitor(value as CompetitorSource)}
            />

            <Button
              variant="secondary"
              onClick={handleCompetitorImport}
              disabled={competitorMutation.isPending}
              className="competitor-import-button"
            >
              {competitorMutation.isPending
                ? __('Importing...', 'prorank-seo')
                : __('Import Data', 'prorank-seo')}
            </Button>
          </div>

          <p className="import-note">
            {__('This will import meta titles, descriptions, focus keywords, redirects, and settings.', 'prorank-seo')}
          </p>
        </div>
      </Card>

      {/* Save Button */}
      <div className="prorank-settings-actions">
        <Button
          variant="primary"
          onClick={handleSave}
          disabled={saveMutation.isPending || !localSettings}
        >
          {saveMutation.isPending
            ? __('Saving...', 'prorank-seo')
            : __('Save Advanced Settings', 'prorank-seo')}
        </Button>

        {localSettings && (
          <Button
            variant="tertiary"
            onClick={() => setLocalSettings(null)}
          >
            {__('Discard Changes', 'prorank-seo')}
          </Button>
        )}
      </div>
    </div>
  );
};

export default AdvancedSettingsTab;
