/* global sprintf, wp */
/**
 * Site Audit Settings Component
 *
 * Provides advanced controls for audit configuration
 */

import {  useState, useEffect  } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';

// Custom Premium Components
import ProrankButton from '../../../components/ProrankButton';
import ProrankToggleSlider from '../../../components/ProrankToggleSlider';
import { ProrankCard, ProrankCardBody, ProrankCardHeader } from '../../../components/ProrankCard';
import { ProrankInput } from '../../../components/ProrankInput';
import { ProrankTextarea } from '../../../components/ProrankTextarea';
import { ProrankSelect } from '../../../components/ProrankSelect';
import { ProrankNotice } from '../../../components/ProrankNotice';
import { ProrankRangeControl } from '../../../components/ProrankRangeControl';
import { ProrankNumberControl } from '../../../components/ProrankNumberControl';
import ProrankNumberInput from '../../../components/ProrankNumberInput';
import { Flex, FlexBlock, FlexItem } from '../../../components/design-system/Flex';

const AuditSettings = ({
  settings,
  onSave,
  onClose,
  onSettingsChange,
  showSaveButton = true
}) => {
  const [localSettings, setLocalSettings] = useState({
    // Speed settings
    crawl_speed: 30, // URLs per minute
    concurrent_requests: 5,
    request_timeout: 5,

    // Check settings
    execute_javascript: false,
    check_images: true,
    check_css: true,
    check_javascript: true,
    follow_non_canonical: false,
    follow_nofollow: false,
    check_external_links: false,
    remove_url_parameters: true,

    // Limits
    max_pages: 100,
    max_duration: 30, // minutes
    max_depth: 5,
    max_folder_depth: 10,
    max_url_length: 2048,
    max_query_params: 5,

    // Robots
    ignore_robots_txt: false,

    // URL patterns
    include_patterns: '',
    exclude_patterns: '',

    ...settings,
  });

  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState('');

  useEffect(() => {
    if (!settings || typeof settings !== 'object') {
      return;
    }
    setLocalSettings((prev) => ({
      ...prev,
      ...settings,
    }));
  }, [settings]);

  const handleSave = async () => {
    setSaving(true);
    setMessage('');

    try {
      // Save to both database and localStorage for redundancy
      const savePromises = [
        // Save to database via API
        onSave(localSettings),
        // Save to localStorage as backup
        new Promise<void>((resolve) => {
          localStorage.setItem('prorank_audit_settings_advanced', JSON.stringify(localSettings));
          resolve();
        })
      ];

      await Promise.all(savePromises);
      
      // Verify settings were saved to database
      const verifyResponse = await fetch('/wp-json/prorank-seo/v1/audit-settings', {
        method: 'GET',
        headers: {
          'X-WP-Nonce': (window as any).prorankSeo?.nonce || '',
        },
      });
      
      if (verifyResponse.ok) {
        const savedSettings = await verifyResponse.json();
        if (savedSettings.success) {
          setMessage(__('Settings saved successfully to database!', 'prorank-seo'));
        } else {
          setMessage(__('Settings saved locally. Database sync pending.', 'prorank-seo'));
        }
      }
    } catch (error) {
      console.error('Settings save error:', error);
      // Still save to localStorage even if database save fails
      localStorage.setItem('prorank_audit_settings_advanced', JSON.stringify(localSettings));
      setMessage(__('Settings saved locally. Database save failed.', 'prorank-seo'));
    } finally {
      setSaving(false);
    }
  };

  const updateSetting = (key, value) => {
    setLocalSettings((prev) => {
      const next = {
        ...prev,
        [key]: value,
      };
      if (typeof onSettingsChange === 'function') {
        onSettingsChange(next);
      }
      return next;
    });
  };

  return (
    <div className="prorank-audit-settings">
      {message && (
        <ProrankNotice
          status={message.includes('success') ? 'success' : 'error'}
          isDismissible
          onDismiss={() => setMessage('')}
        >
          <p>{message}</p>
        </ProrankNotice>
      )}

      {/* Speed Settings */}
      <ProrankCard className="audit-settings-card">
        <ProrankCardHeader>
          <h3>{__('Crawl Speed', 'prorank-seo')}</h3>
        </ProrankCardHeader>
        <ProrankCardBody>
          <p style={{ color: '#757575', marginBottom: '20px' }}>
            {__(
              'Higher crawl speeds may impact server performance. Start with lower speeds and increase gradually.',
              'prorank-seo'
            )}
          </p>

          <ProrankRangeControl
            label={__('Crawl Speed (URLs per minute)', 'prorank-seo')}
            value={localSettings.crawl_speed}
            onChange={(value) => updateSetting('crawl_speed', value)}
            min={1}
            max={60}
            marks={[
              { value: 1, label: '1' },
              { value: 10, label: '10' },
              { value: 30, label: '30' },
              { value: 60, label: '60' },
            ]}
            /* translators: %s: placeholder description */

            help={sprintf(
              __('Process up to %d URLs per minute', 'prorank-seo'),
              localSettings.crawl_speed
            )}
          />

          <ProrankRangeControl
            label={__('Concurrent Requests', 'prorank-seo')}
            value={localSettings.concurrent_requests}
            onChange={(value) => updateSetting('concurrent_requests', value)}
            min={1}
            max={5}
            help={__('Number of simultaneous URL checks', 'prorank-seo')}
          />

          <ProrankRangeControl
            label={__('Request Timeout (seconds)', 'prorank-seo')}
            value={localSettings.request_timeout}
            onChange={(value) => updateSetting('request_timeout', value)}
            min={1}
            max={30}
            help={__('Maximum time to wait for a page response', 'prorank-seo')}
          />
        </ProrankCardBody>
      </ProrankCard>

      {/* Check Settings */}
      <ProrankCard className="audit-settings-card">
        <ProrankCardHeader>
          <h3>{__('Check Settings', 'prorank-seo')}</h3>
        </ProrankCardHeader>
        <ProrankCardBody>
          <div className="prorank-settings-list">
            <div className="prorank-setting-row">
              <div className="prorank-setting-info">
                <div className="prorank-setting-label">{__('Execute JavaScript', 'prorank-seo')}</div>
                <div className="prorank-setting-desc">{__('Enable to check JavaScript-rendered content (slower)', 'prorank-seo')}</div>
              </div>
              <ProrankToggleSlider
                checked={localSettings.execute_javascript}
                onChange={(value) => updateSetting('execute_javascript', value)}
              />
            </div>

            <div className="prorank-setting-row">
              <div className="prorank-setting-info">
                <div className="prorank-setting-label">{__('Check Images', 'prorank-seo')}</div>
                <div className="prorank-setting-desc">{__('Verify all images load correctly', 'prorank-seo')}</div>
              </div>
              <ProrankToggleSlider
                checked={localSettings.check_images}
                onChange={(value) => updateSetting('check_images', value)}
              />
            </div>

            <div className="prorank-setting-row">
              <div className="prorank-setting-info">
                <div className="prorank-setting-label">{__('Check CSS Files', 'prorank-seo')}</div>
                <div className="prorank-setting-desc">{__('Verify CSS stylesheets load correctly', 'prorank-seo')}</div>
              </div>
              <ProrankToggleSlider
                checked={localSettings.check_css}
                onChange={(value) => updateSetting('check_css', value)}
              />
            </div>

            <div className="prorank-setting-row">
              <div className="prorank-setting-info">
                <div className="prorank-setting-label">{__('Check JavaScript Files', 'prorank-seo')}</div>
                <div className="prorank-setting-desc">{__('Verify JavaScript files load correctly', 'prorank-seo')}</div>
              </div>
              <ProrankToggleSlider
                checked={localSettings.check_javascript}
                onChange={(value) => updateSetting('check_javascript', value)}
              />
            </div>

            <div className="prorank-setting-row">
              <div className="prorank-setting-info">
                <div className="prorank-setting-label">{__('Follow Non-Canonical Pages', 'prorank-seo')}</div>
                <div className="prorank-setting-desc">{__('Follow links on pages with canonical pointing elsewhere', 'prorank-seo')}</div>
              </div>
              <ProrankToggleSlider
                checked={localSettings.follow_non_canonical}
                onChange={(value) => updateSetting('follow_non_canonical', value)}
              />
            </div>

            <div className="prorank-setting-row">
              <div className="prorank-setting-info">
                <div className="prorank-setting-label">{__('Follow Nofollow Links', 'prorank-seo')}</div>
                <div className="prorank-setting-desc">{__('Crawl pages linked with rel="nofollow"', 'prorank-seo')}</div>
              </div>
              <ProrankToggleSlider
                checked={localSettings.follow_nofollow}
                onChange={(value) => updateSetting('follow_nofollow', value)}
              />
            </div>

            <div className="prorank-setting-row">
              <div className="prorank-setting-info">
                <div className="prorank-setting-label">{__('Check External Links', 'prorank-seo')}</div>
                <div className="prorank-setting-desc">{__('Verify HTTP status of external links (increases audit time)', 'prorank-seo')}</div>
              </div>
              <ProrankToggleSlider
                checked={localSettings.check_external_links}
                onChange={(value) => updateSetting('check_external_links', value)}
              />
            </div>

            <div className="prorank-setting-row">
              <div className="prorank-setting-info">
                <div className="prorank-setting-label">{__('Remove URL Parameters', 'prorank-seo')}</div>
                <div className="prorank-setting-desc">{__('Strip query parameters from URLs', 'prorank-seo')}</div>
              </div>
              <ProrankToggleSlider
                checked={localSettings.remove_url_parameters}
                onChange={(value) => updateSetting('remove_url_parameters', value)}
              />
            </div>
          </div>
        </ProrankCardBody>
      </ProrankCard>

      {/* Limits */}
      <ProrankCard className="audit-settings-card">
        <ProrankCardHeader>
          <h3>{__('Crawl Limits', 'prorank-seo')}</h3>
        </ProrankCardHeader>
        <ProrankCardBody>
          <ProrankNumberControl
            label={__('Maximum Crawl Duration (minutes)', 'prorank-seo')}
            value={localSettings.max_duration}
            onChange={(value) => updateSetting('max_duration', parseInt(value) || 30)}
            min={5}
            max={180}
            step={5}
            help={__('Stop audit after this duration', 'prorank-seo')}
          />

          <ProrankNumberControl
            label={__('Maximum Folder Depth', 'prorank-seo')}
            value={localSettings.max_folder_depth}
            onChange={(value) => updateSetting('max_folder_depth', parseInt(value) || 10)}
            min={1}
            max={50}
            help={__('Maximum folder levels in URL path', 'prorank-seo')}
          />

          <ProrankNumberControl
            label={__('Maximum URL Length (characters)', 'prorank-seo')}
            value={localSettings.max_url_length}
            onChange={(value) => updateSetting('max_url_length', parseInt(value) || 2048)}
            min={100}
            max={4096}
            step={100}
          />

          <ProrankNumberControl
            label={__('Maximum Query Parameters', 'prorank-seo')}
            value={localSettings.max_query_params}
            onChange={(value) => updateSetting('max_query_params', parseInt(value) || 5)}
            min={0}
            max={20}
          />
        </ProrankCardBody>
      </ProrankCard>

      {/* Robots Settings */}
      <ProrankCard className="audit-settings-card">
        <ProrankCardHeader>
          <h3>{__('Robots Instructions', 'prorank-seo')}</h3>
        </ProrankCardHeader>
        <ProrankCardBody>
          <div className="prorank-settings-list">
            <div className="prorank-setting-row">
              <div className="prorank-setting-info">
                <div className="prorank-setting-label">{__('Ignore robots.txt', 'prorank-seo')}</div>
                <div className="prorank-setting-desc">{__('Crawl pages even if disallowed by robots.txt', 'prorank-seo')}</div>
              </div>
              <ProrankToggleSlider
                checked={localSettings.ignore_robots_txt}
                onChange={(value) => updateSetting('ignore_robots_txt', value)}
              />
            </div>
          </div>
        </ProrankCardBody>
      </ProrankCard>

      {/* URL Patterns */}
      <ProrankCard className="audit-settings-card">
        <ProrankCardHeader>
          <h3>{__('Include and Exclude URLs', 'prorank-seo')}</h3>
        </ProrankCardHeader>
        <ProrankCardBody>
          <ProrankTextarea
            label={__('Only crawl URLs matching these patterns', 'prorank-seo')}
            value={localSettings.include_patterns}
            onChange={(value) => updateSetting('include_patterns', value)}
            placeholder="/blog/*&#10;/products/*&#10;*.html"
            rows={4}
            help={__(
              'One pattern per line. Use * for wildcards, or regex patterns.',
              'prorank-seo'
            )}
          />

          <ProrankTextarea
            label={__("Don't crawl URLs matching these patterns", 'prorank-seo')}
            value={localSettings.exclude_patterns}
            onChange={(value) => updateSetting('exclude_patterns', value)}
            placeholder="/admin/*&#10;/wp-admin/*&#10;*.pdf&#10;/tag/*"
            rows={4}
            help={__(
              'One pattern per line. Common exclusions: admin areas, PDFs, tag pages.',
              'prorank-seo'
            )}
          />
        </ProrankCardBody>
      </ProrankCard>

      {/* Actions */}
      {showSaveButton || onClose ? (
        <Flex justify="flex-end" gap={3} style={{ marginTop: '20px' }}>
          {onClose ? (
            <ProrankButton variant="tertiary" onClick={onClose}>
              {__('Cancel', 'prorank-seo')}
            </ProrankButton>
          ) : null}
          {showSaveButton ? (
            <ProrankButton variant="primary" onClick={handleSave} isBusy={saving}>
              {__('Save Settings', 'prorank-seo')}
            </ProrankButton>
          ) : null}
        </Flex>
      ) : null}
    </div>
  );
};

export default AuditSettings;
