/**
 * Site Verification Tab Component
 *
 * Manages webmaster tools verification codes and custom meta tags
 *
 * @package ProRank\SEO
 */

import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { CheckCircleIcon, InformationCircleIcon } from '@heroicons/react/24/outline';
import { Card, Button, Input } from '../../../../components/ui';

const SiteVerificationTab = ({ settings, updateSettings, saveSettings }) => {
  const [isSaving, setIsSaving] = useState(false);
  const [hasChanges, setHasChanges] = useState(false);
  const [verificationStatus, setVerificationStatus] = useState({});

  const handleChange = (key, value) => {
    // Extract just the content value from full meta tag if provided
    if (value.includes('content=')) {
      const match = value.match(/content=['"](.*?)['"]/);
      if (match) {
        value = match[1];
      }
    }

    updateSettings({ [key]: value });
    setHasChanges(true);

    // Mark as unverified when changed
    setVerificationStatus(prev => ({
      ...prev,
      [key]: 'pending'
    }));
  };

  const handleSave = async () => {
    setIsSaving(true);
    const success = await saveSettings(settings);
    if (success) {
      setHasChanges(false);
      // Mark all as verified after successful save
      const newStatus = {};
      Object.keys(verificationStatus).forEach(key => {
        if (settings[key]) {
          newStatus[key] = 'verified';
        }
      });
      setVerificationStatus(newStatus);
    }
    setIsSaving(false);
  };

  const validateCustomMetaTags = (tags) => {
    // Basic validation to ensure only meta tags are allowed
    const cleaned = tags.replace(/<(?!meta\s|\/meta>)[^>]*>/gi, '');
    return cleaned;
  };

  const verificationServices = [
    {
      key: 'google_verification',
      name: __('Google Search Console', 'prorank-seo'),
      metaName: 'google-site-verification',
      helpUrl: 'https://search.google.com/search-console/verification',
      helpText: __('Get your verification code in Google Search Console', 'prorank-seo'),
      placeholder: 'your-google-verification-id',
    },
    {
      key: 'bing_verification',
      name: __('Bing Webmaster Tools', 'prorank-seo'),
      metaName: 'msvalidate.01',
      helpUrl: 'https://www.bing.com/webmasters/help/how-to-verify-ownership-of-your-site-afcfefc6',
      helpText: __('Get your verification code in Bing Webmaster Tools', 'prorank-seo'),
      placeholder: 'your-bing-verification-id',
    },
    {
      key: 'baidu_verification',
      name: __('Baidu Webmaster Tools', 'prorank-seo'),
      metaName: 'baidu-site-verification',
      helpUrl: 'https://ziyuan.baidu.com/',
      helpText: __('Get your verification code in Baidu Webmaster Tools', 'prorank-seo'),
      placeholder: 'your-baidu-verification-id',
    },
    {
      key: 'yandex_verification',
      name: __('Yandex Webmaster', 'prorank-seo'),
      metaName: 'yandex-verification',
      helpUrl: 'https://webmaster.yandex.com/',
      helpText: __('Get your verification code in Yandex Webmaster', 'prorank-seo'),
      placeholder: 'your-yandex-verification-id',
    },
    {
      key: 'pinterest_verification',
      name: __('Pinterest', 'prorank-seo'),
      metaName: 'p:domain_verify',
      helpUrl: 'https://help.pinterest.com/en/business/article/claim-your-website',
      helpText: __('Claim your site on Pinterest', 'prorank-seo'),
      placeholder: 'your-pinterest-verification-id',
    },
    {
      key: 'norton_verification',
      name: __('Norton Safe Web', 'prorank-seo'),
      metaName: 'norton-safeweb-site-verification',
      helpUrl: 'https://safeweb.norton.com/help/site_owners',
      helpText: __('Get your verification code from Norton Safe Web', 'prorank-seo'),
      placeholder: 'your-norton-verification-id',
    },
  ];

  return (
    <div className="pr:space-y-6">
      <div className="pr:flex pr:items-start pr:gap-3 pr:p-4 pr:bg-info-50 pr:border pr:border-info-200 pr:rounded-lg">
        <InformationCircleIcon className="pr:w-5 pr:h-5 pr:text-info-500 pr:shrink-0 pr:mt-0.5" />
        <p className="pr:text-sm pr:text-info-700">
          {__('Site verification helps establish ownership of your website with search engines and other services. Enter only the verification code/ID, not the entire meta tag.', 'prorank-seo')}
        </p>
      </div>

      <Card
        header={
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Webmaster Tools Verification', 'prorank-seo')}
          </h3>
        }
      >
        <div className="pr:space-y-6">
          {verificationServices.map((service) => (
            <div key={service.key} className="pr:space-y-2">
              <div className="pr:flex pr:items-start pr:justify-between pr:gap-4">
                <div className="pr:flex-1">
                  <h4 className="pr:text-sm pr:font-semibold pr:text-gray-900">
                    {service.name}
                  </h4>
                  <p className="pr:text-xs pr:text-gray-600 pr:mt-1">
                    {service.helpText}
                  </p>
                </div>
                <a
                  href={service.helpUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="pr:text-sm pr:text-primary-500 pr:hover:text-primary-600 pr:font-medium pr:shrink-0"
                >
                  {__('Get Code', 'prorank-seo')}
                </a>
              </div>

              <Input
                value={settings[service.key] || ''}
                onChange={(value) => handleChange(service.key, value)}
                placeholder={service.placeholder}
              />

              <div className="pr:p-3 pr:bg-gray-50 pr:rounded-xs pr:border pr:border-gray-200">
                <code className="pr:text-xs pr:text-gray-700 pr:break-all">
                  {`<meta name="${service.metaName}" content="${settings[service.key] || service.placeholder}" />`}
                </code>
              </div>

              {verificationStatus[service.key] === 'verified' && (
                <div className="pr:flex pr:items-center pr:gap-2 pr:text-success-600">
                  <CheckCircleIcon className="pr:w-4 pr:h-4" />
                  <span className="pr:text-xs pr:font-medium">
                    {__('Saved', 'prorank-seo')}
                  </span>
                </div>
              )}
            </div>
          ))}
        </div>
      </Card>

      <Card
        header={
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Custom Webmaster Tags', 'prorank-seo')}
          </h3>
        }
      >
        <div className="pr:space-y-4">
          <div className="pr:flex pr:items-start pr:gap-3 pr:p-3 pr:bg-gray-50 pr:rounded-lg">
            <InformationCircleIcon className="pr:w-5 pr:h-5 pr:text-gray-500 pr:shrink-0 pr:mt-0.5" />
            <p className="pr:text-sm pr:text-gray-700">
              {__('Add any additional verification meta tags here. Only <meta> tags are allowed.', 'prorank-seo')}
            </p>
          </div>

          <div className="pr:space-y-2">
            <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
              {__('Additional Meta Tags', 'prorank-seo')}
            </label>
            <textarea
              className="pr:block pr:w-full pr:px-3 pr:py-2 pr:border pr:border-gray-300 pr:rounded-md pr:text-sm pr:font-mono pr:focus:outline-hidden pr:focus:ring-2 pr:focus:ring-primary-500 pr:focus:border-transparent"
              value={settings.custom_meta_tags || ''}
              onChange={(e) => {
                const validated = validateCustomMetaTags(e.target.value);
                handleChange('custom_meta_tags', validated);
              }}
              placeholder={`<meta name="example-verification" content="your-verification-code" />
<meta name="another-service" content="another-code" />`}
              rows={5}
            />
            <p className="pr:text-xs pr:text-gray-500">
              {__('Each meta tag should be on a new line. Invalid HTML will be automatically removed.', 'prorank-seo')}
            </p>
          </div>
        </div>
      </Card>

      <Card
        header={
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('How Verification Works', 'prorank-seo')}
          </h3>
        }
      >
        <div className="pr:space-y-4">
          <div>
            <h4 className="pr:text-sm pr:font-semibold pr:text-gray-900 pr:mb-2">
              {__('What happens after you save:', 'prorank-seo')}
            </h4>
            <ol className="pr:list-decimal pr:list-inside pr:space-y-1 pr:text-sm pr:text-gray-600">
              <li>{__('ProRank SEO adds the verification meta tags to your homepage', 'prorank-seo')}</li>
              <li>{__('Visit the respective webmaster tools to complete verification', 'prorank-seo')}</li>
              <li>{__('The service will detect the meta tag and verify ownership', 'prorank-seo')}</li>
              <li>{__('You can then access analytics and tools for that service', 'prorank-seo')}</li>
            </ol>
          </div>

          <div>
            <h4 className="pr:text-sm pr:font-semibold pr:text-gray-900 pr:mb-2">
              {__('Important Notes:', 'prorank-seo')}
            </h4>
            <ul className="pr:list-disc pr:list-inside pr:space-y-1 pr:text-sm pr:text-gray-600">
              <li>{__('Keep verification codes even after verification is complete', 'prorank-seo')}</li>
              <li>{__('Verification codes are only added to your homepage', 'prorank-seo')}</li>
              <li>{__('Each service provides different tools and insights', 'prorank-seo')}</li>
              <li>{__('Google Search Console is highly recommended for SEO', 'prorank-seo')}</li>
            </ul>
          </div>
        </div>
      </Card>

      {hasChanges && (
        <Card>
          <div className="pr:flex pr:items-center pr:justify-end pr:gap-3">
            <Button
              variant="ghost"
              onClick={() => window.location.reload()}
              disabled={isSaving}
            >
              {__('Discard Changes', 'prorank-seo')}
            </Button>
            <Button
              variant="primary"
              onClick={handleSave}
              loading={isSaving}
              disabled={isSaving}
            >
              {isSaving ? __('Saving...', 'prorank-seo') : __('Save Changes', 'prorank-seo')}
            </Button>
          </div>
        </Card>
      )}
    </div>
  );
};

export default SiteVerificationTab;
