/**
 * Site Basics Step Component
 *
 * Integrates existing Site Basics settings into the wizard
 * with validation for required fields and proper error handling
 */

import { useState, useCallback, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Card, Alert } from '../../../../components/ui';
import { ExclamationTriangleIcon } from '@heroicons/react/24/outline';

// Import existing Site Basics components
import SiteInfoTab from '../../../../settings/OnPageSEO/SiteBasics/tabs/SiteInfoTab';
import SiteVerificationTab from '../../../../settings/OnPageSEO/SiteBasics/tabs/SiteVerificationTab';
import SocialProfilesTab from '../../../../settings/OnPageSEO/SiteBasics/tabs/SocialProfilesTab';
import OrganizationTab from '../../../../settings/OnPageSEO/SiteBasics/tabs/OrganizationTab';

const normalizeDetectedSiteBasics = (payload = {}) => {
  if (!payload || typeof payload !== 'object') {
    return {};
  }

  const normalized = { ...payload };

  if (!normalized.org_or_person && normalized.site_representation) {
    normalized.org_or_person = normalized.site_representation;
  }
  if (!normalized.org_name && normalized.organization_name) {
    normalized.org_name = normalized.organization_name;
  }
  if (!normalized.org_logo && normalized.organization_logo) {
    normalized.org_logo = normalized.organization_logo;
  }

  return normalized;
};

