/**
 * Quick Setup Wizard Component
 *
 * Modern, polished wizard with blue/orange brand colors
 */

import { useState, useEffect, lazy, Suspense } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { useWizardState } from './wizard/hooks/useWizardState';
import WizardProgress from './wizard/components/WizardProgress';
import WizardNavigation from './wizard/components/WizardNavigation';
import LoadingState from '../../components/LoadingState';
import prorankIcon from '../../media/prorank-icon.png';

// Lazy load wizard steps for better performance
const WelcomeStep = lazy(() => import(/* webpackMode: "eager" */ './wizard/steps/WelcomeStep'));
const CompetitorImportStep = lazy(() => import(/* webpackMode: "eager" */ './wizard/steps/CompetitorImportStep'));
const SiteBasicsStep = lazy(() => import(/* webpackMode: "eager" */ './wizard/steps/SiteBasicsStep'));
const ModulesStep = lazy(() => import(/* webpackMode: "eager" */ './wizard/steps/ModulesStep'));
const OptimizationStep = lazy(() => import(/* webpackMode: "eager" */ './wizard/steps/OptimizationStep'));
const ReadyStep = lazy(() => import(/* webpackMode: "eager" */ './wizard/steps/ReadyStep'));


const QuickSetupWizard = () => {
  const {
    currentStep,
    completedSteps,
    wizardData,
    isWizardCompleted,
    goToStep,
    nextStep,
    previousStep,
    markStepCompleted,
    updateWizardData,
    restartWizard,
    completeWizard,
    canNavigateToStep,
    saving,
    lastSaved,
  } = useWizardState();

  const [isProcessing, setIsProcessing] = useState(false);
  const [canGoNext, setCanGoNext] = useState(true);
  const [isRestarting, setIsRestarting] = useState(false);

  // If returning from OAuth, jump to the requested wizard step
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const requestedStep = params.get('wizard_step');
    if (!requestedStep) return;

    const stepMap = {
      welcome: 0,
      import: 1,
      'site-basics': 2,
      modules: 3,
      optimization: 4,
      ready: 5,
    };
    const stepIndex = stepMap[requestedStep];
    if (stepIndex !== undefined && stepIndex !== currentStep) {
      goToStep(stepIndex);
    }

    // Clean up the URL params so a page refresh doesn't keep jumping
    const url = new URL(window.location.href);
    url.searchParams.delete('wizard_step');
    url.searchParams.delete('tab');
    url.searchParams.delete('ga4_success');
    url.searchParams.delete('ga4_error');
    url.searchParams.delete('gsc_connected');
    url.searchParams.delete('gsc_error');
    url.searchParams.delete('context');
    window.history.replaceState({}, '', url.toString());
  }, []); // Run once on mount

  // Define wizard steps
  const wizardSteps = [
    {
      id: 'welcome',
      title: __('Welcome', 'prorank-seo'),
      description: __('Welcome and compatibility check', 'prorank-seo'),
      component: WelcomeStep,
    },
    {
      id: 'import',
      title: __('Import Data', 'prorank-seo'),
      description: __('Import from other SEO plugins', 'prorank-seo'),
      component: CompetitorImportStep,
    },
    {
      id: 'site-basics',
      title: __('Site Basics', 'prorank-seo'),
      description: __('Configure basic site information', 'prorank-seo'),
      component: SiteBasicsStep,
    },
    {
      id: 'modules',
      title: __('Modules', 'prorank-seo'),
      description: __('Choose SEO modules to activate', 'prorank-seo'),
      component: ModulesStep,
    },
    {
      id: 'optimization',
      title: __('Optimization', 'prorank-seo'),
      description: __('Quick optimization settings', 'prorank-seo'),
      component: OptimizationStep,
    },
    {
      id: 'ready',
      title: __('Ready!', 'prorank-seo'),
      description: __('Setup complete', 'prorank-seo'),
      component: ReadyStep,
    },
  ];

  const currentStepData = wizardSteps[currentStep];
  const StepComponent = currentStepData?.component;

  const handleNext = () => {
    if (!canGoNext) {
      return;
    }

    if (currentStep === 2) {
      updateWizardData('siteBasicsCompleted', true);
    }

    markStepCompleted(currentStep);
    if (currentStep < wizardSteps.length - 1) {
      nextStep();
      setCanGoNext(true);
    }
  };

  const handlePrevious = () => {
    previousStep();
  };

  const handleSkip = () => {
    const confirmSkip = window.confirm(__('Skip this step? You can always configure it later.', 'prorank-seo'));
    if (!confirmSkip) return;
    updateWizardData(`step_${currentStep}_skipped`, true);
    handleNext();
  };

  const handleComplete = async () => {
    setIsProcessing(true);
    try {
      await completeWizard();
      window.location.href = '/wp-admin/admin.php?page=prorank-seo';
    } catch (error) {
      // Error is handled by completeWizard
    } finally {
      setIsProcessing(false);
    }
  };

  const handleStepClick = (stepIndex) => {
    if (canNavigateToStep(stepIndex)) {
      goToStep(stepIndex);
      setCanGoNext(true);
    }
  };

  const handleRerunWizard = async () => {
    const confirmed = window.confirm(
      __('Run the setup wizard again? Your existing settings will not be deleted.', 'prorank-seo')
    );
    if (!confirmed) {
      return;
    }

    setIsRestarting(true);
    try {
      await restartWizard();
    } finally {
      setIsRestarting(false);
    }
  };

  if (isWizardCompleted) {
    return (
      <div className="prorank-wizard-shell prorank-wizard-shell--complete">
        <div className="prorank-wizard-complete">
          <div className="prorank-wizard-complete__icon">
            <svg className="pr:w-10 pr:h-10 pr:text-emerald-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
          </div>
          <h2 className="prorank-wizard-complete__title">
            {__('Setup Already Complete', 'prorank-seo')}
          </h2>
          <p className="prorank-wizard-complete__copy">
            {__('The setup wizard has already been completed. You can configure individual settings from the menu.', 'prorank-seo')}
          </p>
          <div className="prorank-wizard-complete__actions">
            <button
              type="button"
              onClick={handleRerunWizard}
              disabled={isRestarting}
              className="prorank-wizard-secondary-btn"
            >
              {isRestarting ? __('Restarting...', 'prorank-seo') : __('Run Wizard Again', 'prorank-seo')}
            </button>
            <a
              href="/wp-admin/admin.php?page=prorank-seo"
              className="prorank-wizard-primary-btn"
              style={{ color: '#fff' }}
            >
              {__('Go to Dashboard', 'prorank-seo')}
            </a>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="prorank-wizard-shell">
      <div className="prorank-wizard-hero">
        <div className="prorank-wizard-hero__content">
          <span className="prorank-wizard-hero__eyebrow">
            {__('Setup Flow', 'prorank-seo')}
          </span>
          <div className="prorank-wizard-hero__brand">
            <img src={prorankIcon} alt="ProRank" className="prorank-wizard-hero__brand-icon" />
            <span>{__('ProRank SEO', 'prorank-seo')}</span>
          </div>
          <h2 className="prorank-wizard-hero__title">
            {__('Quick Setup Wizard', 'prorank-seo')}
          </h2>
          <p className="prorank-wizard-hero__copy">
            {__('Configure the essentials, activate the right modules, and launch with a clean SEO baseline in one guided flow.', 'prorank-seo')}
          </p>
        </div>

        <div className="prorank-wizard-hero__stats">
          <div className="prorank-wizard-hero__stat">
            <span className="prorank-wizard-hero__stat-value">{currentStep + 1}/{wizardSteps.length}</span>
            <span className="prorank-wizard-hero__stat-label">{__('Current Step', 'prorank-seo')}</span>
          </div>
          <div className="prorank-wizard-hero__stat">
            <span className="prorank-wizard-hero__stat-value">{completedSteps.length}</span>
            <span className="prorank-wizard-hero__stat-label">{__('Completed', 'prorank-seo')}</span>
          </div>
          <div className="prorank-wizard-hero__stat">
            <span className="prorank-wizard-hero__stat-value">
              {saving ? __('Saving…', 'prorank-seo') : lastSaved ? __('Saved', 'prorank-seo') : __('Draft', 'prorank-seo')}
            </span>
            <span className="prorank-wizard-hero__stat-label">{__('Autosave', 'prorank-seo')}</span>
          </div>
        </div>
      </div>

      <div className="prorank-wizard-frame">
        <div className="prorank-wizard-frame__intro">
          <div>
            <div className="prorank-wizard-frame__eyebrow">
              {__('Step', 'prorank-seo')} {currentStep + 1}
            </div>
            <h3 className="prorank-wizard-frame__title">{currentStepData?.title}</h3>
            <p className="prorank-wizard-frame__copy">{currentStepData?.description}</p>
          </div>
          <div className="prorank-wizard-frame__pill">
            {Math.round(((currentStep + 1) / wizardSteps.length) * 100)}% {__('complete', 'prorank-seo')}
          </div>
        </div>

        <div className="prorank-wizard-frame__panel">
          {/* Progress */}
          <WizardProgress
            steps={wizardSteps}
            currentStep={currentStep}
            completedSteps={completedSteps}
            onStepClick={handleStepClick}
          />

          {/* Step Content */}
          <div className="prorank-wizard-stage">
            <Suspense fallback={<LoadingState message={__('Loading...', 'prorank-seo')} />}>
              {StepComponent && (
                <StepComponent
                  wizardData={wizardData}
                  updateWizardData={updateWizardData}
                  onNext={handleNext}
                  onComplete={handleComplete}
                  onValidationChange={setCanGoNext}
                />
              )}
            </Suspense>
          </div>

          {/* Navigation */}
          <WizardNavigation
            currentStep={currentStep}
            totalSteps={wizardSteps.length}
            onPrevious={handlePrevious}
            onNext={handleNext}
            onSkip={currentStep < wizardSteps.length - 1 ? handleSkip : null}
            onComplete={handleComplete}
            canGoNext={canGoNext}
            canGoPrevious={currentStep > 0}
            isProcessing={isProcessing}
            isLastStep={currentStep === wizardSteps.length - 1}
            saving={saving}
            lastSaved={lastSaved}
          />
        </div>

        <div className="prorank-wizard-footnote">
          {__('Need help?', 'prorank-seo')}{' '}
          <a
            href="https://prorank.io/docs"
            target="_blank"
            rel="noopener noreferrer"
            className="prorank-wizard-footnote__link"
          >
            {__('View docs', 'prorank-seo')}
          </a>
        </div>
      </div>
    </div>
  );
};

export default QuickSetupWizard;
