/**
 * Site Audit Settings Component
 *
 * Provides advanced controls for audit configuration
 */

import React, { useState, useEffect } from 'react';
import { __, sprintf } from '@wordpress/i18n';
import { Card, Button, Alert, Toggle, Select, Input, Textarea } from '../../components/ui';

const AuditSettings = ({ settings, onSave, onClose }) => {
  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('');

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

    try {
      await onSave(localSettings);
      setMessage(__('Settings saved successfully!', 'prorank-seo'));
    } catch (error) {
      setMessage(__('Failed to save settings.', 'prorank-seo'));
    } finally {
      setSaving(false);
    }
  };

  const updateSetting = (key, value) => {
    setLocalSettings((prev) => ({
      ...prev,
      [key]: value,
    }));
  };

  return (
    <div className="prorank-audit-settings pr:space-y-6">
      {message && (
        <Alert
          variant={message.includes('success') ? 'success' : 'error'}
          onDismiss={() => setMessage('')}
        >
          {message}
        </Alert>
      )}

      {/* Speed Settings */}
      <Card>
        <div className="pr:p-6">
          <h3 className="pr:text-lg pr:font-semibold pr:mb-4">{__('Crawl Speed', 'prorank-seo')}</h3>
          <p className="pr:text-gray-600 pr:mb-6">
            {__(
              'Higher crawl speeds may impact server performance. Start with lower speeds and increase gradually.',
              'prorank-seo'
            )}
          </p>

          <div className="pr:space-y-6">
            <div>
              <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700 pr:mb-2">
                {__('Crawl Speed (URLs per minute)', 'prorank-seo')}
              </label>
              <input
                type="range"
                min="1"
                max="60"
                value={localSettings.crawl_speed}
                onChange={(e) => updateSetting('crawl_speed', parseInt(e.target.value))}
                className="pr:w-full"
              />
              <p className="pr:text-sm pr:text-gray-500 pr:mt-1">
                {sprintf(__('Process up to %d URLs per minute', 'prorank-seo'), localSettings.crawl_speed)}
              </p>
            </div>

            <div>
              <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700 pr:mb-2">
                {__('Concurrent Requests', 'prorank-seo')}
              </label>
              <input
                type="range"
                min="1"
                max="5"
                value={localSettings.concurrent_requests}
                onChange={(e) => updateSetting('concurrent_requests', parseInt(e.target.value))}
                className="pr:w-full"
              />
              <p className="pr:text-sm pr:text-gray-500 pr:mt-1">
                {__('Number of simultaneous URL checks', 'prorank-seo')}: {localSettings.concurrent_requests}
              </p>
            </div>

            <div>
              <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700 pr:mb-2">
                {__('Request Timeout (seconds)', 'prorank-seo')}
              </label>
              <input
                type="range"
                min="1"
                max="30"
                value={localSettings.request_timeout}
                onChange={(e) => updateSetting('request_timeout', parseInt(e.target.value))}
                className="pr:w-full"
              />
              <p className="pr:text-sm pr:text-gray-500 pr:mt-1">
                {__('Maximum time to wait for a page response', 'prorank-seo')}: {localSettings.request_timeout}s
              </p>
            </div>
          </div>
        </div>
      </Card>

      {/* Check Settings */}
      <Card>
        <div className="pr:p-6">
          <h3 className="pr:text-lg pr:font-semibold pr:mb-4">{__('Check Settings', 'prorank-seo')}</h3>
          <div className="pr:space-y-4">
            <div>
              <Toggle
                label={__('Execute JavaScript', 'prorank-seo')}
                checked={localSettings.execute_javascript}
                onChange={(value) => updateSetting('execute_javascript', value)}
              />
              <p className="pr:text-sm pr:text-gray-500 pr:mt-1 pr:ml-12">
                {__('Enable to check JavaScript-rendered content (slower)', 'prorank-seo')}
              </p>
            </div>

            <Toggle
              label={__('Check Images', 'prorank-seo')}
              checked={localSettings.check_images}
              onChange={(value) => updateSetting('check_images', value)}
            />

            <Toggle
              label={__('Check CSS Files', 'prorank-seo')}
              checked={localSettings.check_css}
              onChange={(value) => updateSetting('check_css', value)}
            />

            <Toggle
              label={__('Check JavaScript Files', 'prorank-seo')}
              checked={localSettings.check_javascript}
              onChange={(value) => updateSetting('check_javascript', value)}
            />

            <Toggle
              label={__('Follow Links on Non-Canonical Pages', 'prorank-seo')}
              checked={localSettings.follow_non_canonical}
              onChange={(value) => updateSetting('follow_non_canonical', value)}
            />

            <Toggle
              label={__('Follow Nofollow Links', 'prorank-seo')}
              checked={localSettings.follow_nofollow}
              onChange={(value) => updateSetting('follow_nofollow', value)}
            />

            <div>
              <Toggle
                label={__('Check HTTP Status of External Links', 'prorank-seo')}
                checked={localSettings.check_external_links}
                onChange={(value) => updateSetting('check_external_links', value)}
              />
              <p className="pr:text-sm pr:text-gray-500 pr:mt-1 pr:ml-12">
                {__('This may significantly increase audit time', 'prorank-seo')}
              </p>
            </div>

            <div>
              <Toggle
                label={__('Remove URL Parameters', 'prorank-seo')}
                checked={localSettings.remove_url_parameters}
                onChange={(value) => updateSetting('remove_url_parameters', value)}
              />
              <p className="pr:text-sm pr:text-gray-500 pr:mt-1 pr:ml-12">
                {__('Strip query parameters from URLs', 'prorank-seo')}
              </p>
            </div>
          </div>
        </div>
      </Card>

      {/* Limits */}
      <Card>
        <div className="pr:p-6">
          <h3 className="pr:text-lg pr:font-semibold pr:mb-4">{__('Crawl Limits', 'prorank-seo')}</h3>
          <div className="pr:space-y-4">
            <div>
              <Input
                type="number"
                label={__('Maximum Pages to Crawl', 'prorank-seo')}
                value={localSettings.max_pages}
                onChange={(e) => updateSetting('max_pages', parseInt(e.target.value) || 100)}
                min="10"
                max="10000"
                step="10"
              />
              <p className="pr:text-sm pr:text-gray-500 pr:mt-1">
                {__('Limit the total number of pages to audit', 'prorank-seo')}
              </p>
            </div>

            <div>
              <Input
                type="number"
                label={__('Maximum Crawl Duration (minutes)', 'prorank-seo')}
                value={localSettings.max_duration}
                onChange={(e) => updateSetting('max_duration', parseInt(e.target.value) || 30)}
                min="5"
                max="180"
                step="5"
              />
              <p className="pr:text-sm pr:text-gray-500 pr:mt-1">
                {__('Stop audit after this duration', 'prorank-seo')}
              </p>
            </div>

            <div>
              <Input
                type="number"
                label={__('Maximum Depth Level', 'prorank-seo')}
                value={localSettings.max_depth}
                onChange={(e) => updateSetting('max_depth', parseInt(e.target.value) || 5)}
                min="1"
                max="20"
              />
              <p className="pr:text-sm pr:text-gray-500 pr:mt-1">
                {__('Maximum clicks from homepage', 'prorank-seo')}
              </p>
            </div>

            <div>
              <Input
                type="number"
                label={__('Maximum Folder Depth', 'prorank-seo')}
                value={localSettings.max_folder_depth}
                onChange={(e) => updateSetting('max_folder_depth', parseInt(e.target.value) || 10)}
                min="1"
                max="50"
              />
              <p className="pr:text-sm pr:text-gray-500 pr:mt-1">
                {__('Maximum folder levels in URL path', 'prorank-seo')}
              </p>
            </div>

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

            <div>
              <Input
                type="number"
                label={__('Maximum Query Parameters', 'prorank-seo')}
                value={localSettings.max_query_params}
                onChange={(e) => updateSetting('max_query_params', parseInt(e.target.value) || 5)}
                min="0"
                max="20"
              />
            </div>
          </div>
        </div>
      </Card>

      {/* Robots Settings */}
      <Card>
        <div className="pr:p-6">
          <h3 className="pr:text-lg pr:font-semibold pr:mb-4">{__('Robots Instructions', 'prorank-seo')}</h3>
          <div>
            <Toggle
              label={__('Ignore robots.txt', 'prorank-seo')}
              checked={localSettings.ignore_robots_txt}
              onChange={(value) => updateSetting('ignore_robots_txt', value)}
            />
            <p className="pr:text-sm pr:text-gray-500 pr:mt-1 pr:ml-12">
              {__('Crawl pages even if disallowed by robots.txt', 'prorank-seo')}
            </p>
          </div>
        </div>
      </Card>

      {/* URL Patterns */}
      <Card>
        <div className="pr:p-6">
          <h3 className="pr:text-lg pr:font-semibold pr:mb-4">{__('Include and Exclude URLs', 'prorank-seo')}</h3>
          <div className="pr:space-y-4">
            <div>
              <Textarea
                label={__('Only crawl URLs matching these patterns', 'prorank-seo')}
                value={localSettings.include_patterns}
                onChange={(e) => updateSetting('include_patterns', e.target.value)}
                placeholder="/blog/*&#10;/products/*&#10;*.html"
                rows={4}
              />
              <p className="pr:text-sm pr:text-gray-500 pr:mt-1">
                {__('One pattern per line. Use * for wildcards, or regex patterns.', 'prorank-seo')}
              </p>
            </div>

            <div>
              <Textarea
                label={__("Don't crawl URLs matching these patterns", 'prorank-seo')}
                value={localSettings.exclude_patterns}
                onChange={(e) => updateSetting('exclude_patterns', e.target.value)}
                placeholder="/admin/*&#10;/wp-admin/*&#10;*.pdf&#10;/tag/*"
                rows={4}
              />
              <p className="pr:text-sm pr:text-gray-500 pr:mt-1">
                {__('One pattern per line. Common exclusions: admin areas, PDFs, tag pages.', 'prorank-seo')}
              </p>
            </div>
          </div>
        </div>
      </Card>

      {/* Actions */}
      <div className="pr:flex pr:justify-end pr:gap-3 pr:mt-6">
        <Button variant="secondary" onClick={onClose}>
          {__('Cancel', 'prorank-seo')}
        </Button>
        <Button variant="primary" onClick={handleSave} loading={saving}>
          {__('Save Settings', 'prorank-seo')}
        </Button>
      </div>
    </div>
  );
};

export default AuditSettings;
