import { useCallback, useEffect, useMemo, useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import {
  Card,
  CardBody,
  CardHeader,
  __experimentalHeading as Heading,
  __experimentalText as Text,
  TextControl,
  RangeControl,
  Button,
  Spinner,
} from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
import { Alert, Toggle } from '../../components/ui';

const TEXT_DOMAIN = 'prorank-seo';

const DEFAULT_SETTINGS = {
  enabled: true,
  auto_linking: false,
  max_links_per_post: 5,
  min_word_count: 80,
  post_types: ['post', 'page'],
  open_internal_new_tab: false,
  add_nofollow: false,
};

const DEFAULT_RULE = {
  keyword: '',
  target_url: '',
  case_sensitive: false,
  whole_word: true,
  max_links_per_post: 1,
  max_total_links: 10,
  exclude_posts: '',
  priority: 5,
  enabled: true,
};

const KNOWN_POST_TYPE_LABELS = {
  post: __('Posts', TEXT_DOMAIN),
  page: __('Pages', TEXT_DOMAIN),
  product: __('Products', TEXT_DOMAIN),
  prorank_podcast: __('Podcast Episodes', TEXT_DOMAIN),
};

const AutoLinkingTool = () => {
  const [loading, setLoading] = useState(true);
  const [processing, setProcessing] = useState('');
  const [creatingRule, setCreatingRule] = useState(false);
  const [rules, setRules] = useState([]);
  const [preview, setPreview] = useState([]);
  const [notice, setNotice] = useState(null);
  const [settings, setSettings] = useState(DEFAULT_SETTINGS);
  const [ruleForm, setRuleForm] = useState(DEFAULT_RULE);
  const [stats, setStats] = useState({
    total_rules: 0,
    active_rules: 0,
    links_created: 0,
    last_run: null,
    current_job: null,
  });
  const currentJob = stats.current_job || null;
  const isBatchRunning = currentJob?.status === 'processing';

  const settingsSummary = useMemo(() => {
    const enabledTypes = (settings.post_types || []).map((type) => KNOWN_POST_TYPE_LABELS[type] || type);

    return [
      {
        label: __('Internal Linking', TEXT_DOMAIN),
        value: settings.enabled ? __('Enabled', TEXT_DOMAIN) : __('Disabled', TEXT_DOMAIN),
      },
      {
        label: __('Auto Linking', TEXT_DOMAIN),
        value: settings.auto_linking ? __('Enabled', TEXT_DOMAIN) : __('Disabled', TEXT_DOMAIN),
      },
      {
        label: __('Max Links Per Post', TEXT_DOMAIN),
        value: String(Number(settings.max_links_per_post || 5)),
      },
      {
        label: __('Minimum Word Count', TEXT_DOMAIN),
        value: String(Number(settings.min_word_count || 80)),
      },
      {
        label: __('Open In New Tab', TEXT_DOMAIN),
        value: settings.open_internal_new_tab ? __('Yes', TEXT_DOMAIN) : __('No', TEXT_DOMAIN),
      },
      {
        label: __('Add Nofollow', TEXT_DOMAIN),
        value: settings.add_nofollow ? __('Yes', TEXT_DOMAIN) : __('No', TEXT_DOMAIN),
      },
      {
        label: __('Post Types', TEXT_DOMAIN),
        value: enabledTypes.length ? enabledTypes.join(', ') : __('None selected', TEXT_DOMAIN),
      },
    ];
  }, [settings]);

  const openSettingsTab = () => {
    const baseHash = window.location.hash.split('?')[0];
    window.location.hash = `${baseHash}?tab=settings`;
  };

  const loadSettings = useCallback(async () => {
    const response = await apiFetch({
      path: '/prorank-seo/v1/settings/internal-linking',
    });

    const payload = response?.data || response || {};
    setSettings((prev) => ({
      ...prev,
      ...payload,
      post_types: Array.isArray(payload.post_types)
        ? payload.post_types
        : (Array.isArray(payload.link_post_types) ? payload.link_post_types : prev.post_types),
      open_internal_new_tab: Boolean(payload.open_internal_new_tab ?? payload.open_in_new_tab ?? prev.open_internal_new_tab),
      add_nofollow: Boolean(payload.add_nofollow ?? prev.add_nofollow),
    }));
  }, []);

  const loadRules = useCallback(async () => {
    const response = await apiFetch({
      path: '/prorank-seo/v1/linking/auto-link-rules',
    });

    setRules(response?.data?.rules || []);
  }, []);

  const loadStats = useCallback(async () => {
    const response = await apiFetch({
      path: '/prorank-seo/v1/linking/auto-link-stats',
    });

    setStats((response?.data || response || {}));
  }, []);

  const bootstrap = useCallback(async () => {
    setLoading(true);
    setNotice(null);

    try {
      await Promise.all([loadSettings(), loadRules(), loadStats()]);
    } catch (error) {
      setNotice({
        variant: 'error',
        message: error?.message || __('Could not load auto-linking data.', TEXT_DOMAIN),
      });
    } finally {
      setLoading(false);
    }
  }, [loadRules, loadSettings, loadStats]);

  useEffect(() => {
    bootstrap();
  }, [bootstrap]);

  useEffect(() => {
    if (!isBatchRunning) {
      return undefined;
    }

    const intervalId = window.setInterval(() => {
      loadStats().catch(() => undefined);
    }, 3000);

    return () => window.clearInterval(intervalId);
  }, [isBatchRunning, loadStats]);

  const handleRuleField = (field, value) => {
    setRuleForm((prev) => ({
      ...prev,
      [field]: value,
    }));
  };

  const createRule = async () => {
    if (!ruleForm.keyword.trim() || !ruleForm.target_url.trim()) {
      setNotice({
        variant: 'warning',
        message: __('Keyword and target URL are required.', TEXT_DOMAIN),
      });
      return;
    }

    setCreatingRule(true);

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/linking/auto-link-rule',
        method: 'POST',
        data: ruleForm,
      });

      if (!response?.success) {
        throw new Error(response?.message || __('Could not create rule.', TEXT_DOMAIN));
      }

      setRuleForm(DEFAULT_RULE);
      await Promise.all([loadRules(), loadStats()]);
      setNotice({
        variant: 'success',
        message: __('Auto-link rule created.', TEXT_DOMAIN),
      });
    } catch (error) {
      setNotice({
        variant: 'error',
        message: error?.message || __('Could not create rule.', TEXT_DOMAIN),
      });
    } finally {
      setCreatingRule(false);
    }
  };

  const toggleRule = async (rule) => {
    try {
      const response = await apiFetch({
        path: `/prorank-seo/v1/linking/auto-link-rule/${rule.id}/toggle`,
        method: 'POST',
        data: { enabled: !rule.enabled },
      });

      if (!response?.success) {
        throw new Error(response?.message || __('Could not update rule.', TEXT_DOMAIN));
      }

      await Promise.all([loadRules(), loadStats()]);
    } catch (error) {
      setNotice({
        variant: 'error',
        message: error?.message || __('Could not update rule.', TEXT_DOMAIN),
      });
    }
  };

  const cancelAutoLinking = async () => {
    setProcessing('cancel');

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/linking/cancel-auto-linking',
        method: 'POST',
      });

      if (!response?.success) {
        throw new Error(response?.message || __('Could not cancel auto-linking.', TEXT_DOMAIN));
      }

      await loadStats();
      setNotice({
        variant: 'info',
        message: response?.message || __('Auto-linking run cancelled.', TEXT_DOMAIN),
      });
    } catch (error) {
      setNotice({
        variant: 'error',
        message: error?.message || __('Could not cancel auto-linking.', TEXT_DOMAIN),
      });
    } finally {
      setProcessing('');
    }
  };

  const resumeAutoLinking = async () => {
    setProcessing('resume');

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/linking/resume-auto-linking',
        method: 'POST',
      });

      if (!response?.success) {
        throw new Error(response?.message || __('Could not resume auto-linking.', TEXT_DOMAIN));
      }

      await loadStats();
      setNotice({
        variant: 'success',
        message: response?.message || __('Auto-linking resumed.', TEXT_DOMAIN),
      });
    } catch (error) {
      setNotice({
        variant: 'error',
        message: error?.message || __('Could not resume auto-linking.', TEXT_DOMAIN),
      });
    } finally {
      setProcessing('');
    }
  };

  const clearAutoLinkingJob = async () => {
    setProcessing('clear');

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/linking/clear-auto-linking-job',
        method: 'POST',
      });

      if (!response?.success) {
        throw new Error(response?.message || __('Could not clear auto-linking job state.', TEXT_DOMAIN));
      }

      await loadStats();
      setNotice({
        variant: 'info',
        message: response?.message || __('Saved auto-linking job state cleared.', TEXT_DOMAIN),
      });
    } catch (error) {
      setNotice({
        variant: 'error',
        message: error?.message || __('Could not clear auto-linking job state.', TEXT_DOMAIN),
      });
    } finally {
      setProcessing('');
    }
  };

  const deleteRule = async (rule) => {
    try {
      const response = await apiFetch({
        path: `/prorank-seo/v1/linking/auto-link-rule/${rule.id}`,
        method: 'DELETE',
      });

      if (!response?.success) {
        throw new Error(response?.message || __('Could not delete rule.', TEXT_DOMAIN));
      }

      await Promise.all([loadRules(), loadStats()]);
      setNotice({
        variant: 'success',
        message: __('Auto-link rule deleted.', TEXT_DOMAIN),
      });
    } catch (error) {
      setNotice({
        variant: 'error',
        message: error?.message || __('Could not delete rule.', TEXT_DOMAIN),
      });
    }
  };

  const runAutoLinking = async (dryRun = false) => {
    if (!settings.auto_linking) {
      setNotice({
        variant: 'warning',
        message: __('Enable Auto Linking in settings before running preview or automation.', TEXT_DOMAIN),
      });
      return;
    }

    if (rules.length === 0) {
      setNotice({
        variant: 'warning',
        message: __('Add at least one auto-link rule before running this tool.', TEXT_DOMAIN),
      });
      return;
    }

    setProcessing(dryRun ? 'preview' : 'run');

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/linking/run-auto-linking',
        method: 'POST',
        data: {
          dry_run: dryRun,
          max_links: settings.max_links_per_post,
          post_types: settings.post_types,
        },
      });

      if (!response?.success) {
        throw new Error(response?.message || __('Auto-linking failed.', TEXT_DOMAIN));
      }

      const payload = response?.data || {};
      if (dryRun) {
        setPreview(payload.preview || []);
        await loadStats();
        await loadRules();
        setNotice({
          variant: 'info',
          message: payload.preview?.length
            ? sprintf(__('Preview ready: %1$d posts would be updated.', TEXT_DOMAIN), payload.preview.length)
            : __('Preview complete. No eligible matches were found.', TEXT_DOMAIN),
        });
      } else {
        setPreview([]);
        await loadStats();
        await loadRules();
        setNotice({
          variant: payload.already_running ? 'info' : 'success',
          message: response?.message || __('Auto-linking started in the background.', TEXT_DOMAIN),
        });
      }
    } catch (error) {
      setNotice({
        variant: 'error',
        message: error?.message || __('Auto-linking failed.', TEXT_DOMAIN),
      });
    } finally {
      setProcessing('');
    }
  };

  if (loading) {
    return (
      <div className="prorank-auto-linking pr:p-6 pr:flex pr:items-center pr:justify-center">
        <Spinner />
      </div>
    );
  }

  return (
    <div className="prorank-auto-linking">
      {notice && (
        <Alert variant={notice.variant} className="pr:mb-4">
          {notice.message}
        </Alert>
      )}

      <div className="prorank-il-hero">
        <div>
          <span className="prorank-il-hero__eyebrow">
            {__('Internal Linking', TEXT_DOMAIN)}
          </span>
          <h2 className="prorank-il-hero__title">
            {__('Auto Linking', TEXT_DOMAIN)}
          </h2>
          <p className="prorank-il-hero__meta">
            {__('Create keyword-to-URL rules, preview changes, and run the rules-based linker.', TEXT_DOMAIN)}
          </p>
        </div>
        <div className="prorank-il-hero__actions">
          <Button
            variant="secondary"
            onClick={() => runAutoLinking(true)}
            disabled={processing !== '' || isBatchRunning}
            className="prorank-il-hero-button"
          >
            {processing === 'preview' ? __('Previewing...', TEXT_DOMAIN) : __('Preview Run', TEXT_DOMAIN)}
          </Button>
          <Button
            variant="primary"
            onClick={() => runAutoLinking(false)}
            isBusy={processing === 'run'}
            disabled={processing !== '' || isBatchRunning}
            className="prorank-il-hero-button is-primary"
          >
            {processing === 'run'
              ? __('Starting...', TEXT_DOMAIN)
              : (isBatchRunning ? __('Background Run Active', TEXT_DOMAIN) : __('Run Auto Linking', TEXT_DOMAIN))}
          </Button>
          {isBatchRunning && (
            <Button
              variant="secondary"
              onClick={cancelAutoLinking}
              isBusy={processing === 'cancel'}
              disabled={processing !== ''}
              className="prorank-il-hero-button"
            >
              {processing === 'cancel' ? __('Cancelling...', TEXT_DOMAIN) : __('Cancel Run', TEXT_DOMAIN)}
            </Button>
          )}
        </div>
      </div>

      <div className="prorank-il-kpi-grid">
        <Card className="prorank-il-kpi-card" padding="none" data-tone="posts">
          <div>
            <div className="prorank-il-kpi-value">{stats.total_rules || 0}</div>
            <div className="prorank-il-kpi-label">{__('Rules', TEXT_DOMAIN)}</div>
          </div>
        </Card>
        <Card className="prorank-il-kpi-card" padding="none" data-tone="active">
          <div>
            <div className="prorank-il-kpi-value">{stats.active_rules || 0}</div>
            <div className="prorank-il-kpi-label">{__('Active Rules', TEXT_DOMAIN)}</div>
          </div>
        </Card>
        <Card className="prorank-il-kpi-card" padding="none" data-tone="internal">
          <div>
            <div className="prorank-il-kpi-value">{stats.links_created || 0}</div>
            <div className="prorank-il-kpi-label">{__('Links Created', TEXT_DOMAIN)}</div>
          </div>
        </Card>
        <Card className="prorank-il-kpi-card" padding="none" data-tone="external">
          <div>
            <div className="prorank-il-kpi-value prorank-il-kpi-value--compact">{stats.last_run ? new Date(stats.last_run).toLocaleDateString() : __('Never', TEXT_DOMAIN)}</div>
            <div className="prorank-il-kpi-label">{__('Last Run', TEXT_DOMAIN)}</div>
          </div>
        </Card>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: '24px' }}>
        <div>
          <Card style={{ marginBottom: '24px' }}>
            <CardHeader>
              <Heading level={3} size={16}>{__('Settings Summary', TEXT_DOMAIN)}</Heading>
            </CardHeader>
            <CardBody>
              <Text size="13" style={{ display: 'block', marginBottom: '12px', color: '#6b7280' }}>
                {__('Auto Linking uses the global Internal Linking settings. Edit the master settings in the Settings tab, then return here to create rules, preview changes, and run automation.', TEXT_DOMAIN)}
              </Text>
              <Text size="13" style={{ display: 'block', marginBottom: '12px', color: '#6b7280' }}>
                {__('Preview checks the latest 100 eligible posts. Full runs process all eligible posts in background batches and continue after you leave this page.', TEXT_DOMAIN)}
              </Text>
              <div style={{ display: 'grid', gap: '10px' }}>
                {settingsSummary.map((item) => (
                  <div key={item.label} style={{ display: 'flex', justifyContent: 'space-between', gap: '16px', borderBottom: '1px solid #e5e7eb', paddingBottom: '8px' }}>
                    <Text size="13" weight="600">{item.label}</Text>
                    <Text size="13" style={{ textAlign: 'right', color: '#475569' }}>{item.value}</Text>
                  </div>
                ))}
              </div>
              <Button variant="secondary" onClick={openSettingsTab} style={{ marginTop: '12px' }}>
                {__('Open Settings', TEXT_DOMAIN)}
              </Button>
            </CardBody>
          </Card>

          {currentJob && (
            <Card style={{ marginBottom: '24px' }}>
              <CardHeader>
                <Heading level={3} size={16}>{__('Background Run Status', TEXT_DOMAIN)}</Heading>
              </CardHeader>
              <CardBody>
                <Text size="13" style={{ display: 'block', marginBottom: '10px', color: '#475569' }}>
                  {currentJob.message || __('No background run is active.', TEXT_DOMAIN)}
                </Text>
                <div style={{ display: 'grid', gap: '10px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: '16px' }}>
                    <Text size="13" weight="600">{__('Status', TEXT_DOMAIN)}</Text>
                    <Text size="13">{String(currentJob.status || '').replace(/^\w/, (value) => value.toUpperCase())}</Text>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: '16px' }}>
                    <Text size="13" weight="600">{__('Progress', TEXT_DOMAIN)}</Text>
                    <Text size="13">{sprintf(__('%1$d%% (%2$d / %3$d posts)', TEXT_DOMAIN), Number(currentJob.percentage || 0), Number(currentJob.processed_posts || 0), Number(currentJob.total_posts || 0))}</Text>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: '16px' }}>
                    <Text size="13" weight="600">{__('Posts Updated', TEXT_DOMAIN)}</Text>
                    <Text size="13">{Number(currentJob.posts_updated || 0)}</Text>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: '16px' }}>
                    <Text size="13" weight="600">{__('Links Created In Run', TEXT_DOMAIN)}</Text>
                    <Text size="13">{Number(currentJob.links_created || 0)}</Text>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: '16px' }}>
                    <Text size="13" weight="600">{__('Errors', TEXT_DOMAIN)}</Text>
                    <Text size="13">{Number(currentJob.error_count || 0)}</Text>
                  </div>
                </div>
                <div style={{ marginTop: '12px', height: '10px', background: '#e5e7eb', borderRadius: '999px', overflow: 'hidden' }}>
                  <div
                    style={{
                      width: `${Math.max(0, Math.min(100, Number(currentJob.percentage || 0)))}%`,
                      height: '100%',
                      background: isBatchRunning ? '#2563eb' : '#16a34a',
                      transition: 'width 0.2s ease',
                    }}
                  />
                </div>
                {Array.isArray(currentJob.errors) && currentJob.errors.length > 0 && (
                  <ul style={{ marginTop: '12px', paddingLeft: '18px' }}>
                    {currentJob.errors.map((error, index) => (
                      <li key={`${currentJob.job_id}-${index}`} style={{ marginBottom: '6px' }}>
                        <Text size="12">{error}</Text>
                      </li>
                    ))}
                  </ul>
                )}
                <div style={{ display: 'flex', gap: '8px', marginTop: '12px', flexWrap: 'wrap' }}>
                  {isBatchRunning && (
                    <Button
                      variant="secondary"
                      onClick={cancelAutoLinking}
                      isBusy={processing === 'cancel'}
                      disabled={processing !== ''}
                    >
                      {processing === 'cancel' ? __('Cancelling...', TEXT_DOMAIN) : __('Cancel Run', TEXT_DOMAIN)}
                    </Button>
                  )}
                  {currentJob.status === 'cancelled' && (
                    <Button
                      variant="secondary"
                      onClick={resumeAutoLinking}
                      isBusy={processing === 'resume'}
                      disabled={processing !== ''}
                    >
                      {processing === 'resume' ? __('Resuming...', TEXT_DOMAIN) : __('Resume Run', TEXT_DOMAIN)}
                    </Button>
                  )}
                  {(currentJob.status === 'cancelled' || currentJob.status === 'completed') && (
                    <Button
                      variant="tertiary"
                      onClick={clearAutoLinkingJob}
                      isBusy={processing === 'clear'}
                      disabled={processing !== ''}
                    >
                      {processing === 'clear' ? __('Clearing...', TEXT_DOMAIN) : __('Clear Job', TEXT_DOMAIN)}
                    </Button>
                  )}
                </div>
              </CardBody>
            </Card>
          )}

          <Card>
            <CardHeader>
              <Heading level={3} size={16}>{__('Create Rule', TEXT_DOMAIN)}</Heading>
            </CardHeader>
            <CardBody>
              <TextControl
                label={__('Keyword or Phrase', TEXT_DOMAIN)}
                value={ruleForm.keyword}
                onChange={(value) => handleRuleField('keyword', value)}
              />
              <TextControl
                label={__('Target URL', TEXT_DOMAIN)}
                value={ruleForm.target_url}
                onChange={(value) => handleRuleField('target_url', value)}
              />
              <RangeControl
                label={__('Priority', TEXT_DOMAIN)}
                value={Number(ruleForm.priority || 5)}
                onChange={(value) => handleRuleField('priority', value || 0)}
                min={0}
                max={10}
              />
              <RangeControl
                label={__('Max Links Per Post For This Rule', TEXT_DOMAIN)}
                value={Number(ruleForm.max_links_per_post || 1)}
                onChange={(value) => handleRuleField('max_links_per_post', value || 1)}
                min={1}
                max={10}
              />
              <RangeControl
                label={__('Max Total Links', TEXT_DOMAIN)}
                value={Number(ruleForm.max_total_links || 10)}
                onChange={(value) => handleRuleField('max_total_links', value || 0)}
                min={0}
                max={100}
              />
              <TextControl
                label={__('Exclude Post IDs', TEXT_DOMAIN)}
                help={__('Comma-separated post IDs to exclude from this rule.', TEXT_DOMAIN)}
                value={ruleForm.exclude_posts}
                onChange={(value) => handleRuleField('exclude_posts', value)}
              />
              <Toggle
                label={__('Whole Word Only', TEXT_DOMAIN)}
                checked={!!ruleForm.whole_word}
                onChange={(value) => handleRuleField('whole_word', value)}
              />
              <Toggle
                label={__('Case Sensitive', TEXT_DOMAIN)}
                checked={!!ruleForm.case_sensitive}
                onChange={(value) => handleRuleField('case_sensitive', value)}
              />
              <Toggle
                label={__('Enabled', TEXT_DOMAIN)}
                checked={!!ruleForm.enabled}
                onChange={(value) => handleRuleField('enabled', value)}
              />
              <Button variant="primary" onClick={createRule} isBusy={creatingRule} disabled={creatingRule} style={{ marginTop: '12px' }}>
                {creatingRule ? __('Creating...', TEXT_DOMAIN) : __('Add Rule', TEXT_DOMAIN)}
              </Button>
            </CardBody>
          </Card>
        </div>

        <div>
          <Card style={{ marginBottom: '24px' }}>
            <CardHeader>
              <Heading level={3} size={16}>{__('Existing Rules', TEXT_DOMAIN)}</Heading>
            </CardHeader>
            <CardBody>
              {rules.length === 0 ? (
                <Alert variant="info">{__('No auto-link rules created yet.', TEXT_DOMAIN)}</Alert>
              ) : (
                <div style={{ display: 'grid', gap: '12px' }}>
                  {rules.map((rule) => (
                    <Card key={rule.id} style={{ border: '1px solid #e5e7eb' }}>
                      <CardBody style={{ padding: '14px' }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', gap: '12px' }}>
                          <div>
                            <Heading level={4} size={14}>{rule.keyword}</Heading>
                            <Text size="12" style={{ display: 'block', marginTop: '4px', wordBreak: 'break-word' }}>{rule.target_url}</Text>
                            <Text size="11" style={{ display: 'block', marginTop: '6px', color: '#6b7280' }}>
                              {sprintf(__('Priority %1$d · %2$d link(s) created', TEXT_DOMAIN), Number(rule.priority || 0), Number(rule.links_count || 0))}
                            </Text>
                          </div>
                          <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', alignItems: 'flex-end' }}>
                            <Button variant="secondary" onClick={() => toggleRule(rule)}>
                              {rule.enabled ? __('Disable', TEXT_DOMAIN) : __('Enable', TEXT_DOMAIN)}
                            </Button>
                            <Button variant="tertiary" isDestructive onClick={() => deleteRule(rule)}>
                              {__('Delete', TEXT_DOMAIN)}
                            </Button>
                          </div>
                        </div>
                      </CardBody>
                    </Card>
                  ))}
                </div>
              )}
            </CardBody>
          </Card>

          <Card>
            <CardHeader>
              <Heading level={3} size={16}>{__('Preview Results', TEXT_DOMAIN)}</Heading>
            </CardHeader>
            <CardBody>
              {preview.length === 0 ? (
                <Text>{__('Run a preview to inspect which of the latest eligible posts would receive links.', TEXT_DOMAIN)}</Text>
              ) : (
                <div style={{ display: 'grid', gap: '12px' }}>
                  {preview.map((item) => (
                    <Card key={`${item.post_id}-${item.post_title}`} style={{ border: '1px solid #e5e7eb' }}>
                      <CardBody style={{ padding: '14px' }}>
                        <Heading level={4} size={14}>{item.post_title}</Heading>
                        <Text size="12" style={{ display: 'block', marginTop: '4px' }}>
                          {sprintf(__('Would add %1$d link(s)', TEXT_DOMAIN), Number(item.total_links || item.links_created || 0))}
                        </Text>
                        {Array.isArray(item.changes) && item.changes.length > 0 && (
                          <ul style={{ marginTop: '10px', paddingLeft: '18px' }}>
                            {item.changes.map((change, index) => (
                              <li key={`${item.post_id}-${index}`} style={{ marginBottom: '6px' }}>
                                <Text size="12">
                                  {sprintf(__('%1$s → %2$s (%3$d)', TEXT_DOMAIN), change.keyword, change.target_url, Number(change.count || 0))}
                                </Text>
                              </li>
                            ))}
                          </ul>
                        )}
                      </CardBody>
                    </Card>
                  ))}
                </div>
              )}
            </CardBody>
          </Card>
        </div>
      </div>
    </div>
  );
};

export default AutoLinkingTool;
