import { useState, useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Button, TextControl, Notice } from '@wordpress/components';
import { CheckCircleIcon, XCircleIcon, BeakerIcon } from '@heroicons/react/24/outline';

/**
 * RegexTester component for testing regex redirect patterns
 *
 * @param {Object} props
 * @param {string} props.pattern - The regex pattern to test
 * @param {string} props.targetUrl - The target URL with backreferences
 * @param {Function} props.onPatternChange - Callback when pattern is updated
 */
const RegexTester = ({ pattern, targetUrl = '', onPatternChange }) => {
  const [testUrls, setTestUrls] = useState(['']);
  const [results, setResults] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const addTestUrl = useCallback(() => {
    setTestUrls([...testUrls, '']);
  }, [testUrls]);

  const removeTestUrl = useCallback((index) => {
    const newUrls = testUrls.filter((_, i) => i !== index);
    setTestUrls(newUrls.length > 0 ? newUrls : ['']);
  }, [testUrls]);

  const updateTestUrl = useCallback((index, value) => {
    const newUrls = [...testUrls];
    newUrls[index] = value;
    setTestUrls(newUrls);
  }, [testUrls]);

  const runTest = useCallback(async () => {
    if (!pattern.trim()) {
      setError(__('Please enter a regex pattern to test', 'prorank-seo'));
      return;
    }

    const urlsToTest = testUrls.filter(url => url.trim());
    if (urlsToTest.length === 0) {
      setError(__('Please enter at least one URL to test', 'prorank-seo'));
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/redirects/test-regex',
        method: 'POST',
        data: {
          pattern,
          test_urls: urlsToTest,
          target_url: targetUrl,
        },
      });

      if (!response.valid) {
        setError(response.error);
        setResults(null);
      } else {
        setResults(response.results);
        setError(null);
      }
    } catch (err) {
      setError(err.message || __('Failed to test regex pattern', 'prorank-seo'));
      setResults(null);
    } finally {
      setLoading(false);
    }
  }, [pattern, testUrls, targetUrl]);

  return (
    <div className="prorank-regex-tester">
      <div className="prorank-regex-tester__header">
        <BeakerIcon className="pr:w-5 pr:h-5 pr:text-primary-500" />
        <h4 className="pr:text-sm pr:font-medium pr:text-gray-700 pr:m-0 pr:ml-2">
          {__('Test Your Pattern', 'prorank-seo')}
        </h4>
      </div>

      <p className="pr:text-xs pr:text-gray-500 pr:mt-1 pr:mb-3">
        {__('Enter URLs to test if they match your regex pattern', 'prorank-seo')}
      </p>

      <div className="prorank-regex-tester__urls">
        {testUrls.map((url, index) => (
          <div key={index} className="prorank-regex-tester__url-row">
            <TextControl
              value={url}
              onChange={(value) => updateTestUrl(index, value)}
              placeholder={__('e.g., /old-page/123', 'prorank-seo')}
              className="prorank-regex-tester__input"
            />
            {testUrls.length > 1 && (
              <Button
                variant="secondary"
                isSmall
                isDestructive
                onClick={() => removeTestUrl(index)}
                className="prorank-regex-tester__remove"
              >
                ×
              </Button>
            )}
          </div>
        ))}
      </div>

      <div className="prorank-regex-tester__actions">
        <Button
          variant="link"
          onClick={addTestUrl}
          className="pr:text-xs"
        >
          {__('+ Add another URL', 'prorank-seo')}
        </Button>
        <Button
          variant="secondary"
          onClick={runTest}
          isBusy={loading}
          disabled={loading}
        >
          {__('Test Pattern', 'prorank-seo')}
        </Button>
      </div>

      {error && (
        <Notice status="error" isDismissible={false} className="pr:mt-3">
          {error}
        </Notice>
      )}

      {results && results.length > 0 && (
        <div className="prorank-regex-tester__results">
          <h5 className="pr:text-xs pr:font-medium pr:text-gray-600 pr:mb-2">
            {__('Results', 'prorank-seo')}
          </h5>
          {results.map((result, index) => (
            <div
              key={index}
              className={`prorank-regex-tester__result ${
                result.matches ? 'prorank-regex-tester__result--match' : 'prorank-regex-tester__result--no-match'
              }`}
            >
              <div className="prorank-regex-tester__result-header">
                {result.matches ? (
                  <CheckCircleIcon className="pr:w-4 pr:h-4 pr:text-success-500" />
                ) : (
                  <XCircleIcon className="pr:w-4 pr:h-4 pr:text-error-500" />
                )}
                <code className="pr:text-xs pr:ml-2">{result.url}</code>
              </div>
              {result.matches && result.captures && result.captures.length > 0 && (
                <div className="prorank-regex-tester__captures">
                  <span className="pr:text-xs pr:text-gray-500">
                    {__('Captured groups:', 'prorank-seo')}
                  </span>
                  {result.captures.map((capture, i) => (
                    <span key={i} className="prorank-regex-tester__capture">
                      ${i}: <code>{capture}</code>
                    </span>
                  ))}
                </div>
              )}
              {result.resolved_target && (
                <div className="prorank-regex-tester__resolved">
                  <span className="pr:text-xs pr:text-gray-500">
                    {__('Redirects to:', 'prorank-seo')}
                  </span>
                  <code className="pr:text-xs pr:ml-1 pr:text-primary-600">
                    {result.resolved_target}
                  </code>
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default RegexTester;
