/**
 * Broken Links Report
 * 
 * Comprehensive broken links checker with status codes and management
 */

import { useState, useEffect } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import {
  Icon,
  Spinner,
  TextControl,
  SelectControl,
  CheckboxControl,
  __experimentalHStack as HStack,
  __experimentalText as Text,
  __experimentalHeading as Heading
} from '@wordpress/components';
import { check, download, external, update } from '@wordpress/icons';
import { Card, CardBody, Button, Input, Select, Alert, Modal } from '../../components/ui';
import { CheckIcon, ExclamationTriangleIcon, ArrowDownTrayIcon, ArrowPathIcon, ArrowTopRightOnSquareIcon } from '@heroicons/react/24/outline';
import apiFetch from '@wordpress/api-fetch';

const BrokenLinksReport = () => {
  const [loading, setLoading] = useState(true);
  const [scanning, setScanning] = useState(false);
  const [scanProgress, setScanProgress] = useState(0);
  const [scanStatus, setScanStatus] = useState('');
  const [brokenLinks, setBrokenLinks] = useState([]);
  const [filteredLinks, setFilteredLinks] = useState([]);
  const [selectedLinks, setSelectedLinks] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [postType, setPostType] = useState('all');
  const [category, setCategory] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [categories, setCategories] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(20);
  const [showIgnoreModal, setShowIgnoreModal] = useState(false);
  const [linkToIgnore, setLinkToIgnore] = useState(null);
  const [stats, setStats] = useState({
    total_broken: 0,
    status_404: 0,
    status_403: 0,
    status_400: 0,
    status_500: 0,
    connection_failed: 0,
    invalid_links: 0,
    ignored: 0,
    high_confidence: 0,
    last_scan: null,
  });

  // Status code colors
  const statusColors = {
    '400': '#f59e0b',
    '403': '#ef4444',
    '404': '#dc2626',
    '500': '#991b1b',
    '0': '#2563eb',
    '800': '#7c3aed',
    '925': '#8b5cf6',
    'ignored': '#6b7280',
    'timeout': '#3b82f6',
  };

  // Status code descriptions
  const statusDescriptions = {
    '400': __('Bad Request - The server cannot process the request', 'prorank-seo'),
    '403': __('Forbidden - Access denied to this resource', 'prorank-seo'),
    '404': __('Not Found - The page does not exist', 'prorank-seo'),
    '500': __('Server Error - Internal server error occurred', 'prorank-seo'),
    '0': __('Connection failed - The URL could not be reached during the scan', 'prorank-seo'),
    '800': __('Placeholder link - Empty/hash/javascript placeholder found in content', 'prorank-seo'),
    '925': __('Malformed URL - Template or malformed URL found in content', 'prorank-seo'),
    'timeout': __('Timeout - The request took too long to respond', 'prorank-seo'),
  };

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

  useEffect(() => {
    filterLinks();
  }, [brokenLinks, searchTerm, postType, category, statusFilter]);

  const loadBrokenLinks = async () => {
    setLoading(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/linking/broken-links',
      });
      
      if (response && response.links) {
        setBrokenLinks(response.links);
        setStats(response.stats || stats);
      }
    } catch (error) {
      // Error loading broken links
    } finally {
      setLoading(false);
    }
  };

  const loadCategories = async () => {
    try {
      const response = await apiFetch({
        path: '/wp/v2/categories?per_page=100',
      });
      setCategories(response || []);
    } catch (error) {
      // Error loading categories
    }
  };

  const scanForBrokenLinks = async () => {
    setScanning(true);
    setScanProgress(0);
    setScanStatus(__('Starting broken links scan...', 'prorank-seo'));
    
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/linking/scan-broken-links',
        method: 'POST',
        data: {
          batch_size: 10, // Process 10 posts at a time
        }
      });
      
      if (response && response.scan_id) {
        // Store scan info
        setScanStatus(__('Processing site posts...', 'prorank-seo'));
        pollScanProgress(response.scan_id);
      }
    } catch (error) {
      setScanning(false);
      setScanStatus(__('Scan failed. Please try again.', 'prorank-seo'));
    }
  };

  const pollScanProgress = async (scanId) => {
    let pollDelay = 1000; // Start with 1 second
    let consecutiveErrors = 0;
    const maxErrors = 5;
    const maxDelay = 10000; // Max 10 seconds between polls

    const poll = async () => {
      try {
        const response = await apiFetch({
          path: `/prorank-seo/v1/linking/scan-progress/${scanId}`,
        });

        // Reset error count on success
        consecutiveErrors = 0;
        pollDelay = 1000; // Reset delay on success

        if (response) {
          setScanProgress(response.progress || 0);

          // Update status message with current/total
          if (response.current && response.total) {
            setScanStatus(
              sprintf(
                __('%d%%, %d/%d completed', 'prorank-seo'),
                Math.round(response.progress),
                response.current,
                response.total
              )
            );
          } else {
            setScanStatus(response.status || __('Processing...', 'prorank-seo'));
          }

          // Update broken links count in real-time
          if (response.broken_count !== undefined) {
            setStats(prev => ({
              ...prev,
              total_broken: response.broken_count
            }));
          }

          if (response.completed) {
            setScanning(false);
            setScanStatus(__('Scan completed!', 'prorank-seo'));
            // Reload the broken links list
            setTimeout(() => loadBrokenLinks(), 1000);
            return; // Stop polling
          }
        }

        // Continue polling
        setTimeout(poll, pollDelay);
      } catch (error) {
        consecutiveErrors++;

        if (consecutiveErrors >= maxErrors) {
          setScanning(false);
          setScanStatus(__('Scan interrupted after multiple failures.', 'prorank-seo'));
          return; // Stop polling
        }

        // Exponential backoff: double delay on each error, up to max
        pollDelay = Math.min(pollDelay * 2, maxDelay);
        setScanStatus(sprintf(__('Retrying... (attempt %d/%d)', 'prorank-seo'), consecutiveErrors, maxErrors));

        // Continue polling with increased delay
        setTimeout(poll, pollDelay);
      }
    };

    // Start polling
    poll();
  };

  const filterLinks = () => {
    let filtered = [...brokenLinks];

    // Search filter
    if (searchTerm) {
      filtered = filtered.filter(link => 
        link.url.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (link.anchor_text || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
        (link.post_title || '').toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    // Post type filter
    if (postType !== 'all') {
      filtered = filtered.filter(link => link.post_type === postType);
    }

    // Category filter
    if (category !== 'all') {
      filtered = filtered.filter(link => 
        link.categories && link.categories.includes(parseInt(category))
      );
    }

    // Status code filter
    if (statusFilter !== 'all') {
      if (statusFilter === 'high_confidence') {
        filtered = filtered.filter(link => link.confidence === 'high');
      } else {
        filtered = filtered.filter(link => 
          link.status_code.toString() === statusFilter
        );
      }
    }

    setFilteredLinks(filtered);
    setCurrentPage(1);
  };

  const handleIgnoreLink = async (linkId) => {
    try {
      await apiFetch({
        path: `/prorank-seo/v1/linking/ignore-link/${linkId}`,
        method: 'POST',
      });
      await loadBrokenLinks();
    } catch (error) {
      // Error ignoring link
    }
  };

  const handleDeleteSelected = async () => {
    if (selectedLinks.length === 0) return;
    
    if (!confirm(__('Are you sure you want to delete these broken links from the report?', 'prorank-seo'))) {
      return;
    }
    
    try {
      await apiFetch({
        path: '/prorank-seo/v1/linking/delete-broken-links',
        method: 'DELETE',
        data: { link_ids: selectedLinks },
      });

      await loadBrokenLinks();
      setSelectedLinks([]);
    } catch (error) {
      // Error deleting links
    }
  };

  const handleDeleteHighConfidence = async () => {
    const highConfidenceLinks = brokenLinks
      .filter(link => link.confidence === 'high')
      .map(link => link.id);
    
    if (highConfidenceLinks.length === 0) return;
    
    if (!confirm(`Are you sure you want to delete ${highConfidenceLinks.length} high-confidence broken links?`)) {
      return;
    }
    
    try {
      await apiFetch({
        path: '/prorank-seo/v1/linking/delete-broken-links',
        method: 'DELETE',
        data: { link_ids: highConfidenceLinks },
      });

      await loadBrokenLinks();
    } catch (error) {
      // Error deleting high-confidence links
    }
  };

  const exportToCSV = () => {
    const csvContent = [
      ['Post Title', 'Post URL', 'Broken URL', 'Anchor Text', 'Status Code', 'Context'],
      ...filteredLinks.map(link => [
        link.post_title,
        link.post_url,
        link.url,
        link.anchor_text,
        link.status_code,
        link.context,
      ])
    ].map(row => row.map(cell => `"${cell || ''}"`).join(',')).join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'broken-links-report.csv';
    a.click();
  };

  const toggleLinkSelection = (linkId) => {
    setSelectedLinks(prev => 
      prev.includes(linkId) 
        ? prev.filter(id => id !== linkId)
        : [...prev, linkId]
    );
  };

  const selectAllLinks = () => {
    if (selectedLinks.length === paginatedLinks.length) {
      setSelectedLinks([]);
    } else {
      setSelectedLinks(paginatedLinks.map(link => link.id));
    }
  };

  // Pagination
  const totalPages = Math.ceil(filteredLinks.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const paginatedLinks = filteredLinks.slice(startIndex, startIndex + itemsPerPage);

  const getStatusBadge = (statusCode) => {
    const color = statusColors[statusCode] || '#6b7280';
    const label = statusCode === '404' || statusCode === 404 ? 'Not Found'
      : statusCode === '403' || statusCode === 403 ? 'Forbidden'
      : statusCode === '400' || statusCode === 400 ? 'Bad Request'
      : statusCode === '500' || statusCode === 500 ? 'Server Error'
      : statusCode === '0' || statusCode === 0 ? 'Connection Failed'
      : statusCode === '800' || statusCode === 800 ? 'Placeholder Link'
      : statusCode === '925' || statusCode === 925 ? 'Malformed URL'
      : statusCode === 'ignored' ? 'Ignored'
      : '';
    return (
      <span style={{
        padding: '4px 8px',
        background: color + '20',
        color: color,
        borderRadius: '4px',
        fontSize: '12px',
        fontWeight: '600',
        border: `1px solid ${color}40`,
      }}>
        {statusCode} {label}
      </span>
    );
  };

  if (loading) {
    return (
      <Card>
        <CardBody>
          <HStack alignment="center" justify="center" style={{ minHeight: '400px' }}>
            <Spinner />
            <Text>{__('Loading broken links...', 'prorank-seo')}</Text>
          </HStack>
        </CardBody>
      </Card>
    );
  }

  return (
    <div className="prorank-broken-links-report">
      {/* Header */}
      <div className="prorank-il-hero">
        <div>
          <span className="prorank-il-hero__eyebrow">
            {__('Internal Linking', 'prorank-seo')}
          </span>
          <h2 className="prorank-il-hero__title">
            {__('Broken Links Report', 'prorank-seo')}
          </h2>
          <p className="prorank-il-hero__meta">
            {__('Track broken destinations, validate status codes, and clean up high-confidence failures before they become crawl debt.', 'prorank-seo')}
            {' '}
            {stats.last_scan
              ? `${__('Last scan:', 'prorank-seo')} ${new Date(stats.last_scan).toLocaleString()}`
              : __('No completed scan recorded yet.', 'prorank-seo')}
          </p>
        </div>
        <div className="prorank-il-hero__actions">
          <Button
            variant="secondary"
            onClick={exportToCSV}
            className="prorank-il-hero-button"
          >
            <Icon icon={download} style={{ marginRight: '4px' }} />
            {__('Export to CSV', 'prorank-seo')}
          </Button>
          <Button
            variant="primary"
            onClick={scanForBrokenLinks}
            disabled={scanning}
            className="prorank-il-hero-button is-primary"
          >
            <Icon icon={update} style={{ marginRight: '4px' }} />
            {scanning ? __('Scanning...', 'prorank-seo') : __('Scan for Broken Links', 'prorank-seo')}
          </Button>
        </div>
      </div>

      {/* Scan Progress */}
      {scanning && (
        <div className="prorank-il-progress-card">
          <div>
            <div style={{ marginBottom: '16px' }}>
              <h3 className="prorank-il-progress-title">
                {__('Broken Links Report', 'prorank-seo')}
              </h3>
              <p className="prorank-il-progress-copy">
                {__('Processing Site Posts...', 'prorank-seo')}
              </p>
              <p className="prorank-il-progress-note">
                {__("Please don't close this tab otherwise the process will stop and have to be continued later.", 'prorank-seo')}
              </p>
            </div>
            
            <div style={{ marginBottom: '12px' }}>
              <div style={{ 
                display: 'flex', 
                justifyContent: 'space-between',
                marginBottom: '8px'
              }}>
                <span style={{ fontSize: '14px', fontWeight: '500', color: '#e2e8f0' }}>
                  {scanStatus}
                </span>
                <span style={{ fontSize: '16px', fontWeight: '600', color: '#f8fafc' }}>
                  {scanProgress}%
                </span>
              </div>
              <div className="prorank-il-progress-track">
                <div className="prorank-il-progress-fill" style={{ width: `${scanProgress}%` }} />
              </div>
            </div>
            
            <HStack justify="space-between" align="center">
              <HStack spacing={2}>
                <Spinner style={{ color: '#fff' }} />
                <Text className="prorank-il-progress-meta" style={{ color: '#e2e8f0' }}>
                  {__('Scanning links in your content...', 'prorank-seo')}
                </Text>
              </HStack>
              <Button
                variant="secondary"
                size="small"
                onClick={() => {
                  setScanning(false);
                  setScanStatus(__('Scan stopped', 'prorank-seo'));
                }}
                className="prorank-il-hero-button"
              >
                {__('Stop Scan', 'prorank-seo')}
              </Button>
            </HStack>
          </div>
        </div>
      )}

      {/* Stats Summary */}
      <div className="prorank-il-kpi-grid prorank-il-kpi-grid--compact">
        <Card className="prorank-il-kpi-card" padding="none" data-tone="total">
          <div>
            <div className="prorank-il-kpi-value">
              {stats.total_broken}
            </div>
            <div className="prorank-il-kpi-label">
              {__('Total Broken', 'prorank-seo')}
            </div>
          </div>
        </Card>
        <Card className="prorank-il-kpi-card" padding="none" data-tone="404" onClick={() => setStatusFilter('404')} style={{ cursor: 'pointer' }}>
          <div>
            <div className="prorank-il-kpi-value" style={{ color: statusColors['404'] }}>
              {stats.status_404}
            </div>
            <div className="prorank-il-kpi-label">
              {__('404 Not Found', 'prorank-seo')}
            </div>
          </div>
        </Card>
        <Card className="prorank-il-kpi-card" padding="none" data-tone="403" onClick={() => setStatusFilter('403')} style={{ cursor: 'pointer' }}>
          <div>
            <div className="prorank-il-kpi-value" style={{ color: statusColors['403'] }}>
              {stats.status_403}
            </div>
            <div className="prorank-il-kpi-label">
              {__('403 Forbidden', 'prorank-seo')}
            </div>
          </div>
        </Card>
        <Card className="prorank-il-kpi-card" padding="none" data-tone="400" onClick={() => setStatusFilter('400')} style={{ cursor: 'pointer' }}>
          <div>
            <div className="prorank-il-kpi-value" style={{ color: statusColors['400'] }}>
              {stats.status_400}
            </div>
            <div className="prorank-il-kpi-label">
              {__('400 Bad Request', 'prorank-seo')}
            </div>
          </div>
        </Card>
        <Card className="prorank-il-kpi-card" padding="none" data-tone="500" onClick={() => setStatusFilter('500')} style={{ cursor: 'pointer' }}>
          <div>
            <div className="prorank-il-kpi-value" style={{ color: statusColors['500'] }}>
              {stats.status_500}
            </div>
            <div className="prorank-il-kpi-label">
              {__('500 Server Error', 'prorank-seo')}
            </div>
          </div>
        </Card>
        <Card className="prorank-il-kpi-card" padding="none" data-tone="0" onClick={() => setStatusFilter('0')} style={{ cursor: 'pointer' }}>
          <div>
            <div className="prorank-il-kpi-value" style={{ color: statusColors['0'] }}>
              {stats.connection_failed}
            </div>
            <div className="prorank-il-kpi-label">
              {__('Connection Failed', 'prorank-seo')}
            </div>
          </div>
        </Card>
        <Card className="prorank-il-kpi-card" padding="none" data-tone="800" onClick={() => setStatusFilter('800')} style={{ cursor: 'pointer' }}>
          <div>
            <div className="prorank-il-kpi-value" style={{ color: statusColors['800'] }}>
              {stats.invalid_links}
            </div>
            <div className="prorank-il-kpi-label">
              {__('Invalid / Placeholder', 'prorank-seo')}
            </div>
          </div>
        </Card>
        <Card className="prorank-il-kpi-card" padding="none" data-tone="ignored">
          <div>
            <div className="prorank-il-kpi-value" style={{ color: statusColors.ignored }}>
              {stats.ignored}
            </div>
            <div className="prorank-il-kpi-label">
              {__('Ignored', 'prorank-seo')}
            </div>
          </div>
        </Card>
      </div>

      {/* Bulk Actions & Filters */}
      <Card className="prorank-il-panel prorank-il-filters-card">
        <CardBody>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', gap: '16px' }}>
            <div style={{ display: 'flex', gap: '12px', alignItems: 'end' }}>
              <Button
                variant="secondary"
                onClick={handleDeleteSelected}
                disabled={selectedLinks.length === 0}
                style={{ 
                  background: selectedLinks.length > 0 ? '#fee2e2' : '#f3f4f6',
                  color: selectedLinks.length > 0 ? '#dc2626' : '#6b7280',
                  border: 'none'
                }}
              >
                {__('Delete Selected', 'prorank-seo')} ({selectedLinks.length})
              </Button>
              <Button
                variant="secondary"
                onClick={handleDeleteHighConfidence}
                style={{ 
                  background: '#fef3c7',
                  color: '#d97706',
                  border: 'none'
                }}
              >
                {__('Delete', 'prorank-seo')} {stats.high_confidence} {__('High-Confidence Broken Links', 'prorank-seo')}
              </Button>
            </div>
            
            <div style={{ display: 'flex', gap: '12px', alignItems: 'end' }}>
              <TextControl
                label={__('Search', 'prorank-seo')}
                value={searchTerm}
                onChange={setSearchTerm}
                placeholder={__('URL or anchor text', 'prorank-seo')}
                style={{ minWidth: '200px' }}
                __nextHasNoMarginBottom
                __next40pxDefaultSize
              />
              <SelectControl
                label={__('Status Code', 'prorank-seo')}
                value={statusFilter}
                onChange={setStatusFilter}
                options={[
                  { label: __('All Status Codes', 'prorank-seo'), value: 'all' },
                  { label: __('404 Not Found', 'prorank-seo'), value: '404' },
                  { label: __('403 Forbidden', 'prorank-seo'), value: '403' },
                  { label: __('400 Bad Request', 'prorank-seo'), value: '400' },
                  { label: __('500 Server Error', 'prorank-seo'), value: '500' },
                  { label: __('Connection Failed', 'prorank-seo'), value: '0' },
                  { label: __('Placeholder Link', 'prorank-seo'), value: '800' },
                  { label: __('Malformed URL', 'prorank-seo'), value: '925' },
                  { label: __('High Confidence Only', 'prorank-seo'), value: 'high_confidence' },
                  { label: __('Ignored', 'prorank-seo'), value: 'ignored' },
                ]}
                __nextHasNoMarginBottom
                __next40pxDefaultSize
              />
              <SelectControl
                label={__('Post Type', 'prorank-seo')}
                value={postType}
                onChange={setPostType}
                options={[
                  { label: __('All types', 'prorank-seo'), value: 'all' },
                  { label: __('Posts', 'prorank-seo'), value: 'post' },
                  { label: __('Pages', 'prorank-seo'), value: 'page' },
                ]}
                __nextHasNoMarginBottom
                __next40pxDefaultSize
              />
              <SelectControl
                label={__('Category', 'prorank-seo')}
                value={category}
                onChange={setCategory}
                options={[
                  { label: __('All categories', 'prorank-seo'), value: 'all' },
                  ...categories.map(cat => ({ label: cat.name, value: cat.id.toString() }))
                ]}
                __nextHasNoMarginBottom
                __next40pxDefaultSize
              />
            </div>
          </div>
        </CardBody>
      </Card>

      {/* Results Table */}
      <Card className="prorank-il-panel prorank-il-table-card">
        <CardBody style={{ padding: 0 }}>
          {filteredLinks.length === 0 ? (
            <div style={{ padding: '60px', textAlign: 'center' }}>
              <Icon icon={check} size={48} style={{ color: '#10b981', marginBottom: '16px' }} />
              <Heading level={3} style={{ marginBottom: '8px' }}>
                {__('No Broken Links Found', 'prorank-seo')}
              </Heading>
              <Text style={{ color: '#6b7280' }}>
                {searchTerm || statusFilter !== 'all' 
                  ? __('No broken links match your filters', 'prorank-seo')
                  : __('Great! Your site has no broken links.', 'prorank-seo')}
              </Text>
            </div>
          ) : (
            <>
              <div className="prorank-il-table-toolbar">
                <Text weight="600" className="prorank-il-table-toolbar__label">{filteredLinks.length} {__('broken links found', 'prorank-seo')}</Text>
              </div>
              
              <div style={{ overflowX: 'auto' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                  <thead>
                    <tr style={{ background: '#f9fafb', borderBottom: '2px solid #e5e7eb' }}>
                      <th style={{ padding: '12px', width: '40px' }}>
                        <CheckboxControl
                          checked={selectedLinks.length === paginatedLinks.length && paginatedLinks.length > 0}
                          onChange={selectAllLinks}
                        />
                      </th>
                      <th style={{ padding: '12px', textAlign: 'left', minWidth: '200px' }}>
                        {__('Post', 'prorank-seo')}
                      </th>
                      <th style={{ padding: '12px', textAlign: 'left', minWidth: '250px' }}>
                        {__('Broken URL', 'prorank-seo')}
                      </th>
                      <th style={{ padding: '12px', textAlign: 'left' }}>
                        {__('Anchor', 'prorank-seo')}
                      </th>
                      <th style={{ padding: '12px', textAlign: 'left', minWidth: '300px' }}>
                        {__('Context', 'prorank-seo')}
                      </th>
                      <th style={{ padding: '12px', textAlign: 'center', width: '120px' }}>
                        {__('Status', 'prorank-seo')}
                      </th>
                      <th style={{ padding: '12px', textAlign: 'center', width: '100px' }}>
                        {__('Actions', 'prorank-seo')}
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {paginatedLinks.map((link, index) => (
                      <tr key={link.id} style={{ 
                        borderBottom: '1px solid #e5e7eb',
                        background: link.status === 'ignored' ? '#f9fafb' : (index % 2 === 0 ? '#fff' : '#fafafa')
                      }}>
                        <td style={{ padding: '12px' }}>
                          <CheckboxControl
                            checked={selectedLinks.includes(link.id)}
                            onChange={() => toggleLinkSelection(link.id)}
                          />
                        </td>
                        <td style={{ padding: '12px' }}>
                          <div>
                            <a 
                              href={link.post_url}
                              target="_blank"
                              rel="noopener noreferrer"
                              style={{ 
                                color: '#2563eb',
                                textDecoration: 'none',
                                fontWeight: '500'
                              }}
                            >
                              {link.post_title}
                            </a>
                            <div style={{ fontSize: '12px', color: '#6b7280', marginTop: '2px' }}>
                              <a 
                                href={link.post_url}
                                target="_blank"
                                rel="noopener noreferrer"
                                style={{ color: '#6b7280' }}
                              >
                                {__('View', 'prorank-seo')}
                              </a>
                              {' | '}
                              <a 
                                href={`/wp-admin/post.php?post=${link.post_id}&action=edit`}
                                style={{ color: '#6b7280' }}
                              >
                                {__('Edit', 'prorank-seo')}
                              </a>
                            </div>
                          </div>
                        </td>
                        <td style={{ padding: '12px' }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                            <a 
                              href={link.url}
                              target="_blank"
                              rel="noopener noreferrer"
                              style={{ 
                                color: '#dc2626',
                                textDecoration: 'none',
                                wordBreak: 'break-all',
                                fontSize: '13px'
                              }}
                            >
                              {link.url}
                            </a>
                            <Icon icon={external} size={14} style={{ color: '#9ca3af', flexShrink: 0 }} />
                          </div>
                          <div style={{ marginTop: '4px' }}>
                            <Button
                              variant="link"
                              onClick={() => handleIgnoreLink(link.id)}
                              style={{ 
                                fontSize: '11px',
                                color: '#6b7280',
                                padding: 0,
                                minHeight: 'auto'
                              }}
                            >
                              {__('Ignore', 'prorank-seo')}
                            </Button>
                            {' | '}
                            <a
                              href={`/wp-admin/post.php?post=${link.post_id}&action=edit`}
                              style={{
                                fontSize: '11px',
                                color: '#6b7280',
                                textDecoration: 'none'
                              }}
                            >
                              {__('Edit', 'prorank-seo')}
                            </a>
                          </div>
                        </td>
                        <td style={{ padding: '12px' }}>
                          <Text size="small" style={{ fontWeight: '500' }}>
                            {link.anchor_text || __('(no anchor text)', 'prorank-seo')}
                          </Text>
                        </td>
                        <td style={{ padding: '12px' }}>
                          <Text size="small" style={{ 
                            color: '#6b7280',
                            fontStyle: 'italic',
                            display: '-webkit-box',
                            WebkitLineClamp: 2,
                            WebkitBoxOrient: 'vertical',
                            overflow: 'hidden'
                          }}>
                            ...{link.context}...
                          </Text>
                        </td>
                        <td style={{ padding: '12px', textAlign: 'center' }}>
                          <span title={statusDescriptions[link.status_code?.toString?.() || String(link.status_code)] || ''}>
                            {getStatusBadge(link.status_code)}
                          </span>
                        </td>
                        <td style={{ padding: '12px', textAlign: 'center' }}>
                          <Button
                            variant="secondary"
                            onClick={() => window.open(link.url, '_blank')}
                            disabled={link.status_code === 800 || link.status_code === 925 || link.url === '#'}
                            style={{ 
                              padding: '4px 8px',
                              fontSize: '12px',
                              minHeight: 'auto'
                            }}
                          >
                            {__('Test', 'prorank-seo')}
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Pagination */}
              {totalPages > 1 && (
                <div style={{ 
                  padding: '16px', 
                  borderTop: '1px solid #e5e7eb',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between'
                }}>
                  <Text size="small" style={{ color: '#6b7280' }}>
                    {__('Showing', 'prorank-seo')} {startIndex + 1}-{Math.min(startIndex + itemsPerPage, filteredLinks.length)} {__('of', 'prorank-seo')} {filteredLinks.length} {__('items', 'prorank-seo')}
                  </Text>
                  <div style={{ display: 'flex', gap: '8px' }}>
                    <Button
                      variant="secondary"
                      onClick={() => setCurrentPage(1)}
                      disabled={currentPage === 1}
                      style={{ minWidth: '32px', padding: '4px 8px' }}
                    >
                      «
                    </Button>
                    <Button
                      variant="secondary"
                      onClick={() => setCurrentPage(currentPage - 1)}
                      disabled={currentPage === 1}
                      style={{ minWidth: '32px', padding: '4px 8px' }}
                    >
                      ‹
                    </Button>
                    <Text style={{ padding: '4px 12px', background: '#f3f4f6', borderRadius: '4px' }}>
                      {__('Page', 'prorank-seo')} {currentPage} {__('of', 'prorank-seo')} {totalPages}
                    </Text>
                    <Button
                      variant="secondary"
                      onClick={() => setCurrentPage(currentPage + 1)}
                      disabled={currentPage === totalPages}
                      style={{ minWidth: '32px', padding: '4px 8px' }}
                    >
                      ›
                    </Button>
                    <Button
                      variant="secondary"
                      onClick={() => setCurrentPage(totalPages)}
                      disabled={currentPage === totalPages}
                      style={{ minWidth: '32px', padding: '4px 8px' }}
                    >
                      »
                    </Button>
                  </div>
                </div>
              )}
            </>
          )}
        </CardBody>
      </Card>
    </div>
  );
};

export default BrokenLinksReport;
