import { useState, useEffect, useCallback } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import {
  ExclamationTriangleIcon,
  CheckCircleIcon,
  ArrowPathIcon,
  MagnifyingGlassIcon,
  TrashIcon,
  ArrowRightIcon,
  LinkIcon,
  GlobeAltIcon,
  ChartBarIcon,
  SparklesIcon,
  XMarkIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
  FunnelIcon,
} from '@heroicons/react/24/outline';
import { CheckCircleIcon as CheckCircleSolid } from '@heroicons/react/24/solid';
import { useNotification } from '../../contexts/NotificationContext';
import './404-monitor.css';

const NotFoundMonitor = ({
  onCreateRedirect,
  onOpenRedirectEditor,
  initialStatus = 'unresolved',
  initialSearch = '',
  initialMinHits = 0,
}) => {
  const [errors, setErrors] = useState([]);
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState(null);
  const [filteredTotal, setFilteredTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [filterStatus, setFilterStatus] = useState(() => initialStatus || 'unresolved');
  const [searchTerm, setSearchTerm] = useState(() => initialSearch || '');
  const [minHits, setMinHits] = useState(() => Math.max(0, Number(initialMinHits) || 0));
  const [showNoiseTraffic, setShowNoiseTraffic] = useState(false);
  const [selectedErrors, setSelectedErrors] = useState([]);
  const [actionLoading, setActionLoading] = useState({});

  const { showNotification } = useNotification();
  const perPage = 20;

  // Load 404 errors and stats
  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const query = new URLSearchParams({
        page: String(currentPage),
        per_page: String(perPage),
        status: filterStatus || '',
        search: searchTerm || '',
        include_noise: showNoiseTraffic ? '1' : '0',
      });
      if (minHits > 0) {
        query.set('min_hits', String(minHits));
      }

      // Load errors
      const errorsResponse = await apiFetch({
        path: `/prorank-seo/v1/404-monitor?${query.toString()}`,
      });

      setErrors(errorsResponse?.errors || []);
      setFilteredTotal(errorsResponse?.total || 0);
      setTotalPages(errorsResponse?.total_pages || 1);

      // Load stats
      try {
        const statsResponse = await apiFetch({
          path: `/prorank-seo/v1/404-monitor/stats?${query.toString()}`,
        });

        if (statsResponse && typeof statsResponse === 'object') {
          setStats({
            stats: statsResponse.stats || {
              total_urls: 0,
              total_hits: 0,
              resolved_count: 0,
              suggested_count: 0
            },
            top_errors: statsResponse.top_errors || [],
            recent_errors: statsResponse.recent_errors || []
          });
        }
      } catch (statsError) {
        console.warn('404 stats not available:', statsError);
        setStats({
          stats: { total_urls: 0, total_hits: 0, resolved_count: 0, suggested_count: 0 },
          top_errors: [],
          recent_errors: []
        });
      }
    } catch (error) {
      console.error('Failed to load 404 data:', error);
      showNotification(__('404 Monitor is not available. Please ensure the database tables are created.', 'prorank-seo'), 'error');
      setErrors([]);
      setFilteredTotal(0);
      setStats({
        stats: { total_urls: 0, total_hits: 0, resolved_count: 0, suggested_count: 0 },
        top_errors: [],
        recent_errors: []
      });
    } finally {
      setLoading(false);
    }
  }, [currentPage, filterStatus, searchTerm, minHits, showNoiseTraffic, showNotification]);

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

  // Handle create redirect from 404
  const handleCreateRedirect = async (errorId, targetUrl = null, sourceUrl = '') => {
    if (!errorId) {
      if (onOpenRedirectEditor) {
        onOpenRedirectEditor({
          source_url: sourceUrl || '',
          target_url: targetUrl || '',
          type: '301',
          status: 'active',
          is_regex: false,
        });
        return;
      }
      showNotification(__('Unable to create redirect: missing 404 error reference.', 'prorank-seo'), 'error');
      return;
    }

    if (!targetUrl && onOpenRedirectEditor) {
      onOpenRedirectEditor({
        source_url: sourceUrl || '',
        target_url: '',
        type: '301',
        status: 'active',
        is_regex: false,
      });
      return;
    }

    setActionLoading(prev => ({ ...prev, [errorId]: 'redirect' }));
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/404-monitor/create-redirect',
        method: 'POST',
        data: {
          id: errorId,
          target_url: targetUrl,
          type: 301,
        },
      });

      showNotification(response.message, 'success');
      loadData();

      if (onCreateRedirect) {
        onCreateRedirect(response.redirect_id);
      }
    } catch (error) {
      showNotification(error?.message || __('Failed to create redirect', 'prorank-seo'), 'error');
    } finally {
      setActionLoading(prev => ({ ...prev, [errorId]: null }));
    }
  };

  // Handle mark as resolved
  const handleResolve = async (errorId) => {
    setActionLoading(prev => ({ ...prev, [errorId]: 'resolve' }));
    try {
      await apiFetch({
        path: `/prorank-seo/v1/404-monitor/${errorId}`,
        method: 'POST',
      });

      showNotification(__('404 error marked as resolved', 'prorank-seo'), 'success');
      loadData();
    } catch (error) {
      showNotification(__('Failed to resolve 404 error', 'prorank-seo'), 'error');
    } finally {
      setActionLoading(prev => ({ ...prev, [errorId]: null }));
    }
  };

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

    setActionLoading(prev => ({ ...prev, [errorId]: 'delete' }));
    try {
      await apiFetch({
        path: `/prorank-seo/v1/404-monitor/${errorId}`,
        method: 'DELETE',
      });

      showNotification(__('404 error deleted', 'prorank-seo'), 'success');
      loadData();
    } catch (error) {
      showNotification(__('Failed to delete 404 error', 'prorank-seo'), 'error');
    } finally {
      setActionLoading(prev => ({ ...prev, [errorId]: null }));
    }
  };

  // Format date
  const formatDate = (dateString) => {
    if (!dateString) return '—';
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
  };

  // Get relative time
  const getRelativeTime = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now - date;
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    if (diffDays === 0) return __('Today', 'prorank-seo');
    if (diffDays === 1) return __('Yesterday', 'prorank-seo');
    if (diffDays < 7) return sprintf(__('%d days ago', 'prorank-seo'), diffDays);
    if (diffDays < 30) return sprintf(__('%d weeks ago', 'prorank-seo'), Math.floor(diffDays / 7));
    return formatDate(dateString);
  };

  if (loading) {
    return (
      <div className="prorank-404-loading">
        <div className="prorank-404-loading-spinner">
          <ArrowPathIcon className="pr:w-8 pr:h-8 pr:animate-spin pr:text-blue-500" />
        </div>
        <p className="pr:text-gray-600 pr:text-lg pr:font-medium">{__('Loading 404 Monitor…', 'prorank-seo')}</p>
        <p className="pr:text-gray-400 pr:text-sm">{__('Analyzing your site for broken links', 'prorank-seo')}</p>
      </div>
    );
  }

  const statsData = stats?.stats || {};
  const topErrors = stats?.top_errors || [];

  return (
    <div className="prorank-404-monitor-premium">
      {/* Stats Cards */}
      <div className="prorank-404-stats-grid">
        <div className="prorank-404-stat-card prorank-404-stat-danger">
          <div className="prorank-404-stat-icon">
            <ExclamationTriangleIcon className="pr:w-6 pr:h-6" />
          </div>
          <div className="prorank-404-stat-content">
            <span className="prorank-404-stat-value">{statsData.total_urls || 0}</span>
            <span className="prorank-404-stat-label">{__('Total 404 URLs', 'prorank-seo')}</span>
          </div>
        </div>

        <div className="prorank-404-stat-card prorank-404-stat-warning">
          <div className="prorank-404-stat-icon">
            <ChartBarIcon className="pr:w-6 pr:h-6" />
          </div>
          <div className="prorank-404-stat-content">
            <span className="prorank-404-stat-value">{statsData.total_hits || 0}</span>
            <span className="prorank-404-stat-label">{__('Total Hits', 'prorank-seo')}</span>
          </div>
        </div>

        <div className="prorank-404-stat-card prorank-404-stat-success">
          <div className="prorank-404-stat-icon">
            <CheckCircleIcon className="pr:w-6 pr:h-6" />
          </div>
          <div className="prorank-404-stat-content">
            <span className="prorank-404-stat-value">{statsData.resolved_count || 0}</span>
            <span className="prorank-404-stat-label">{__('Resolved', 'prorank-seo')}</span>
          </div>
        </div>

        <div className="prorank-404-stat-card prorank-404-stat-info">
          <div className="prorank-404-stat-icon">
            <SparklesIcon className="pr:w-6 pr:h-6" />
          </div>
          <div className="prorank-404-stat-content">
            <span className="prorank-404-stat-value">{statsData.suggested_count || 0}</span>
            <span className="prorank-404-stat-label">{__('Auto-Suggested', 'prorank-seo')}</span>
          </div>
        </div>
      </div>

      {/* Filters */}
      <div className="prorank-404-filters-bar">
        <div className="prorank-404-filter-group">
          <label className="prorank-404-filter-label">
            <FunnelIcon className="pr:w-4 pr:h-4" />
            {__('Status', 'prorank-seo')}
          </label>
          <select
            value={filterStatus}
            onChange={(e) => {
              setCurrentPage(1);
              setFilterStatus(e.target.value);
            }}
            className="prorank-404-filter-select"
          >
            <option value="">{__('All', 'prorank-seo')}</option>
            <option value="unresolved">{__('Unresolved', 'prorank-seo')}</option>
            <option value="resolved">{__('Resolved', 'prorank-seo')}</option>
          </select>
        </div>

        <div className="prorank-404-filter-group">
          <label className="prorank-404-filter-label">
            {__('Min Hits', 'prorank-seo')}
          </label>
          <input
            type="number"
            min="0"
            step="1"
            value={minHits}
            onChange={(e) => {
              setCurrentPage(1);
              const nextValue = parseInt(e.target.value || '0', 10);
              setMinHits(Number.isNaN(nextValue) ? 0 : Math.max(0, nextValue));
            }}
            className="prorank-404-search-input"
          />
        </div>

        <div className="prorank-404-filter-group">
          <label className="prorank-404-filter-label">
            {__('Traffic Type', 'prorank-seo')}
          </label>
          <label className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:font-medium pr:text-gray-700">
            <input
              type="checkbox"
              checked={showNoiseTraffic}
              onChange={(e) => {
                setCurrentPage(1);
                setShowNoiseTraffic(e.target.checked);
              }}
            />
            {__('Show scanner/probe traffic', 'prorank-seo')}
          </label>
        </div>

        <div className="prorank-404-filter-group prorank-404-search-group">
          <label className="prorank-404-filter-label">
            <MagnifyingGlassIcon className="pr:w-4 pr:h-4" />
            {__('Search URLs', 'prorank-seo')}
          </label>
          <input
            type="text"
            value={searchTerm}
            onChange={(e) => {
              setCurrentPage(1);
              setSearchTerm(e.target.value);
            }}
            placeholder={__('Search…', 'prorank-seo')}
            className="prorank-404-search-input"
          />
        </div>

        <button type="button" onClick={loadData} className="prorank-404-refresh-btn">
          <ArrowPathIcon className="pr:w-4 pr:h-4" />
          {__('Refresh', 'prorank-seo')}
        </button>
      </div>

      {!!statsData?.noise_filter_active && (
        <div className="pr:rounded-md pr:border pr:border-amber-200 pr:bg-amber-50 pr:px-4 pr:py-3 pr:text-sm pr:text-amber-800">
          {sprintf(
            __('Showing actionable 404s only. %1$d noisy URLs (%2$d hits) are hidden.', 'prorank-seo'),
            Number(statsData.noise_filtered_urls || 0),
            Number(statsData.noise_filtered_hits || 0)
          )}
        </div>
      )}

      {/* Top 404 Errors */}
      {topErrors.length > 0 && (
        <div className="prorank-404-top-section">
          <div className="prorank-404-section-header">
            <h3>
              <ExclamationTriangleIcon className="pr:w-5 pr:h-5 pr:text-red-500" />
              {__('Top 404 Errors', 'prorank-seo')}
            </h3>
            <span className="prorank-404-section-badge">{topErrors.length} {__('critical', 'prorank-seo')}</span>
          </div>
          <div className="prorank-404-top-list">
            {topErrors.slice(0, 5).map((error, index) => (
              <div key={error.url || index} className="prorank-404-top-item">
                <div className="prorank-404-top-rank">#{index + 1}</div>
                <div className="prorank-404-top-content">
                  <code className="prorank-404-url">{error.url}</code>
                  <div className="prorank-404-top-meta">
                    <span className="prorank-404-hits-badge">
                      {sprintf(__('%d hits', 'prorank-seo'), error.hits || 0)}
                    </span>
                    {error.auto_suggested && error.suggestion_url && (
                      <span className="prorank-404-suggestion-badge">
                        <SparklesIcon className="pr:w-3 pr:h-3" />
                        {__('Suggestion available', 'prorank-seo')}
                      </span>
                    )}
                  </div>
                </div>
                <button
                  type="button"
                  onClick={() => handleCreateRedirect(error.id, error.suggestion_url, error.url)}
                  className="prorank-404-action-btn prorank-404-action-primary"
                  disabled={actionLoading[error.id]}
                >
                  <LinkIcon className="pr:w-4 pr:h-4" />
                  {__('Create Redirect', 'prorank-seo')}
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 404 Errors Table */}
      <div className="prorank-404-table-section">
        <div className="prorank-404-section-header">
          <h3>
            <GlobeAltIcon className="pr:w-5 pr:h-5 pr:text-blue-500" />
            {__('404 Error Details', 'prorank-seo')}
          </h3>
          <span className="prorank-404-count-badge">{filteredTotal} {__('errors', 'prorank-seo')}</span>
        </div>

        {errors.length === 0 ? (
          <div className="prorank-404-empty-state">
            <div className="prorank-404-empty-icon">
              <CheckCircleSolid className="pr:w-16 pr:h-16 pr:text-green-500" />
            </div>
            <h4>{__('No 404 errors found!', 'prorank-seo')}</h4>
            <p>{__('Great job! Your site has no broken links to fix.', 'prorank-seo')}</p>
          </div>
        ) : (
          <>
            <div className="prorank-404-table-wrapper">
              <table className="prorank-404-table">
                <thead>
                  <tr>
                    <th className="prorank-404-th-url">{__('URL', 'prorank-seo')}</th>
                    <th className="prorank-404-th-hits">{__('Hits', 'prorank-seo')}</th>
                    <th className="prorank-404-th-date">{__('First Hit', 'prorank-seo')}</th>
                    <th className="prorank-404-th-date">{__('Last Hit', 'prorank-seo')}</th>
                    <th className="prorank-404-th-referrer">{__('Referrer', 'prorank-seo')}</th>
                    <th className="prorank-404-th-status">{__('Status', 'prorank-seo')}</th>
                    <th className="prorank-404-th-actions">{__('Actions', 'prorank-seo')}</th>
                  </tr>
                </thead>
                <tbody>
                  {errors.map((error) => (
                    <tr key={error.id} className={`prorank-404-row ${error.status === 'resolved' ? 'prorank-404-row-resolved' : ''}`}>
                      <td className="prorank-404-td-url">
                        <code className="prorank-404-url-code">{error.url}</code>
                        {error.auto_suggested && error.suggestion_url && (
                          <div className="prorank-404-suggestion-inline">
                            <ArrowRightIcon className="pr:w-3 pr:h-3" />
                            <code>{error.suggestion_url}</code>
                            <span className="prorank-404-match-score">
                              {sprintf(__('%d%% match', 'prorank-seo'), error.similarity_score || 0)}
                            </span>
                          </div>
                        )}
                      </td>
                      <td className="prorank-404-td-hits">
                        <span className={`prorank-404-hits ${error.hits >= 10 ? 'prorank-404-hits-high' : error.hits >= 5 ? 'prorank-404-hits-medium' : ''}`}>
                          {error.hits}
                        </span>
                      </td>
                      <td className="prorank-404-td-date">
                        <span title={formatDate(error.first_hit)}>{getRelativeTime(error.first_hit)}</span>
                      </td>
                      <td className="prorank-404-td-date">
                        <span title={formatDate(error.last_hit)}>{getRelativeTime(error.last_hit)}</span>
                      </td>
                      <td className="prorank-404-td-referrer">
                        {error.referrer ? (
                          <a href={error.referrer} target="_blank" rel="noopener noreferrer" className="prorank-404-referrer-link" title={error.referrer}>
                            {new URL(error.referrer).pathname.substring(0, 30)}...
                          </a>
                        ) : (
                          <span className="prorank-404-no-referrer">—</span>
                        )}
                      </td>
                      <td className="prorank-404-td-status">
                        <span className={`prorank-404-status-badge prorank-404-status-${error.status}`}>
                          {error.status === 'resolved' ? (
                            <>
                              <CheckCircleIcon className="pr:w-3 pr:h-3" />
                              {__('Resolved', 'prorank-seo')}
                            </>
                          ) : (
                            <>
                              <ExclamationTriangleIcon className="pr:w-3 pr:h-3" />
                              {__('Unresolved', 'prorank-seo')}
                            </>
                          )}
                        </span>
                      </td>
                      <td className="prorank-404-td-actions">
                        <div className="prorank-404-actions">
                          {error.status === 'unresolved' && (
                            <>
                              <button
                                type="button"
                                onClick={() => handleCreateRedirect(error.id, error.suggestion_url, error.url)}
                                className="prorank-404-btn prorank-404-btn-primary"
                                disabled={actionLoading[error.id]}
                                title={__('Create Redirect', 'prorank-seo')}
                              >
                                {actionLoading[error.id] === 'redirect' ? (
                                  <ArrowPathIcon className="pr:w-4 pr:h-4 pr:animate-spin" />
                                ) : (
                                  <LinkIcon className="pr:w-4 pr:h-4" />
                                )}
                              </button>
                              <button
                                type="button"
                                onClick={() => handleResolve(error.id)}
                                className="prorank-404-btn prorank-404-btn-success"
                                disabled={actionLoading[error.id]}
                                title={__('Mark Resolved', 'prorank-seo')}
                              >
                                {actionLoading[error.id] === 'resolve' ? (
                                  <ArrowPathIcon className="pr:w-4 pr:h-4 pr:animate-spin" />
                                ) : (
                                  <CheckCircleIcon className="pr:w-4 pr:h-4" />
                                )}
                              </button>
                            </>
                          )}
                          <button
                            type="button"
                            onClick={() => handleDelete(error.id)}
                            className="prorank-404-btn prorank-404-btn-danger"
                            disabled={actionLoading[error.id]}
                            title={__('Delete', 'prorank-seo')}
                          >
                            {actionLoading[error.id] === 'delete' ? (
                              <ArrowPathIcon className="pr:w-4 pr:h-4 pr:animate-spin" />
                            ) : (
                              <TrashIcon className="pr:w-4 pr:h-4" />
                            )}
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="prorank-404-pagination">
                <button
                  type="button"
                  onClick={() => setCurrentPage(currentPage - 1)}
                  disabled={currentPage === 1}
                  className="prorank-404-page-btn"
                >
                  <ChevronLeftIcon className="pr:w-4 pr:h-4" />
                  {__('Previous', 'prorank-seo')}
                </button>
                <span className="prorank-404-page-info">
                  {sprintf(__('Page %1$d of %2$d', 'prorank-seo'), currentPage, totalPages)}
                </span>
                <button
                  type="button"
                  onClick={() => setCurrentPage(currentPage + 1)}
                  disabled={currentPage === totalPages}
                  className="prorank-404-page-btn"
                >
                  {__('Next', 'prorank-seo')}
                  <ChevronRightIcon className="pr:w-4 pr:h-4" />
                </button>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

export default NotFoundMonitor;