const SiteBasicsStep = ({ wizardData, updateWizardData, onNext, onValidationChange }) => {
  const [activeTab, setActiveTab] = useState('site-info');
  const [errors, setErrors] = useState({});
  const [showValidationError, setShowValidationError] = useState(false);
  const [settings, setSettings] = useState({
    // Site Info
    site_name: wizardData.site_name || '',
    site_alternate_name: wizardData.site_alternate_name || '',
    site_tagline: wizardData.site_tagline || '',
    title_separator: wizardData.title_separator || '-',
    site_logo: wizardData.site_logo || '',
    site_image: wizardData.site_image || '',

    // Verification
    google_verification: wizardData.google_verification || '',
    bing_verification: wizardData.bing_verification || '',
    baidu_verification: wizardData.baidu_verification || '',
    yandex_verification: wizardData.yandex_verification || '',
    pinterest_verification: wizardData.pinterest_verification || '',

    // Social Profiles
    facebook_page_url: wizardData.facebook_page_url || '',
    twitter_username: wizardData.twitter_username || '',
    linkedin_url: wizardData.linkedin_url || '',
    instagram_url: wizardData.instagram_url || '',
    youtube_url: wizardData.youtube_url || '',

    // Organization
    org_or_person: wizardData.org_or_person || wizardData.site_representation || 'organization',
    org_name: wizardData.org_name || wizardData.organization_name || '',
    org_logo: wizardData.org_logo || wizardData.organization_logo || '',
  });

  // Auto-detect site basics from deactivated competitor plugins
  const [detectedSource, setDetectedSource] = useState(null);
  useEffect(() => {
    const mergeIncomingSettings = (incomingSettings = {}, onlyFillEmpty = false) => {
      if (!incomingSettings || typeof incomingSettings !== 'object') {
        return;
      }

      setSettings((prev) => {
        const updates = {};

        Object.entries(incomingSettings).forEach(([key, value]) => {
          const hasValue = Array.isArray(value)
            ? value.length > 0
            : value !== undefined && value !== null && value !== '';

          if (!hasValue) {
            return;
          }

          const currentValue = prev[key];
          const hasCurrentValue = Array.isArray(currentValue)
            ? currentValue.length > 0
            : currentValue !== undefined && currentValue !== null && currentValue !== '';

          if (!onlyFillEmpty || !hasCurrentValue) {
            updates[key] = value;
          }
        });

        Object.entries(updates).forEach(([key, value]) => {
          updateWizardData(key, value);
        });

        return Object.keys(updates).length > 0 ? { ...prev, ...updates } : prev;
      });
    };

    const loadCurrentSiteBasics = async () => {
      try {
        const response = await apiFetch({
          path: '/prorank-seo/v1/settings/site_basics',
        });

        if (response?.settings) {
          mergeIncomingSettings(normalizeDetectedSiteBasics(response.settings), true);
        }
      } catch {
        // Silent — the wizard can still continue with manual entry.
      }
    };

    const fetchCompetitorData = async () => {
      try {
        const response = await apiFetch({
          path: '/prorank-seo/v1/system/competitor-site-data',
        });
        if (response?.success && response.data) {
          const detected = normalizeDetectedSiteBasics(response.data);
          setDetectedSource(response.source);
          mergeIncomingSettings(detected, true);
        }
      } catch {
        // Silent — fields stay empty for manual entry
      }
    };

    loadCurrentSiteBasics().then(fetchCompetitorData);
  }, []);

  const updateSettings = (updates) => {
    const newSettings = { ...settings, ...updates };
    setSettings(newSettings);
    // Clear errors when user makes changes
    if (showValidationError) {
      setShowValidationError(false);
    }
    // Update wizard data
    Object.keys(updates).forEach(key => {
      updateWizardData(key, updates[key]);
    });
  };

  // URL validation helper
  const isValidUrl = (url) => {
    if (!url) return true; // Empty URLs are valid (optional fields)
    try {
      new URL(url);
      return true;
    } catch {
      return false;
    }
  };

  // Verification code validation (alphanumeric with dashes/underscores)
  const isValidVerificationCode = (code) => {
    if (!code) return true; // Empty is valid (optional)
    return /^[a-zA-Z0-9_-]+$/.test(code);
  };

  // Validate all fields
  const validateForm = useCallback(() => {
    const newErrors = {};

    // Required: Site name
    if (!settings.site_name?.trim()) {
      newErrors.site_name = __('Website name is required', 'prorank-seo');
    }

    // Optional but validate format: Social URLs
    const urlFields = [
      { key: 'facebook_page_url', label: 'Facebook' },
      { key: 'linkedin_url', label: 'LinkedIn' },
      { key: 'instagram_url', label: 'Instagram' },
      { key: 'youtube_url', label: 'YouTube' },
    ];

    urlFields.forEach(({ key, label }) => {
      if (settings[key] && !isValidUrl(settings[key])) {
        newErrors[key] = __(`Invalid ${label} URL format`, 'prorank-seo');
      }
    });

    // Validate Twitter username (should not start with @)
    if (settings.twitter_username?.startsWith('@')) {
      // Auto-fix: remove @ prefix
      updateSettings({ twitter_username: settings.twitter_username.slice(1) });
    }

    // Validate verification codes format
    const verificationFields = [
      { key: 'google_verification', label: 'Google' },
      { key: 'bing_verification', label: 'Bing' },
      { key: 'baidu_verification', label: 'Baidu' },
      { key: 'yandex_verification', label: 'Yandex' },
      { key: 'pinterest_verification', label: 'Pinterest' },
    ];

    verificationFields.forEach(({ key, label }) => {
      if (settings[key] && !isValidVerificationCode(settings[key])) {
        newErrors[key] = __(`Invalid ${label} verification code format`, 'prorank-seo');
      }
    });

    // Organization validation
    if (settings.org_or_person === 'organization' && !settings.org_name?.trim()) {
      newErrors.org_name = __('Organization name is required when representing as organization', 'prorank-seo');
    }

    setErrors(newErrors);
    const isValid = Object.keys(newErrors).length === 0;

    // Notify parent about validation state
    if (onValidationChange) {
      onValidationChange(isValid);
    }

    return isValid;
  }, [settings, onValidationChange]);

  // Handle proceeding to next step with validation
  const handleNext = useCallback(() => {
    if (validateForm()) {
      updateWizardData('siteBasicsCompleted', true);
      onNext?.();
    } else {
      setShowValidationError(true);
      // Scroll to top to show error
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  }, [validateForm, updateWizardData, onNext]);

  const saveSettings = async (data) => {
    // In wizard mode, we just store the data
    // Actual saving happens at the end
    return true;
  };

  // Check which tabs have errors
  const tabHasError = {
    'site-info': !!(errors.site_name),
    'verification': !!(errors.google_verification || errors.bing_verification || errors.baidu_verification || errors.yandex_verification || errors.pinterest_verification),
    'social': !!(errors.facebook_page_url || errors.linkedin_url || errors.instagram_url || errors.youtube_url || errors.twitter_username),
    'organization': !!(errors.org_name),
  };

  const tabs = [
    {
      name: 'site-info',
      title: __('Site Information', 'prorank-seo'),
      hasError: tabHasError['site-info'],
      content: (
        <SiteInfoTab
          settings={settings}
          updateSettings={updateSettings}
          saveSettings={saveSettings}
          errors={errors}
        />
      ),
    },
    {
      name: 'verification',
      title: __('Verification', 'prorank-seo'),
      hasError: tabHasError['verification'],
      content: (
        <SiteVerificationTab
          settings={settings}
          updateSettings={updateSettings}
          saveSettings={saveSettings}
          errors={errors}
        />
      ),
    },
    {
      name: 'social',
      title: __('Social Profiles', 'prorank-seo'),
      hasError: tabHasError['social'],
      content: (
        <SocialProfilesTab
          settings={settings}
          updateSettings={updateSettings}
          saveSettings={saveSettings}
          errors={errors}
        />
      ),
    },
    {
      name: 'organization',
      title: __('Organization', 'prorank-seo'),
      hasError: tabHasError['organization'],
      content: (
        <OrganizationTab
          settings={settings}
          updateSettings={updateSettings}
          saveSettings={saveSettings}
          errors={errors}
        />
      ),
    },
  ];

  const currentTab = tabs.find(tab => tab.name === activeTab) || tabs[0];

  // Expose handleNext for parent component to call
  const stepRef = { handleNext };

  return (
    <div className="pr:space-y-6">
      <div className="pr:text-center">
        <h2 className="pr:text-2xl pr:font-semibold pr:text-gray-900 pr:mb-2">
          {__('Site Basics Configuration', 'prorank-seo')}
        </h2>
        <p className="pr:text-sm pr:text-gray-600 pr:max-w-2xl pr:mx-auto">
          {__('Configure your site information, verification codes, and social profiles. These settings are essential for search engines to understand your website.', 'prorank-seo')}
        </p>
      </div>

      {/* Auto-detected data notification */}
      {detectedSource && (
        <Alert variant="success">
          {__('We auto-filled some fields from your previous SEO plugin settings. Please review and adjust as needed.', 'prorank-seo')}
        </Alert>
      )}

      {/* Validation Error Alert */}
      {showValidationError && Object.keys(errors).length > 0 && (
        <Alert variant="error" className="pr:animate-shake">
          <div className="pr:flex pr:items-start pr:gap-3">
            <ExclamationTriangleIcon className="pr:w-5 pr:h-5 pr:text-red-500 pr:shrink-0 pr:mt-0.5" />
            <div>
              <h4 className="pr:font-semibold pr:text-red-800 pr:mb-1">
                {__('Please fix the following issues:', 'prorank-seo')}
              </h4>
              <ul className="pr:list-disc pr:list-inside pr:text-sm pr:text-red-700 pr:space-y-1">
                {Object.entries(errors).map(([key, message]) => (
                  <li key={key}>{message}</li>
                ))}
              </ul>
            </div>
          </div>
        </Alert>
      )}

      <Card variant="elevated">
        {/* Tab Navigation */}
        <div className="pr:border-b pr:border-gray-200">
          <nav className="pr:flex pr:flex-wrap pr:gap-2 pr:-mb-px" role="tablist">
            {tabs.map((tab) => (
              <button
                key={tab.name}
                onClick={() => setActiveTab(tab.name)}
                role="tab"
                aria-selected={activeTab === tab.name}
                aria-controls={`tabpanel-${tab.name}`}
                className={`
                  pr:px-4 pr:py-3 pr:text-sm pr:font-medium pr:border-b-2 pr:transition-colors pr:flex pr:items-center pr:gap-2
                  ${activeTab === tab.name
                    ? 'pr:border-primary-500 pr:text-primary-600'
                    : 'pr:border-transparent pr:text-gray-600 pr:hover:text-gray-900 pr:hover:border-gray-300'
                  }
                  ${tab.hasError ? 'pr:text-red-600' : ''}
                `}
                type="button"
              >
                {tab.title}
                {tab.hasError && (
                  <span className="pr:w-2 pr:h-2 pr:bg-red-500 pr:rounded-full" title={__('Has validation errors', 'prorank-seo')} />
                )}
              </button>
            ))}
          </nav>
        </div>

        {/* Tab Content */}
        <div className="pr:pt-6">
          {currentTab.content}
        </div>
      </Card>

      <Alert variant="info">
        {__('Tip: You can skip any section and configure it later from the On-Page SEO settings.', 'prorank-seo')}
      </Alert>
    </div>
  );
};

export default SiteBasicsStep;
