/**
 * Internal Linking Sidebar Shell Component
 *
 * Hybrid UI component providing auto-linking settings with link to full page.
 *
 * @package
 * @since   1.0.0
 */

import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { external, plus, trash } from '@wordpress/icons';
import apiFetch from '@wordpress/api-fetch';
import { Card, Button, Input, Textarea, Checkbox } from '../../../components/ui';
import { Heading, Text } from '../../../components/common/Typography';
import { useNotification } from '../../../contexts/NotificationContext';
import OnboardingHint from '../../../../components/OnboardingHint';

const InternalLinkingSidebarShell = () => {
  const [settings, setSettings] = useState({
    // Auto-linking settings
    auto_linking_enabled: false,
    auto_linking_mappings: [],
    auto_linking_max_per_post: 5,
    auto_linking_exclusions: {
      post_ids: [],
      css_classes: [],
    },
    // Scan settings
    auto_linking_orphan_scan_enabled: false,
    auto_linking_orphan_scan_frequency: 'weekly',
    auto_linking_inbound_scan_enabled: false,
    auto_linking_inbound_scan_frequency: 'weekly',
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const { showNotification } = useNotification();

  useEffect(() => {
    loadSettings();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  const loadSettings = async () => {
    setLoading(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/auto_linking',
      });

      if (response.success && response.data) {
        // Ensure mappings is an array
        const data = {
          ...response.data,
          auto_linking_mappings: response.data.auto_linking_mappings || [],
          auto_linking_exclusions: response.data.auto_linking_exclusions || {
            post_ids: [],
            css_classes: [],
          },
        };
        setSettings(data);
      }
    } catch (error) {
      showNotification(__('Failed to load settings', 'prorank-seo'), 'error');
    } finally {
      setLoading(false);
    }
  };

  const saveSettings = async () => {
    setSaving(true);
    try {
      await apiFetch({
        path: '/prorank-seo/v1/settings/auto_linking',
        method: 'POST',
        data: settings,
      });
      showNotification(__('Settings saved successfully', 'prorank-seo'), 'success');
    } catch (error) {
      showNotification(__('Failed to save settings', 'prorank-seo'), 'error');
    } finally {
      setSaving(false);
    }
  };

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

  const addMapping = () => {
    const newMapping = {
      id: Date.now(),
      keyword: '',
      url: '',
      case_sensitive: false,
      limit_once: true,
    };
    updateSetting('auto_linking_mappings', [...settings.auto_linking_mappings, newMapping]);
  };

  const updateMapping = (index, field, value) => {
    const updatedMappings = [...settings.auto_linking_mappings];
    updatedMappings[index] = {
      ...updatedMappings[index],
      [field]: value,
    };
    updateSetting('auto_linking_mappings', updatedMappings);
  };

  const removeMapping = (index) => {
    const updatedMappings = settings.auto_linking_mappings.filter((_, i) => i !== index);
    updateSetting('auto_linking_mappings', updatedMappings);
  };

  const updateExclusions = (field, value) => {
    updateSetting('auto_linking_exclusions', {
      ...settings.auto_linking_exclusions,
      [field]: value,
    });
  };

  if (loading) {
    return (
      <div className="prorank-settings-loading pr:flex pr:items-center pr:gap-2">
        <div className="pr:animate-spin pr:h-5 pr:w-5 pr:border-2 pr:border-primary pr:border-t-transparent pr:rounded-full" />
        <Text>{__('Loading settings…', 'prorank-seo')}</Text>
      </div>
    );
  }

  return (
    <div className="prorank-internal-linking-sidebar">
      <div className="prorank-settings-header">
        <Text>
          {__(
            'Automate internal links with keyword mappings, orphan scans, and inbound opportunity reviews.',
            'prorank-seo'
          )}
        </Text>
      </div>

      <OnboardingHint
        content={__(
          'Auto-linking automatically creates internal links based on your keyword mappings. This helps improve site structure and SEO without manual effort.',
          'prorank-seo'
        )}
      />

      <Card
        className="prorank-settings-card"
        header={<Heading level={3}>{__('Auto-Linking', 'prorank-seo')}</Heading>}
      >
        <div className="pr:flex pr:items-center pr:justify-between">
          <div className="pr:space-y-0.5">
            <label>{__('Enable Auto-Linking', 'prorank-seo')}</label>
            <div className="pr:text-sm pr:text-muted-foreground">
              {__('Automatically create internal links based on keyword mappings.', 'prorank-seo')}
            </div>
          </div>
          <Checkbox
            checked={settings.auto_linking_enabled}
            onChange={(value) => updateSetting('auto_linking_enabled', value)}
          />
        </div>

          {settings.auto_linking_enabled && (
            <>
              <div className="prorank-auto-linking-mappings">
                <Heading level={4}>{__('Keyword Mappings', 'prorank-seo')}</Heading>
                
                {settings.auto_linking_mappings.map((mapping, index) => (
                  <div key={mapping.id || index} className="prorank-mapping-item pr:space-y-4 pr:p-4 pr:border pr:rounded-lg">
                    <div className="pr:space-y-2">
                      <label>{__('Keyword', 'prorank-seo')}</label>
                      <Input
                        value={mapping.keyword}
                        onChange={(value) => updateMapping(index, 'keyword', value)}
                        placeholder={__('e.g., SEO tips', 'prorank-seo')}
                      />
                    </div>

                    <div className="pr:space-y-2">
                      <label>{__('Target URL', 'prorank-seo')}</label>
                      <Input
                        type="url"
                        value={mapping.url}
                        onChange={(value) => updateMapping(index, 'url', value)}
                        placeholder={__('https://example.com/seo-guide', 'prorank-seo')}
                      />
                    </div>

                    <div className="prorank-mapping-options pr:space-y-2">
                      <div className="pr:flex pr:items-center pr:space-x-2">
                        <Checkbox
                          id={`case-sensitive-${index}`}
                          checked={mapping.case_sensitive}
                          onChange={(value) => updateMapping(index, 'case_sensitive', value)}
                        />
                        <label htmlFor={`case-sensitive-${index}`}>
                          {__('Case sensitive', 'prorank-seo')}
                        </label>
                      </div>

                      <div className="pr:flex pr:items-center pr:space-x-2">
                        <Checkbox
                          id={`limit-once-${index}`}
                          checked={mapping.limit_once}
                          onChange={(value) => updateMapping(index, 'limit_once', value)}
                        />
                        <label htmlFor={`limit-once-${index}`}>
                          {__('Link only once per post', 'prorank-seo')}
                        </label>
                      </div>
                    </div>

                    <Button
                      variant="destructive"
                      size="sm"
                      onClick={() => removeMapping(index)}
                    >
                      {__('Remove mapping', 'prorank-seo')}
                    </Button>
                  </div>
                ))}
                
                <Button
                  variant="outline"
                  onClick={addMapping}
                >
                  {__('Add Keyword Mapping', 'prorank-seo')}
                </Button>
              </div>

              <div className="pr:space-y-2">
                <label>{__('Maximum Links Per Post', 'prorank-seo')}</label>
                <Input
                  type="number"
                  value={settings.auto_linking_max_per_post}
                  onChange={(e) => updateSetting('auto_linking_max_per_post', parseInt(e.target.value) || 5)}
                  min={1}
                  max={20}
                />
                <div className="pr:text-sm pr:text-muted-foreground">
                  {__('Maximum number of auto-links to add to a single post.', 'prorank-seo')}
                </div>
              </div>

              <div className="pr:space-y-2">
                <label>{__('Excluded Post IDs', 'prorank-seo')}</label>
                <Textarea
                  value={settings.auto_linking_exclusions.post_ids.join(', ')}
                  onChange={(e) => {
                    const ids = e.target.value.split(',').map(id => id.trim()).filter(id => id);
                    updateExclusions('post_ids', ids);
                  }}
                  placeholder={__('e.g., 123, 456, 789', 'prorank-seo')}
                />
                <div className="pr:text-sm pr:text-muted-foreground">
                  {__('Comma-separated list of post IDs to exclude from auto-linking.', 'prorank-seo')}
                </div>
              </div>

              <div className="pr:space-y-2">
                <label>{__('Excluded CSS Classes', 'prorank-seo')}</label>
                <Input
                  value={settings.auto_linking_exclusions.css_classes.join(', ')}
                  onChange={(e) => {
                    const classes = e.target.value.split(',').map(cls => cls.trim()).filter(cls => cls);
                    updateExclusions('css_classes', classes);
                  }}
                  placeholder={__('e.g., no-autolink, exclude-links', 'prorank-seo')}
                />
                <div className="pr:text-sm pr:text-muted-foreground">
                  {__('Comma-separated list of CSS classes. Content within these classes will not be auto-linked.', 'prorank-seo')}
                </div>
              </div>
            </>
          )}
      </Card>

      <Card
        className="prorank-settings-card"
        header={<Heading level={3}>{__('Content Scans', 'prorank-seo')}</Heading>}
      >
        <div className="pr:space-y-4">
          <div className="pr:flex pr:items-center pr:justify-between">
            <div className="pr:space-y-0.5">
              <label>{__('Enable Orphan Content Scan', 'prorank-seo')}</label>
              <div className="pr:text-sm pr:text-muted-foreground">
                {__('Automatically scan for content with no internal links pointing to it.', 'prorank-seo')}
              </div>
            </div>
            <Checkbox
              checked={settings.auto_linking_orphan_scan_enabled}
              onChange={(value) => updateSetting('auto_linking_orphan_scan_enabled', value)}
            />
          </div>

          <div className="pr:flex pr:items-center pr:justify-between">
            <div className="pr:space-y-0.5">
              <label>{__('Enable Inbound Opportunity Scan', 'prorank-seo')}</label>
              <div className="pr:text-sm pr:text-muted-foreground">
                {__('Find opportunities to add internal links between your content.', 'prorank-seo')}
              </div>
            </div>
            <Checkbox
              checked={settings.auto_linking_inbound_scan_enabled}
              onChange={(value) => updateSetting('auto_linking_inbound_scan_enabled', value)}
            />
          </div>
        </div>
      </Card>

      <div className="prorank-settings-actions pr:flex pr:gap-2">
        <Button onClick={saveSettings} disabled={saving}>
          {saving ? __('Saving…', 'prorank-seo') : __('Save Settings', 'prorank-seo')}
        </Button>

        <Button
          variant="outline"
          asChild
        >
          <a href={`${window.prorankSeoAdmin?.admin_url || ''}admin.php?page=prorank-internal-linking#?tab=links-report`}>
            {__('View Reports', 'prorank-seo')}
          </a>
        </Button>
      </div>
    </div>
  );
};

export default InternalLinkingSidebarShell;
