/**
 * Redirect Settings Full Page Component
 * Integrates the full redirect manager functionality within a tab
 *
 * @package
 * @since   0.1.0
 */

import { useState, useEffect, useCallback } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { PlusIcon, PencilIcon, TrashIcon, LockClosedIcon } from '@heroicons/react/24/outline';
import { useLicense } from '../../../contexts/LicenseContext';
import { useNotification } from '../../../contexts/NotificationContext';
import RedirectEditPanel from '../../../components/redirects/RedirectEditPanel';
import NotFoundMonitor from '../../../components/redirects/NotFoundMonitor';
import {
  Button,
  Input,
  Select,
  Checkbox,
  Toggle,
  Card,
  Alert,
  Spinner,
} from '../../../components/ui';

const REDIRECT_MONITOR_TABS = new Set(['redirects', '404-monitor', 'settings']);

const parseRedirectMonitorDeepLink = () => {
  const params = new URLSearchParams(window.location.search);
  const requestedTab = params.get('redirect_tab');
  const tab = REDIRECT_MONITOR_TABS.has(requestedTab) ? requestedTab : 'redirects';
  const status = params.get('redirect_status') || 'unresolved';
  const search = params.get('redirect_search') || '';
  const minHits = Math.max(0, parseInt(params.get('redirect_min_hits') || '0', 10) || 0);

  return {
    tab,
    status,
    search,
    minHits,
  };
};

const DEFAULT_REDIRECT_SETTINGS = {
  auto_redirects_enabled: true,
  redirect_deleted_posts: false,
  default_redirect_type: '301',
  alert_threshold: '50',
  enable_caching: true,
  cache_expiry: '3600',
  max_chain_depth: '3',
  enable_404_monitoring: true,
  retention_days: '90',
  auto_suggest_redirects: false,
};

