import { __ } from '@wordpress/i18n';
import { useState, useEffect } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';
import { useNotification } from '../../../contexts/NotificationContext';
import {
  Button,
  Toggle,
  Select,
  Input,
  Card,
  Alert,
} from '../../../components/ui';
import {
  Cog6ToothIcon,
  ArrowPathRoundedSquareIcon,
  LinkIcon,
  Squares2X2Icon,
  TagIcon,
  XMarkIcon,
  ChartBarIcon,
  ExclamationTriangleIcon,
} from '@heroicons/react/24/outline';

const InternalLinkingSettings = () => {
  const [settings, setSettings] = useState({
    enabled: true,
    auto_linking: false,
    max_suggestions: 10,
    max_links_per_post: 5,
    min_word_count: 80,
    link_post_types: ['post', 'page'],
    exclude_categories: [],
    ignore_words: '',
    open_in_new_tab: false,
    open_internal_new_tab: false,
    open_external_new_tab: true,
    add_nofollow: false,
    add_title_attribute: true,
    track_clicks: true,
    suggestion_algorithm: 'balanced', // 'keyword', 'semantic', 'balanced'
    anchor_text_length: 4,
    skip_sentences_with_links: true,
    randomize_suggestions: false,
  });
  
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [categories, setCategories] = useState([]);
  const { showNotification } = useNotification();

  useEffect(() => {
    loadSettings();
    loadCategories();
  }, []);

  const loadSettings = async () => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/internal-linking',
      });
      if (response.success && response.data) {
        const normalizedData = { ...response.data };
        const resolvedPostTypes = (
          Array.isArray(normalizedData.post_types) && normalizedData.post_types.length > 0
            ? normalizedData.post_types
            : (Array.isArray(normalizedData.link_post_types) && normalizedData.link_post_types.length > 0
              ? normalizedData.link_post_types
              : ['post', 'page'])
        );
        const resolvedInternalNewTab = Boolean(
          normalizedData.open_internal_new_tab ?? normalizedData.open_in_new_tab ?? false
        );

        setSettings(prevSettings => ({
          ...prevSettings,
          ...normalizedData,
          post_types: resolvedPostTypes,
          open_internal_new_tab: resolvedInternalNewTab,
          ai_suggestions: false,
          ai_anchor_generation: false,
          gsc_integration: false,
          keyword_sources: Array.isArray(normalizedData.keyword_sources)
            ? normalizedData.keyword_sources.filter((source) => !['ai', 'gsc'].includes(source))
            : ['title', 'slug', 'focus', 'categories', 'tags', 'custom'],
        }));
      }
    } catch (error) {
      // Error loading settings
    } finally {
      setLoading(false);
    }
  };

  const loadCategories = async () => {
    try {
      const response = await apiFetch({
        path: '/wp/v2/categories?per_page=100',
      });
      setCategories(response.map(cat => ({
        label: cat.name,
        value: cat.id.toString(),
      })));
    } catch (error) {
      // Error loading categories
    }
  };

  const saveSettings = async () => {
    setSaving(true);
    try {
      const normalizedPostTypes = Array.isArray(settings.post_types) && settings.post_types.length > 0
        ? settings.post_types
        : ['post', 'page'];

      const payload = {
        ...settings,
        post_types: normalizedPostTypes,
        ai_suggestions: false,
        ai_anchor_generation: false,
        gsc_integration: false,
        keyword_sources: (settings.keyword_sources || []).filter((source) => !['ai', 'gsc'].includes(source)),
      };

      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/internal-linking',
        method: 'POST',
        data: payload,
      });
      
      if (response.success) {
        showNotification(__('Settings saved successfully', 'prorank-seo'), 'success');
      } else {
        throw new Error(response.message || 'Failed to save settings');
      }
    } catch (error) {
      showNotification(
        error.message || __('Failed to save settings', 'prorank-seo'),
        'error'
      );
    } finally {
      setSaving(false);
    }
  };

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

  if (loading) {
    return (
      <div className="pr:flex pr:flex-col pr:items-center pr:justify-center pr:min-h-[400px] pr:gap-4">
        <div className="pr:animate-spin pr:w-8 pr:h-8 pr:border-4 pr:border-primary-500 pr:border-t-transparent pr:rounded-full" />
        <p className="pr:text-sm pr:text-gray-600">{__('Loading settings...', 'prorank-seo')}</p>
      </div>
    );
  }

  return (
    <div className="pr:space-y-6">
      <Alert variant="info">
        {__('Use this page to configure Internal Linking behavior and optional modules. Run scans, review reports, and execute auto-linking from the Internal Linking page tabs.', 'prorank-seo')}
      </Alert>

      <Card
        header={
          <div className="pr:flex pr:items-center pr:gap-2">
            <Cog6ToothIcon className="pr:w-5 pr:h-5 pr:text-gray-500" />
            <h2 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Core Engine', 'prorank-seo')}
            </h2>
          </div>
        }
      >
        <div className="pr:space-y-6">
          <Toggle
            label={__('Enable Internal Linking', 'prorank-seo')}
            description={__('Enable or disable internal linking suggestions', 'prorank-seo')}
            checked={settings.enabled}
            onChange={(value) => handleSettingChange('enabled', value)}
          />

          <div>
            <Toggle
              label={__('Auto-Linking', 'prorank-seo')}
              description={__('Apply saved keyword-to-URL rules during preview runs and background batches', 'prorank-seo')}
              checked={settings.auto_linking}
              onChange={(value) => handleSettingChange('auto_linking', value)}
              disabled={!settings.enabled}
            />
          </div>

          <Input
            type="number"
            label={__('Maximum Suggestions Per Post', 'prorank-seo')}
            helperText={__('Maximum number of link suggestions to show', 'prorank-seo')}
            value={settings.max_suggestions}
            onChange={(value) => handleSettingChange('max_suggestions', parseInt(value))}
            min={1}
            max={50}
            disabled={!settings.enabled}
          />

          <Input
            type="number"
            label={__('Maximum Links Per Post', 'prorank-seo')}
            helperText={__('Maximum internal links to add per post', 'prorank-seo')}
            value={settings.max_links_per_post}
            onChange={(value) => handleSettingChange('max_links_per_post', parseInt(value))}
            min={1}
            max={20}
            disabled={!settings.enabled}
          />

          <Input
            type="number"
            label={__('Minimum Word Count', 'prorank-seo')}
            helperText={__('Minimum words required before suggesting links', 'prorank-seo')}
            value={settings.min_word_count}
            onChange={(value) => handleSettingChange('min_word_count', parseInt(value))}
            min={30}
            max={500}
            step={10}
            disabled={!settings.enabled}
          />
        </div>
      </Card>

      <Card
        header={
          <div className="pr:flex pr:items-center pr:gap-2">
            <ArrowPathRoundedSquareIcon className="pr:w-5 pr:h-5 pr:text-gray-500" />
            <h2 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Suggestion Logic', 'prorank-seo')}
            </h2>
          </div>
        }
      >
        <div className="pr:space-y-6">
          <Select
            label={__('Algorithm Type', 'prorank-seo')}
            helperText={__('Choose how suggestions are generated', 'prorank-seo')}
            value={settings.suggestion_algorithm}
            options={[
              { label: __('Keyword Matching', 'prorank-seo'), value: 'keyword' },
              { label: __('Contextual Analysis', 'prorank-seo'), value: 'semantic' },
              { label: __('Balanced (Recommended)', 'prorank-seo'), value: 'balanced' },
            ]}
            onChange={(value) => handleSettingChange('suggestion_algorithm', value)}
            disabled={!settings.enabled}
          />

          <Input
            type="number"
            label={__('Minimum Anchor Text Words', 'prorank-seo')}
            helperText={__('Minimum words in anchor text', 'prorank-seo')}
            value={settings.anchor_text_length}
            onChange={(value) => handleSettingChange('anchor_text_length', parseInt(value))}
            min={1}
            max={10}
            disabled={!settings.enabled}
          />

          <Toggle
            label={__('Skip Sentences with Existing Links', 'prorank-seo')}
            description={__('Don\'t suggest links in sentences that already have links', 'prorank-seo')}
            checked={settings.skip_sentences_with_links}
            onChange={(value) => handleSettingChange('skip_sentences_with_links', value)}
            disabled={!settings.enabled}
          />

          <Toggle
            label={__('Randomize Suggestions', 'prorank-seo')}
            description={__('Show suggestions in random order instead of by relevance', 'prorank-seo')}
            checked={settings.randomize_suggestions}
            onChange={(value) => handleSettingChange('randomize_suggestions', value)}
            disabled={!settings.enabled}
          />
        </div>
      </Card>

      <Card
        header={
          <div className="pr:flex pr:items-center pr:gap-2">
            <LinkIcon className="pr:w-5 pr:h-5 pr:text-gray-500" />
            <h2 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Link Output', 'prorank-seo')}
            </h2>
          </div>
        }
      >
        <div className="pr:space-y-6">
          <Toggle
            label={__('Open Internal Links in New Tab', 'prorank-seo')}
            description={__('Add target="_blank" to ProRank-created internal links', 'prorank-seo')}
            checked={settings.open_internal_new_tab}
            onChange={(value) => handleSettingChange('open_internal_new_tab', value)}
            disabled={!settings.enabled}
          />

          <Toggle
            label={__('Open External Links in New Tab', 'prorank-seo')}
            description={__('Add target="_blank" to ProRank-created external links', 'prorank-seo')}
            checked={settings.open_external_new_tab}
            onChange={(value) => handleSettingChange('open_external_new_tab', value)}
            disabled={!settings.enabled}
          />

          <Toggle
            label={__('Add Nofollow Attribute', 'prorank-seo')}
            description={__('Add rel="nofollow" to ProRank-created external links', 'prorank-seo')}
            checked={settings.add_nofollow}
            onChange={(value) => handleSettingChange('add_nofollow', value)}
            disabled={!settings.enabled}
          />

          <Toggle
            label={__('Track Link Clicks', 'prorank-seo')}
            description={__('Enable click tracking for internal links. Required for link performance reporting.', 'prorank-seo')}
            checked={settings.track_clicks}
            onChange={(value) => handleSettingChange('track_clicks', value)}
            disabled={!settings.enabled}
          />

          <Toggle
            label={__('Add Destination Post Title to Links', 'prorank-seo')}
            description={__('Add title attribute with destination post title', 'prorank-seo')}
            checked={settings.add_title_attribute}
            onChange={(value) => handleSettingChange('add_title_attribute', value)}
            disabled={!settings.enabled}
          />
        </div>
      </Card>

      <Card
        header={
          <div className="pr:flex pr:items-center pr:gap-2">
            <Squares2X2Icon className="pr:w-5 pr:h-5 pr:text-gray-500" />
            <h2 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Content Scope', 'prorank-seo')}
            </h2>
          </div>
        }
      >
        <div className="pr:space-y-6">
          <div>
            <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700 pr:mb-2">
              {__('Post Types to Process', 'prorank-seo')}
            </label>
            <p className="pr:text-xs pr:text-gray-500 pr:mb-3">
              {__('Select which post types to include in internal linking', 'prorank-seo')}
            </p>
            <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:gap-3">
              {[
                { value: 'post', label: __('Posts', 'prorank-seo') },
                { value: 'page', label: __('Pages', 'prorank-seo') },
                { value: 'attachment', label: __('Media', 'prorank-seo') },
                { value: 'product', label: __('Products (WooCommerce)', 'prorank-seo') },
              ].map(type => (
                <label key={type.value} className="pr:flex pr:items-center pr:gap-2 pr:cursor-pointer">
                  <input
                    type="checkbox"
                    checked={settings.post_types && settings.post_types.includes(type.value) || false}
                    onChange={(value) => {
                      const checked = value?.target ? value.target.checked : !!value;
                      const types = settings.post_types || ['post', 'page'];
                      if (checked) {
                        handleSettingChange('post_types', [...types, type.value]);
                      } else {
                        handleSettingChange('post_types', types.filter(t => t !== type.value));
                      }
                    }}
                    disabled={!settings.enabled}
                    className="pr:w-4 pr:h-4 pr:text-primary-500 pr:border-gray-300 pr:rounded-xs pr:focus:ring-2 pr:focus:ring-primary-500"
                  />
                  <span className="pr:text-sm pr:text-gray-900">{type.label}</span>
                </label>
              ))}
            </div>
          </div>

          <div className="pr:rounded-lg pr:border pr:border-gray-200 pr:bg-gray-50 pr:p-4">
            <p className="pr:text-sm pr:font-medium pr:text-gray-900 pr:mb-2">
              {__('Page Builder Content Support', 'prorank-seo')}
            </p>
            <p className="pr:text-xs pr:text-gray-600 pr:mb-2">
              {__('Internal linking analysis includes standard editor content plus major page-builder fields.', 'prorank-seo')}
            </p>
            <div className="pr:flex pr:flex-wrap pr:gap-2">
              <span className="pr:inline-flex pr:items-center pr:rounded-full pr:bg-emerald-100 pr:px-2.5 pr:py-1 pr:text-xs pr:font-medium pr:text-emerald-800">
                Elementor
              </span>
              <span className="pr:inline-flex pr:items-center pr:rounded-full pr:bg-emerald-100 pr:px-2.5 pr:py-1 pr:text-xs pr:font-medium pr:text-emerald-800">
                Beaver Builder
              </span>
              <span className="pr:inline-flex pr:items-center pr:rounded-full pr:bg-emerald-100 pr:px-2.5 pr:py-1 pr:text-xs pr:font-medium pr:text-emerald-800">
                Divi
              </span>
            </div>
          </div>

          <Select
            label={__('Post Status to Create Links For', 'prorank-seo')}
            helperText={__('Which post statuses should be considered for linking', 'prorank-seo')}
            value={settings.post_statuses || 'publish'}
            options={[
              { label: __('Published Only', 'prorank-seo'), value: 'publish' },
              { label: __('Published & Private', 'prorank-seo'), value: 'publish,private' },
              { label: __('All Including Drafts', 'prorank-seo'), value: 'all' },
            ]}
            onChange={(value) => handleSettingChange('post_statuses', value)}
            disabled={!settings.enabled}
          />

          <Input
            type="number"
            label={__('Number of Sentences to Skip at Beginning', 'prorank-seo')}
            helperText={__('Skip this many opening sentences during auto-linking runs', 'prorank-seo')}
            value={settings.skip_sentences || 3}
            onChange={(value) => handleSettingChange('skip_sentences', parseInt(value))}
            min={0}
            max={10}
            disabled={!settings.enabled}
          />

          <Select
            label={__('Maximum Age of Posts to Link To', 'prorank-seo')}
            helperText={__('Don\'t suggest links to posts older than this', 'prorank-seo')}
            value={settings.max_post_age || 'no_limit'}
            options={[
              { label: __('No Limit', 'prorank-seo'), value: 'no_limit' },
              { label: __('1 Month', 'prorank-seo'), value: '30' },
              { label: __('3 Months', 'prorank-seo'), value: '90' },
              { label: __('6 Months', 'prorank-seo'), value: '180' },
              { label: __('1 Year', 'prorank-seo'), value: '365' },
              { label: __('2 Years', 'prorank-seo'), value: '730' },
            ]}
            onChange={(value) => handleSettingChange('max_post_age', value)}
            disabled={!settings.enabled}
          />

          <div>
            <Input
              type="number"
              label={__('Maximum Outbound Links Per Post', 'prorank-seo')}
              helperText={__('Maximum outbound internal links to add per post (0 = No Limit)', 'prorank-seo')}
              value={settings.max_outbound_links || 0}
              onChange={(value) => handleSettingChange('max_outbound_links', parseInt(value))}
              min={0}
              max={50}
              disabled={!settings.enabled}
            />
          </div>

          <div>
            <Input
              type="number"
              label={__('Maximum Inbound Links Per Post', 'prorank-seo')}
              helperText={__('Maximum inbound internal links auto-linking can create for a post (0 = No Limit)', 'prorank-seo')}
              value={settings.max_inbound_links || 0}
              onChange={(value) => handleSettingChange('max_inbound_links', parseInt(value))}
              min={0}
              max={50}
              disabled={!settings.enabled}
            />
          </div>
        </div>
      </Card>

      <Card
        header={
          <div className="pr:flex pr:items-center pr:gap-2">
            <TagIcon className="pr:w-5 pr:h-5 pr:text-gray-500" />
            <h2 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Keyword Sources', 'prorank-seo')}
            </h2>
          </div>
        }
      >
        <div className="pr:space-y-4">
          <p className="pr:text-sm pr:text-gray-500">
            {__('Select which sources to use for identifying target keywords', 'prorank-seo')}
          </p>
          <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:gap-3">
            {[
              { value: 'focus', label: __('ProRank Focus Keywords', 'prorank-seo') },
              { value: 'title', label: __('Page Title Keywords', 'prorank-seo') },
              { value: 'slug', label: __('URL Slug Keywords', 'prorank-seo') },
              { value: 'categories', label: __('Category Names', 'prorank-seo') },
              { value: 'tags', label: __('Tag Names', 'prorank-seo') },
              { value: 'custom', label: __('Custom Keywords', 'prorank-seo') },
            ].map(source => (
              <label key={source.value} className="pr:flex pr:items-center pr:gap-2 pr:cursor-pointer">
                <input
                  type="checkbox"
                  checked={settings.keyword_sources && settings.keyword_sources.includes(source.value) || false}
                  onChange={(value) => {
                    const checked = value?.target ? value.target.checked : !!value;
                    const sources = settings.keyword_sources || ['title', 'slug'];
                    if (checked) {
                      handleSettingChange('keyword_sources', [...sources, source.value]);
                    } else {
                      handleSettingChange('keyword_sources', sources.filter(s => s !== source.value));
                    }
                  }}
                  disabled={!settings.enabled}
                  className="pr:w-4 pr:h-4 pr:text-primary-500 pr:border-gray-300 pr:rounded-xs pr:focus:ring-2 pr:focus:ring-primary-500"
                />
                <span className="pr:text-sm pr:text-gray-900">{source.label}</span>
              </label>
            ))}
          </div>
        </div>
      </Card>

      <Card
        header={
          <div className="pr:flex pr:items-center pr:gap-2">
            <XMarkIcon className="pr:w-5 pr:h-5 pr:text-gray-500" />
            <h2 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Exclusions', 'prorank-seo')}
            </h2>
          </div>
        }
      >
        <div className="pr:space-y-6">
          <Toggle
            label={__('Ignore Numbers', 'prorank-seo')}
            description={__('Don\'t create links from numeric values', 'prorank-seo')}
            checked={settings.ignore_numbers}
            onChange={(value) => handleSettingChange('ignore_numbers', value)}
            disabled={!settings.enabled}
          />

          <Select
            label={__('Selected Language', 'prorank-seo')}
            helperText={__('Language for stop words and stemming (native support for English, Spanish, French, German, Italian, Portuguese, Dutch, Polish, Swedish, Turkish)', 'prorank-seo')}
            value={settings.language || 'en'}
            options={[
              { label: __('English', 'prorank-seo'), value: 'en' },
              { label: __('Spanish', 'prorank-seo'), value: 'es' },
              { label: __('French', 'prorank-seo'), value: 'fr' },
              { label: __('German', 'prorank-seo'), value: 'de' },
              { label: __('Italian', 'prorank-seo'), value: 'it' },
              { label: __('Portuguese', 'prorank-seo'), value: 'pt' },
              { label: __('Dutch', 'prorank-seo'), value: 'nl' },
              { label: __('Polish', 'prorank-seo'), value: 'pl' },
              { label: __('Swedish', 'prorank-seo'), value: 'sv' },
              { label: __('Turkish', 'prorank-seo'), value: 'tr' },
            ]}
            onChange={(value) => handleSettingChange('language', value)}
            disabled={!settings.enabled}
          />

          <div>
            <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700 pr:mb-2">
              {__('Words to be Ignored', 'prorank-seo')}
            </label>
            <p className="pr:text-xs pr:text-gray-500 pr:mb-2">
              {__('One word per line. These words will not be used for link suggestions.', 'prorank-seo')}
            </p>
            <textarea
              value={settings.ignored_words || 'a\nabout\nabove\nafter\nagain\nall\nam\nan\nand\nany\nare\nas\nat\nbe\nbeen\nbefore\nbeing\nbelow\nbetween\nboth\nbut\nby\ncan\ncould\ndid\ndo\ndoes\ndoing\ndown\nduring\neach\nfew\nfor\nfrom\nfurther\nhad\nhas\nhave\nhaving\nhe\nher\nhere\nhers\nherself\nhim\nhimself\nhis\nhow\nif\nin\ninto\nis\nit\nits\nitself\njust\nme\nmore\nmost\nmy\nmyself\nno\nnor\nnot\nof\noff\non\nonce\nonly\nor\nother\nour\nours\nourselves\nout\nover\nown\nsame\nshe\nshould\nso\nsome\nsuch\nthan\nthat\nthe\ntheir\nthem\nthemselves\nthen\nthere\nthese\nthey\nthis\nthose\nthrough\nto\ntoo\nunder\nuntil\nup\nvery\nwas\nwe\nwere\nwhat\nwhen\nwhere\nwhich\nwhile\nwho\nwhom\nwhy\nwill\nwith\nwould\nyou\nyour\nyours\nyourself\nyourselves'}
              onChange={(e) => handleSettingChange('ignored_words', e.target.value)}
              disabled={!settings.enabled}
              className="pr:block pr:w-full pr:px-3 pr:py-2 pr:border pr:border-gray-300 pr:rounded-md pr:text-sm pr:focus:outline-hidden pr:focus:ring-2 pr:focus:ring-primary-500 pr:focus:border-transparent pr:min-h-[200px] pr:font-mono"
            />
          </div>

          <Input
            label={__('Additional Ignore Words', 'prorank-seo')}
            helperText={__('Comma-separated list of additional words to ignore', 'prorank-seo')}
            value={settings.ignore_words}
            onChange={(value) => handleSettingChange('ignore_words', value)}
            placeholder="example, test, demo"
            disabled={!settings.enabled}
          />

          {categories.length > 0 && (
            <div>
              <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700 pr:mb-2">
                {__('Exclude Categories', 'prorank-seo')}
              </label>
              <p className="pr:text-xs pr:text-gray-500 pr:mb-3">
                {__('Select categories to exclude from linking', 'prorank-seo')}
              </p>
              <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:gap-3">
                {categories.map(cat => (
                  <label key={cat.value} className="pr:flex pr:items-center pr:gap-2 pr:cursor-pointer">
                    <input
                      type="checkbox"
                      checked={settings.exclude_categories.includes(cat.value)}
                      onChange={(value) => {
                        const checked = value?.target ? value.target.checked : !!value;
                        const newCategories = checked
                          ? [...settings.exclude_categories, cat.value]
                          : settings.exclude_categories.filter(id => id !== cat.value);
                        handleSettingChange('exclude_categories', newCategories);
                      }}
                      disabled={!settings.enabled}
                      className="pr:w-4 pr:h-4 pr:text-primary-500 pr:border-gray-300 pr:rounded-xs pr:focus:ring-2 pr:focus:ring-primary-500"
                    />
                    <span className="pr:text-sm pr:text-gray-900">{cat.label}</span>
                  </label>
                ))}
              </div>
            </div>
          )}
        </div>
      </Card>

      <Alert variant="info">
        {__('Optional modules below control reports and scans. Configure them here, then use the Links Report, Broken Links, and other Internal Linking tabs to run the actual workflows.', 'prorank-seo')}
      </Alert>

      <Card
        header={
          <div className="pr:flex pr:items-center pr:gap-2">
            <ChartBarIcon className="pr:w-5 pr:h-5 pr:text-gray-500" />
            <h2 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Report Analytics Module', 'prorank-seo')}
            </h2>
          </div>
        }
      >
        <div className="pr:space-y-6">
          <Toggle
            label={__('Enable Links Report Analytics', 'prorank-seo')}
            description={__('Track and analyze internal link performance', 'prorank-seo')}
            checked={settings.enable_link_analysis || false}
            onChange={(value) => handleSettingChange('enable_link_analysis', value)}
            disabled={!settings.enabled}
          />

          <Toggle
            label={__('Track Click-Through Rates', 'prorank-seo')}
            description={__('Monitor how often internal links are clicked', 'prorank-seo')}
            checked={settings.track_ctr || false}
            onChange={(value) => handleSettingChange('track_ctr', value)}
            disabled={!settings.enabled || !settings.enable_link_analysis}
          />

          <Toggle
            label={__('Generate Link Reports', 'prorank-seo')}
            description={__('Store scan snapshots for Links Report history and exports', 'prorank-seo')}
            checked={settings.generate_reports || false}
            onChange={(value) => handleSettingChange('generate_reports', value)}
            disabled={!settings.enabled || !settings.enable_link_analysis}
          />
        </div>
      </Card>

      <Card
        header={
          <div className="pr:flex pr:items-center pr:gap-2">
            <ExclamationTriangleIcon className="pr:w-5 pr:h-5 pr:text-gray-500" />
            <h2 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Broken Links Module', 'prorank-seo')}
            </h2>
          </div>
        }
      >
        <div className="pr:space-y-6">
          <Toggle
            label={__('Enable Broken Link Detection', 'prorank-seo')}
            description={__('Automatically detect and report broken internal links', 'prorank-seo')}
            checked={settings.detect_broken_links || false}
            onChange={(value) => handleSettingChange('detect_broken_links', value)}
            disabled={!settings.enabled}
          />

          <Select
            label={__('Check Frequency', 'prorank-seo')}
            helperText={__('How often to check for broken links', 'prorank-seo')}
            value={settings.check_frequency || 'weekly'}
            options={[
              { label: __('Daily', 'prorank-seo'), value: 'daily' },
              { label: __('Weekly', 'prorank-seo'), value: 'weekly' },
              { label: __('Monthly', 'prorank-seo'), value: 'monthly' },
            ]}
            onChange={(value) => handleSettingChange('check_frequency', value)}
            disabled={!settings.enabled || !settings.detect_broken_links}
          />

          <Toggle
            label={__('Email Notifications', 'prorank-seo')}
            description={__('Send email when broken links are found', 'prorank-seo')}
            checked={settings.email_broken_links || false}
            onChange={(value) => handleSettingChange('email_broken_links', value)}
            disabled={!settings.enabled || !settings.detect_broken_links}
          />
        </div>
      </Card>

      <div className="pr:flex pr:justify-end pr:pt-6 pr:border-t pr:border-gray-200">
        <Button
          variant="primary"
          onClick={saveSettings}
          loading={saving}
          disabled={saving}
        >
          {saving ? __('Saving...', 'prorank-seo') : __('Save Settings', 'prorank-seo')}
        </Button>
      </div>
    </div>
  );
};

export default InternalLinkingSettings;