const RedirectSettingsFullPage = () => {
  const [monitorDeepLink] = useState(() => parseRedirectMonitorDeepLink());
  const [activeTab, setActiveTab] = useState(() => monitorDeepLink.tab);
  const [redirects, setRedirects] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [filterType, setFilterType] = useState('all');
  const [selectedRedirects, setSelectedRedirects] = useState([]);
  const [bulkAction, setBulkAction] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [editingRedirect, setEditingRedirect] = useState(null);
  const [isAddingNew, setIsAddingNew] = useState(false);
  const [chainDetection, setChainDetection] = useState(null);
  const [settings, setSettings] = useState(DEFAULT_REDIRECT_SETTINGS);
  const [settingsLoading, setSettingsLoading] = useState(true);
  const [settingsSaving, setSettingsSaving] = useState(false);

  const { isTierActive } = useLicense();
  const { showNotification } = useNotification();

  const isPro = isTierActive('pro');
  const perPage = 20;
  const defaultRedirectType = String(settings.default_redirect_type || DEFAULT_REDIRECT_SETTINGS.default_redirect_type);

  // Load redirects
  const loadRedirects = useCallback(async () => {
    setLoading(true);
    setSelectedRedirects([]); // Clear selection when loading new data
    try {
      const response = await apiFetch({
        path: `/prorank-seo/v1/redirects?page=${currentPage}&per_page=${perPage}&search=${searchTerm}&type=${filterType}`,
        parse: false,
      });

      const data = await response.json();
      const pages = parseInt(response.headers.get('X-WP-TotalPages') || '1', 10);

      setRedirects(Array.isArray(data) ? data : []);
      setTotalPages(pages);
    } catch (error) {
      console.error('Failed to load redirects:', error);
      setRedirects([]);
      setTotalPages(1);
    } finally {
      setLoading(false);
    }
  }, [currentPage, searchTerm, filterType]);

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

  const loadSettings = useCallback(async () => {
    setSettingsLoading(true);
    try {
      const response = await apiFetch({ path: '/prorank-seo/v1/settings/redirects' });
      setSettings((current) => ({
        ...current,
        ...response,
      }));
    } catch (error) {
      showNotification(__('Failed to load redirect settings', 'prorank-seo'), 'error');
    } finally {
      setSettingsLoading(false);
    }
  }, [showNotification]);

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

  // Support deep links like:
  // admin.php?page=prorank-technical-seo&action=new&source=/old&destination=/new#redirects
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const action = params.get('action');

    if (action !== 'new') {
      return;
    }

    const source = params.get('source') || '';
    const destination = params.get('destination') || '';

    setActiveTab('redirects');
    setEditingRedirect({
      id: null,
      source_url: source,
      target_url: destination,
      type: '301',
      status: 'active',
      is_regex: false,
    });
    setIsAddingNew(true);

    // Consume one-time action params so the editor does not reopen on refresh.
    params.delete('action');
    params.delete('source');
    params.delete('destination');
    const nextQuery = params.toString();
    const nextUrl = `${window.location.pathname}${nextQuery ? `?${nextQuery}` : ''}${window.location.hash || ''}`;
    window.history.replaceState({}, '', nextUrl);
  }, []);

  // Handle bulk actions
  const handleBulkAction = async () => {
    if (!bulkAction || selectedRedirects.length === 0) {
      return;
    }

    try {
      await apiFetch({
        path: '/prorank-seo/v1/redirects/bulk',
        method: 'POST',
        data: {
          action: bulkAction,
          ids: selectedRedirects,
        },
      });

      let actionText;
      if (bulkAction === 'delete') {
        actionText = __('deleted', 'prorank-seo');
      } else if (bulkAction === 'activate') {
        actionText = __('activated', 'prorank-seo');
      } else {
        actionText = __('deactivated', 'prorank-seo');
      }

      showNotification(
        sprintf(__('%1$d redirects %2$s successfully', 'prorank-seo'), selectedRedirects.length, actionText),
        'success'
      );

      setSelectedRedirects([]);
      setBulkAction('');
      loadRedirects();
    } catch (error) {
      showNotification(__('Failed to perform bulk action', 'prorank-seo'), 'error');
    }
  };

  // Handle delete
  const handleDelete = async (id) => {
    if (!confirm(__('Are you sure you want to delete this redirect?', 'prorank-seo'))) {
      return;
    }

    try {
      await apiFetch({
        path: `/prorank-seo/v1/redirects/${id}`,
        method: 'DELETE',
      });
      showNotification(__('Redirect deleted successfully', 'prorank-seo'), 'success');
      loadRedirects();
    } catch (error) {
      showNotification(__('Failed to delete redirect', 'prorank-seo'), 'error');
    }
  };

  // Handle select all
  const handleSelectAll = (checked) => {
    if (checked) {
      setSelectedRedirects(redirects.map((r) => r.id));
    } else {
      setSelectedRedirects([]);
    }
  };

  // Handle check chains
  const handleCheckChains = async () => {
    try {
      const response = await apiFetch({ path: '/prorank-seo/v1/redirects/check-chains' });
      setChainDetection(response);
      if (response.chains_detected > 0 || response.loops_detected > 0) {
        showNotification(
          sprintf(__('%d chains and %d loops detected', 'prorank-seo'), response.chains_detected, response.loops_detected),
          'warning'
        );
      } else {
        showNotification(__('No redirect chains or loops detected', 'prorank-seo'), 'success');
      }
    } catch (error) {
      showNotification(__('Failed to check redirect chains', 'prorank-seo'), 'error');
    }
  };

  // Handle export
  const handleExport = async () => {
    try {
      const response = await apiFetch({ path: '/prorank-seo/v1/redirects/export' });
      const blob = new Blob([response.csv], { type: 'text/csv' });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = response.filename;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      showNotification(__('Redirects exported successfully', 'prorank-seo'), 'success');
    } catch (error) {
      showNotification(__('Failed to export redirects', 'prorank-seo'), 'error');
    }
  };

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

  const handleSaveSettings = async () => {
    setSettingsSaving(true);
    try {
      await apiFetch({
        path: '/prorank-seo/v1/settings/redirects',
        method: 'POST',
        data: settings,
      });
      showNotification(__('Redirect settings saved successfully', 'prorank-seo'), 'success');
      await loadSettings();
    } catch (error) {
      showNotification(error?.message || __('Failed to save redirect settings', 'prorank-seo'), 'error');
    } finally {
      setSettingsSaving(false);
    }
  };

  const typeOptions = [
    { value: 'all', label: __('All Types', 'prorank-seo') },
    { value: '301', label: __('301 Permanent', 'prorank-seo') },
    { value: '302', label: __('302 Temporary', 'prorank-seo') },
    { value: '307', label: __('307 Temporary', 'prorank-seo') },
    { value: '308', label: __('308 Permanent', 'prorank-seo') },
  ];

  const bulkActionOptions = [
    { value: '', label: __('Bulk Actions', 'prorank-seo') },
    { value: 'activate', label: __('Activate', 'prorank-seo') },
    { value: 'deactivate', label: __('Deactivate', 'prorank-seo') },
    { value: 'delete', label: __('Delete', 'prorank-seo') },
  ];

  if (loading) {
    return (
      <div className="pr:flex pr:flex-col pr:items-center pr:justify-center pr:py-12">
        <Spinner size="lg" />
        <p className="pr:mt-4 pr:text-gray-600">{__('Loading redirects…', 'prorank-seo')}</p>
      </div>
    );
  }

  return (
    <div className="pr:space-y-6">
      {/* Header */}
      <div className="pr:flex pr:justify-between pr:items-center">
        <div>
          <h3 className="pr:text-2xl pr:font-bold pr:mb-2">{__('Redirect Manager', 'prorank-seo')}</h3>
          <p className="pr:text-gray-600">
            {__('Manage URL redirects to maintain SEO value when URLs change', 'prorank-seo')}
          </p>
        </div>
        <Button
          variant="primary"
          icon={PlusIcon}
          onClick={() => {
            setEditingRedirect(null);
            setIsAddingNew(true);
          }}
        >
          {__('Add New Redirect', 'prorank-seo')}
        </Button>
      </div>

      {/* Tabs */}
      <div className="pr:flex pr:border-b pr:border-gray-200">
        <button
          type="button"
          className={`pr:px-4 pr:py-3 pr:font-medium pr:text-sm pr:border-b-2 pr:transition-colors ${
            activeTab === 'redirects'
              ? 'pr:border-primary-600 pr:text-primary-600'
              : 'pr:border-transparent pr:text-gray-600 pr:hover:text-gray-800 pr:hover:border-gray-300'
          }`}
          onClick={() => setActiveTab('redirects')}
        >
          {__('Redirects', 'prorank-seo')}
        </button>
        <button
          type="button"
          className={`pr:px-4 pr:py-3 pr:font-medium pr:text-sm pr:border-b-2 pr:transition-colors pr:inline-flex pr:items-center pr:gap-2 ${
            activeTab === '404-monitor'
              ? 'pr:border-primary-600 pr:text-primary-600'
              : 'pr:border-transparent pr:text-gray-600 pr:hover:text-gray-800 pr:hover:border-gray-300'
          }`}
          onClick={() => setActiveTab('404-monitor')}
        >
          {__('404 Monitor', 'prorank-seo')}
        </button>
        <button
          type="button"
          className={`pr:px-4 pr:py-3 pr:font-medium pr:text-sm pr:border-b-2 pr:transition-colors ${
            activeTab === 'settings'
              ? 'pr:border-primary-600 pr:text-primary-600'
              : 'pr:border-transparent pr:text-gray-600 pr:hover:text-gray-800 pr:hover:border-gray-300'
          }`}
          onClick={() => setActiveTab('settings')}
        >
          {__('Settings', 'prorank-seo')}
        </button>
      </div>

      {/* Redirects Tab */}
      {activeTab === 'redirects' && (
        <>
          {/* Tools */}
          <Card>
            <div className="pr:flex pr:gap-3 pr:p-4">
              <Button variant="secondary" onClick={handleExport}>
                {__('Export CSV', 'prorank-seo')}
              </Button>
              <Button variant="secondary" onClick={handleCheckChains}>
                {__('Check for Chains', 'prorank-seo')}
              </Button>
            </div>
          </Card>

          {/* Chain Detection Results */}
          {chainDetection && (chainDetection.chains_detected > 0 || chainDetection.loops_detected > 0) && (
            <Alert type="warning" dismissible onDismiss={() => setChainDetection(null)}>
              <strong>{__('Redirect Issues Detected:', 'prorank-seo')}</strong>
              <ul className="pr:mt-2 pr:ml-4 pr:list-disc">
                {chainDetection.chains_detected > 0 && (
                  <li>{sprintf(__('%d redirect chains found', 'prorank-seo'), chainDetection.chains_detected)}</li>
                )}
                {chainDetection.loops_detected > 0 && (
                  <li>{sprintf(__('%d redirect loops detected', 'prorank-seo'), chainDetection.loops_detected)}</li>
                )}
              </ul>
            </Alert>
          )}

          {/* Filters */}
          <Card>
            <div className="pr:flex pr:flex-wrap pr:items-end pr:gap-4 pr:p-4">
              <div className="pr:flex-1 pr:min-w-[200px]">
                <Input
                  label={__('Search redirects', 'prorank-seo')}
                  value={searchTerm}
                  onChange={(value) => setSearchTerm(value)}
                  placeholder={__('Search by URL…', 'prorank-seo')}
                />
              </div>
              <div className="pr:w-[200px]">
                <Select
                  label={__('Filter by type', 'prorank-seo')}
                  value={filterType}
                  onChange={(value) => setFilterType(value)}
                  options={typeOptions}
                />
              </div>
              <Button variant="secondary" onClick={() => { setCurrentPage(1); loadRedirects(); }}>
                {__('Filter', 'prorank-seo')}
              </Button>
              <div className="pr:flex-1" />
              <div className="pr:w-[150px]">
                <Select value={bulkAction} onChange={(value) => setBulkAction(value)} options={bulkActionOptions} />
              </div>
              <Button variant="secondary" onClick={handleBulkAction} disabled={!bulkAction || selectedRedirects.length === 0}>
                {__('Apply', 'prorank-seo')}
              </Button>
            </div>
          </Card>

          {/* Table */}
          <Card>
            {redirects.length === 0 ? (
              <div className="pr:text-center pr:py-12">
                <p className="pr:text-gray-500 pr:mb-4">{__('No redirects found.', 'prorank-seo')}</p>
                <Button
                  variant="primary"
                  icon={PlusIcon}
                  onClick={() => {
                    setEditingRedirect(null);
                    setIsAddingNew(true);
                  }}
                >
                  {__('Add Your First Redirect', 'prorank-seo')}
                </Button>
              </div>
            ) : (
              <>
                <div className="pr:overflow-x-auto">
                  <table className="pr:w-full pr:border-collapse">
                    <thead className="pr:bg-gray-50">
                      <tr>
                        <th className="pr:px-4 pr:py-3 pr:text-left pr:w-12">
                          <Checkbox
                            checked={selectedRedirects.length === redirects.length}
                            onChange={(value) => handleSelectAll(!!value)}
                          />
                        </th>
                        <th className="pr:px-4 pr:py-3 pr:text-left pr:text-sm pr:font-medium pr:text-gray-700">
                          {__('Source URL', 'prorank-seo')}
                        </th>
                        <th className="pr:px-4 pr:py-3 pr:text-left pr:text-sm pr:font-medium pr:text-gray-700">
                          {__('Target URL', 'prorank-seo')}
                        </th>
                        <th className="pr:px-4 pr:py-3 pr:text-left pr:text-sm pr:font-medium pr:text-gray-700">
                          {__('Type', 'prorank-seo')}
                        </th>
                        <th className="pr:px-4 pr:py-3 pr:text-left pr:text-sm pr:font-medium pr:text-gray-700">
                          {__('Status', 'prorank-seo')}
                        </th>
                        <th className={`pr:px-4 pr:py-3 pr:text-left pr:text-sm pr:font-medium pr:text-gray-700 ${!isPro ? 'pr:opacity-50' : ''}`}>
                          <span className="pr:inline-flex pr:items-center pr:gap-1">
                            {__('Hits', 'prorank-seo')}
                            {!isPro && <LockClosedIcon className="pr:w-4 pr:h-4 pr:text-gray-400" />}
                          </span>
                        </th>
                        <th className={`pr:px-4 pr:py-3 pr:text-left pr:text-sm pr:font-medium pr:text-gray-700 ${!isPro ? 'pr:opacity-50' : ''}`}>
                          <span className="pr:inline-flex pr:items-center pr:gap-1">
                            {__('Last Hit', 'prorank-seo')}
                            {!isPro && <LockClosedIcon className="pr:w-4 pr:h-4 pr:text-gray-400" />}
                          </span>
                        </th>
                        <th className="pr:px-4 pr:py-3 pr:text-left pr:text-sm pr:font-medium pr:text-gray-700">
                          {__('Actions', 'prorank-seo')}
                        </th>
                      </tr>
                    </thead>
                    <tbody className="pr:bg-white pr:divide-y pr:divide-gray-200">
                      {redirects.map((redirect) => (
                        <tr key={redirect.id} className="pr:hover:bg-gray-50">
                          <td className="pr:px-4 pr:py-3">
                            <Checkbox
                              checked={selectedRedirects.includes(redirect.id)}
                              onChange={(value) => {
                                const checked = !!value;
                                if (checked) {
                                  setSelectedRedirects([...selectedRedirects, redirect.id]);
                                } else {
                                  setSelectedRedirects(selectedRedirects.filter((id) => id !== redirect.id));
                                }
                              }}
                            />
                          </td>
                          <td className="pr:px-4 pr:py-3">
                            <code className="pr:text-sm pr:bg-gray-100 pr:px-2 pr:py-1 pr:rounded-xs">{redirect.source_url}</code>
                            {redirect.is_regex && isPro && (
                              <span className="pr:ml-2 pr:px-2 pr:py-0.5 pr:bg-blue-100 pr:text-blue-700 pr:text-xs pr:rounded-xs">
                                {__('Regex', 'prorank-seo')}
                              </span>
                            )}
                          </td>
                          <td className="pr:px-4 pr:py-3">
                            <code className="pr:text-sm pr:bg-gray-100 pr:px-2 pr:py-1 pr:rounded-xs">{redirect.target_url}</code>
                          </td>
                          <td className="pr:px-4 pr:py-3 pr:text-sm">{redirect.type}</td>
                          <td className="pr:px-4 pr:py-3">
                            <span className={`pr:px-2 pr:py-1 pr:text-xs pr:font-medium pr:rounded-xs ${
                              redirect.status === 'active'
                                ? 'pr:bg-success-100 pr:text-success-700'
                                : 'pr:bg-gray-100 pr:text-gray-700'
                            }`}>
                              {redirect.status === 'active' ? __('Active', 'prorank-seo') : __('Inactive', 'prorank-seo')}
                            </span>
                          </td>
                          <td className={`pr:px-4 pr:py-3 pr:text-sm ${!isPro ? 'pr:opacity-50' : ''}`}>
                            {isPro ? redirect.hits : '—'}
                          </td>
                          <td className={`pr:px-4 pr:py-3 pr:text-sm ${!isPro ? 'pr:opacity-50' : ''}`}>
                            {isPro && redirect.last_hit_timestamp ? new Date(redirect.last_hit_timestamp).toLocaleDateString() : '—'}
                          </td>
                          <td className="pr:px-4 pr:py-3">
                            <div className="pr:flex pr:gap-2">
                              <Button size="sm" variant="ghost" icon={PencilIcon} onClick={() => setEditingRedirect(redirect)} />
                              <Button
                                size="sm"
                                variant="ghost"
                                icon={TrashIcon}
                                onClick={() => handleDelete(redirect.id)}
                                className="pr:text-error-500 pr:hover:text-error-600"
                              />
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* Pagination */}
                {totalPages > 1 && (
                  <div className="pr:flex pr:items-center pr:justify-between pr:px-4 pr:py-3 pr:border-t pr:border-gray-200">
                    <Button variant="secondary" onClick={() => setCurrentPage(currentPage - 1)} disabled={currentPage === 1}>
                      {__('Previous', 'prorank-seo')}
                    </Button>
                    <span className="pr:text-sm pr:text-gray-600">
                      {sprintf(__('Page %1$d of %2$d', 'prorank-seo'), currentPage, totalPages)}
                    </span>
                    <Button variant="secondary" onClick={() => setCurrentPage(currentPage + 1)} disabled={currentPage === totalPages}>
                      {__('Next', 'prorank-seo')}
                    </Button>
                  </div>
                )}
              </>
            )}
          </Card>
        </>
      )}

      {/* 404 Monitor Tab */}
      {activeTab === '404-monitor' && (
        <NotFoundMonitor
          initialStatus={monitorDeepLink.status}
          initialSearch={monitorDeepLink.search}
          initialMinHits={monitorDeepLink.minHits}
          onCreateRedirect={() => {
            setEditingRedirect(null);
            setIsAddingNew(false);
            setActiveTab('redirects');
            loadRedirects();
          }}
          onOpenRedirectEditor={(draftRedirect) => {
            setActiveTab('redirects');
            setEditingRedirect({ ...draftRedirect, id: null });
            setIsAddingNew(true);
          }}
        />
      )}

      {/* Settings Tab */}
      {activeTab === 'settings' && (
        <Card>
          <div className="pr:p-6">
            <h3 className="pr:text-xl pr:font-bold pr:mb-4">{__('Redirect Settings', 'prorank-seo')}</h3>
            {settingsLoading ? (
              <div className="pr:flex pr:flex-col pr:items-center pr:justify-center pr:py-12">
                <Spinner size="md" />
                <p className="pr:mt-4 pr:text-gray-600">{__('Loading redirect settings…', 'prorank-seo')}</p>
              </div>
            ) : (
            <div className="pr:space-y-8">
              <div>
                <h4 className="pr:text-lg pr:font-semibold pr:mb-2">{__('Auto-Redirect Settings', 'prorank-seo')}</h4>
                <p className="pr:text-gray-600 pr:mb-4">{__('Configure automatic redirect creation.', 'prorank-seo')}</p>
                <div className="pr:space-y-4">
                  <Toggle
                    label={__('Enable Auto-Redirects', 'prorank-seo')}
                    description={__('Automatically create redirects when post URLs change', 'prorank-seo')}
                    checked={!!settings.auto_redirects_enabled}
                    onChange={(value) => updateSetting('auto_redirects_enabled', !!value)}
                  />
                  <Toggle
                    label={__('Redirect Deleted Posts', 'prorank-seo')}
                    description={__('Create redirects to home page when posts are deleted', 'prorank-seo')}
                    checked={!!settings.redirect_deleted_posts}
                    onChange={(value) => updateSetting('redirect_deleted_posts', !!value)}
                  />
                  <Select
                    label={__('Default Redirect Type', 'prorank-seo')}
                    value={String(settings.default_redirect_type)}
                    onChange={(value) => updateSetting('default_redirect_type', String(value))}
                    options={typeOptions.filter((option) => option.value !== 'all')}
                  />
                </div>
              </div>

              <div>
                <h4 className="pr:text-lg pr:font-semibold pr:mb-2">{__('Performance Settings', 'prorank-seo')}</h4>
                <p className="pr:text-gray-600 pr:mb-4">{__('Optimize redirect processing.', 'prorank-seo')}</p>
                <div className="pr:space-y-4">
                  <Toggle
                    label={__('Enable Redirect Caching', 'prorank-seo')}
                    description={__('Cache redirects for faster processing', 'prorank-seo')}
                    checked={!!settings.enable_caching}
                    onChange={(value) => updateSetting('enable_caching', !!value)}
                  />
                  <Input
                    label={__('Cache Expiry (seconds)', 'prorank-seo')}
                    type="number"
                    min={60}
                    value={String(settings.cache_expiry)}
                    onChange={(value) => updateSetting('cache_expiry', String(value))}
                  />
                  <Input
                    label={__('Maximum Chain Depth', 'prorank-seo')}
                    type="number"
                    min={1}
                    value={String(settings.max_chain_depth)}
                    onChange={(value) => updateSetting('max_chain_depth', String(value))}
                  />
                </div>
              </div>

              <div>
                <h4 className="pr:text-lg pr:font-semibold pr:mb-2">{__('404 Monitor Settings', 'prorank-seo')}</h4>
                <p className="pr:text-gray-600 pr:mb-4">{__('Control how unresolved 404 URLs are tracked and suggested for redirects.', 'prorank-seo')}</p>
                <div className="pr:space-y-4">
                  <Toggle
                    label={__('Enable 404 Monitoring', 'prorank-seo')}
                    description={__('Track unresolved 404 requests and surface them in the 404 Monitor tab', 'prorank-seo')}
                    checked={!!settings.enable_404_monitoring}
                    onChange={(value) => updateSetting('enable_404_monitoring', !!value)}
                  />
                  <Toggle
                    label={__('Auto-Suggest Redirects', 'prorank-seo')}
                    description={__('Suggest likely redirect targets for tracked 404 URLs', 'prorank-seo')}
                    checked={!!settings.auto_suggest_redirects}
                    onChange={(value) => updateSetting('auto_suggest_redirects', !!value)}
                  />
                  <Input
                    label={__('Alert Threshold', 'prorank-seo')}
                    type="number"
                    min={1}
                    value={String(settings.alert_threshold)}
                    onChange={(value) => updateSetting('alert_threshold', String(value))}
                    helperText={__('Trigger high-priority alerts after this many hits on a single 404 URL.', 'prorank-seo')}
                  />
                  <Input
                    label={__('Retention Days', 'prorank-seo')}
                    type="number"
                    min={1}
                    value={String(settings.retention_days)}
                    onChange={(value) => updateSetting('retention_days', String(value))}
                    helperText={__('Delete resolved or stale 404 records after this many days.', 'prorank-seo')}
                  />
                </div>
              </div>

              <div className="pr:pt-4 pr:border-t pr:border-gray-200">
                <Button variant="primary" onClick={handleSaveSettings} disabled={settingsSaving}>
                  {__('Save Settings', 'prorank-seo')}
                </Button>
              </div>
            </div>
            )}
          </div>
        </Card>
      )}

      {/* Edit Panel */}
      {(editingRedirect || isAddingNew) && (
        <RedirectEditPanel
          redirect={editingRedirect}
          onClose={() => {
            setEditingRedirect(null);
            setIsAddingNew(false);
            loadRedirects();
          }}
          defaultRedirectType={defaultRedirectType}
        />
      )}
    </div>
  );
};

export default RedirectSettingsFullPage;
