/**
 * Welcome Step Component
 *
 * First step of the wizard - welcome message and competitor detection
 */

import { useState, useEffect } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Card, Button, Alert, Badge } from '../../../../components/ui';
import LoadingState from '../../../../components/LoadingState';
import {
  ShieldCheckIcon,
  ExclamationTriangleIcon,
  CheckCircleIcon,
  PuzzlePieceIcon,
  ArrowUpTrayIcon,
  GlobeAltIcon,
  ChartBarIcon,
  CogIcon,
} from '@heroicons/react/24/outline';
import {
  CheckCircleIcon as CheckCircleSolid,
} from '@heroicons/react/24/solid';

const WelcomeStep = ({ wizardData, updateWizardData, onNext, onValidationChange }) => {
  const [competitors, setCompetitors] = useState([]);
  const [loadingCompetitors, setLoadingCompetitors] = useState(true);
  const [deactivating, setDeactivating] = useState(false);
  const [deactivatedPlugins, setDeactivatedPlugins] = useState([]);
  const [error, setError] = useState(null);
  const [systemCheckWarning, setSystemCheckWarning] = useState(null);
  const [competitorCheckWarning, setCompetitorCheckWarning] = useState(null);
  const [loadingSystemInfo, setLoadingSystemInfo] = useState(true);
  const [systemInfo, setSystemInfo] = useState({
    wordpress: { version: '', compatible: true },
    php: { version: '', compatible: true },
    extensions: { status: true, missing: [] },
    memory: { limit: '', available: true }
  });

  useEffect(() => {
    detectCompetitors();
    checkSystemRequirements();
    if (onValidationChange) {
      onValidationChange(true);
    }
  }, []);

  const checkSystemRequirements = async () => {
    setLoadingSystemInfo(true);
    setSystemCheckWarning(null);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/system/info',
      });
      setSystemInfo(response);
    } catch (err) {
      // Set warning and use default values
      setSystemCheckWarning(__('Could not verify system compatibility. Using default values.', 'prorank-seo'));
      setSystemInfo({
        wordpress: { version: __('Unable to detect', 'prorank-seo'), compatible: true },
        php: { version: __('Unable to detect', 'prorank-seo'), compatible: true },
        extensions: { status: true, missing: [] },
        memory: { limit: __('Unable to detect', 'prorank-seo'), available: true }
      });
    } finally {
      setLoadingSystemInfo(false);
    }
  };

  const detectCompetitors = async () => {
    setLoadingCompetitors(true);
    setCompetitorCheckWarning(null);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/system/competitors',
      });
      const detectedCompetitors = response.competitors || [];
      setCompetitors(detectedCompetitors);
      updateWizardData('detectedCompetitors', detectedCompetitors);
      return detectedCompetitors;
    } catch (err) {
      // Show warning that competitor check failed
      setCompetitorCheckWarning(__('Could not scan for other SEO plugins. You may need to check manually.', 'prorank-seo'));
      setCompetitors([]);
      return [];
    } finally {
      setLoadingCompetitors(false);
    }
  };

  const handleDeactivateCompetitors = async () => {
    setDeactivating(true);
    setError(null);

    try {
      const activeCompetitors = competitors.filter((plugin) => plugin.active === true);
      const failedPlugins = [];

      for (const competitor of activeCompetitors) {
        try {
          const response = await apiFetch({
            path: `/wp/v2/plugins/${encodeURIComponent(competitor.file)}`,
            method: 'POST',
            data: { status: 'inactive' },
          });

          if (response?.status !== 'inactive') {
            failedPlugins.push(competitor.name);
          }
        } catch (err) {
          failedPlugins.push(competitor.name);
        }
      }

      const refreshedCompetitors = await detectCompetitors();
      const confirmedDeactivated = activeCompetitors
        .filter((plugin) => !refreshedCompetitors.some((candidate) => candidate.file === plugin.file && candidate.active === true))
        .map((plugin) => plugin.name);

      setDeactivatedPlugins(confirmedDeactivated);
      updateWizardData('deactivatedCompetitors', confirmedDeactivated);

      const stillActive = activeCompetitors
        .filter((plugin) => refreshedCompetitors.some((candidate) => candidate.file === plugin.file && candidate.active === true))
        .map((plugin) => plugin.name);

      const unresolvedPlugins = Array.from(new Set([...failedPlugins, ...stillActive]));
      if (unresolvedPlugins.length > 0) {
        setError(__('Some plugins could not be deactivated automatically. Please deactivate them manually.', 'prorank-seo'));
      }
    } catch (err) {
      setError(__('Some plugins could not be deactivated. Please deactivate them manually.', 'prorank-seo'));
    } finally {
      setDeactivating(false);
    }
  };

  const features = [
    {
      icon: ArrowUpTrayIcon,
      title: __('Import Existing SEO Data', 'prorank-seo'),
      description: __('Seamlessly transfer your SEO settings from other plugins', 'prorank-seo')
    },
    {
      icon: ShieldCheckIcon,
      title: __('Site Verification', 'prorank-seo'),
      description: __('Set up Google, Bing, and other search engine verifications', 'prorank-seo')
    },
    {
      icon: ChartBarIcon,
      title: __('Analytics Integration', 'prorank-seo'),
      description: __('Connect Google Analytics 4 and Search Console', 'prorank-seo')
    },
    {
      icon: CogIcon,
      title: __('Smart Optimizations', 'prorank-seo'),
      description: __('Apply SEO best practices with one-click optimizations', 'prorank-seo')
    },
    {
      icon: GlobeAltIcon,
      title: __('Schema & Rich Snippets', 'prorank-seo'),
      description: __('Enable structured data for better search visibility', 'prorank-seo')
    }
  ];

  const activeCompetitors = competitors.filter((plugin) => plugin.active === true);
  const inactiveImportable = competitors.filter((plugin) => plugin.active === false && plugin.has_data);

  return (
    <div className="pr:space-y-4">
      {/* Hero Section */}
      <div className="pr:text-center pr:py-4">
        <div className="pr:inline-flex pr:items-center pr:justify-center pr:w-14 pr:h-14 pr:mb-3">
          <svg width="56" height="56" viewBox="0 0 24 24" fill="none">
            <path d="M12 2L2 7L12 12L22 7L12 2Z" fill="url(#gradient1)" />
            <path d="M2 17L12 22L22 17" stroke="url(#gradient2)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            <path d="M2 12L12 17L22 12" stroke="url(#gradient2)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            <defs>
              <linearGradient id="gradient1" x1="2" y1="2" x2="22" y2="22">
                <stop stopColor="#3b82f6" />
                <stop offset="1" stopColor="#2563eb" />
              </linearGradient>
              <linearGradient id="gradient2" x1="2" y1="2" x2="22" y2="22">
                <stop stopColor="#3b82f6" />
                <stop offset="1" stopColor="#2563eb" />
              </linearGradient>
            </defs>
          </svg>
        </div>

        <h1 className="pr:text-2xl pr:font-bold pr:text-gray-900 pr:mb-2">
          {__('Welcome to ProRank SEO', 'prorank-seo')}
        </h1>

        <p className="pr:text-base pr:text-gray-600 pr:max-w-xl pr:mx-auto pr:mb-4">
          {__('Let\'s optimize your site for search engines in just a few minutes.', 'prorank-seo')}
        </p>

        <div className="pr:flex pr:flex-wrap pr:items-center pr:justify-center pr:gap-2">
          <Badge variant="success" size="md">
            <CheckCircleSolid className="pr:w-4 pr:h-4" />
            {__('5-Minute Setup', 'prorank-seo')}
          </Badge>
          <Badge variant="success" size="md">
            <CheckCircleSolid className="pr:w-4 pr:h-4" />
            {__('No Technical Knowledge Required', 'prorank-seo')}
          </Badge>
          <Badge variant="success" size="md">
            <CheckCircleSolid className="pr:w-4 pr:h-4" />
            {__('Import from Other Plugins', 'prorank-seo')}
          </Badge>
        </div>
      </div>

      {/* System Status Card */}
      <Card variant="elevated">
        <div className="pr:flex pr:items-start pr:gap-3 pr:mb-4">
          <div className="pr:p-2 pr:bg-primary-100 pr:rounded-lg">
            <ShieldCheckIcon className="pr:w-5 pr:h-5 pr:text-primary-600" />
          </div>
          <div className="pr:flex-1">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900 pr:mb-1">
              {__('System Compatibility', 'prorank-seo')}
            </h3>
            <p className="pr:text-sm pr:text-gray-600">
              {loadingSystemInfo
                ? __('Checking your site\'s compatibility...', 'prorank-seo')
                : __('Your site\'s compatibility with ProRank SEO', 'prorank-seo')
              }
            </p>
          </div>
        </div>

        {/* System Check Warning */}
        {systemCheckWarning && (
          <Alert variant="warning" className="pr:mb-4" isDismissible onDismiss={() => setSystemCheckWarning(null)}>
            <div className="pr:flex pr:items-center pr:gap-2">
              <ExclamationTriangleIcon className="pr:w-5 pr:h-5 pr:text-warning-600 pr:shrink-0" />
              <span>{systemCheckWarning}</span>
              <Button
                variant="link"
                size="sm"
                onClick={checkSystemRequirements}
                className="pr:ml-auto pr:text-warning-700 pr:hover:text-warning-800"
              >
                {__('Retry', 'prorank-seo')}
              </Button>
            </div>
          </Alert>
        )}

        {loadingSystemInfo ? (
          <LoadingState message={__('Checking system requirements...', 'prorank-seo')} />
        ) : (
        <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:gap-4">
          <div className={`pr:flex pr:items-center pr:gap-3 pr:p-4 pr:rounded-lg pr:border ${systemInfo.wordpress.compatible ? 'pr:border-success-200 pr:bg-success-50' : 'pr:border-warning-200 pr:bg-warning-50'}`}>
            <div className={`pr:p-2 pr:rounded-lg ${systemInfo.wordpress.compatible ? 'pr:bg-success-100' : 'pr:bg-warning-100'}`}>
              {systemInfo.wordpress.compatible ? (
                <CheckCircleIcon className="pr:w-5 pr:h-5 pr:text-success-600" />
              ) : (
                <ExclamationTriangleIcon className="pr:w-5 pr:h-5 pr:text-warning-600" />
              )}
            </div>
            <div>
              <div className="pr:text-sm pr:font-medium pr:text-gray-700">{__('WordPress', 'prorank-seo')}</div>
              <div className="pr:text-sm pr:text-gray-600">{systemInfo.wordpress.version || 'Compatible'}</div>
            </div>
          </div>

          <div className={`pr:flex pr:items-center pr:gap-3 pr:p-4 pr:rounded-lg pr:border ${systemInfo.php.compatible ? 'pr:border-success-200 pr:bg-success-50' : 'pr:border-warning-200 pr:bg-warning-50'}`}>
            <div className={`pr:p-2 pr:rounded-lg ${systemInfo.php.compatible ? 'pr:bg-success-100' : 'pr:bg-warning-100'}`}>
              {systemInfo.php.compatible ? (
                <CheckCircleIcon className="pr:w-5 pr:h-5 pr:text-success-600" />
              ) : (
                <ExclamationTriangleIcon className="pr:w-5 pr:h-5 pr:text-warning-600" />
              )}
            </div>
            <div>
              <div className="pr:text-sm pr:font-medium pr:text-gray-700">{__('PHP Version', 'prorank-seo')}</div>
              <div className="pr:text-sm pr:text-gray-600">{systemInfo.php.version || 'Compatible'}</div>
            </div>
          </div>

          <div className={`pr:flex pr:items-center pr:gap-3 pr:p-4 pr:rounded-lg pr:border ${systemInfo.extensions.status ? 'pr:border-success-200 pr:bg-success-50' : 'pr:border-warning-200 pr:bg-warning-50'}`}>
            <div className={`pr:p-2 pr:rounded-lg ${systemInfo.extensions.status ? 'pr:bg-success-100' : 'pr:bg-warning-100'}`}>
              {systemInfo.extensions.status ? (
                <CheckCircleIcon className="pr:w-5 pr:h-5 pr:text-success-600" />
              ) : (
                <ExclamationTriangleIcon className="pr:w-5 pr:h-5 pr:text-warning-600" />
              )}
            </div>
            <div>
              <div className="pr:text-sm pr:font-medium pr:text-gray-700">{__('Extensions', 'prorank-seo')}</div>
              <div className="pr:text-sm pr:text-gray-600">
                {systemInfo.extensions.status ? __('All Ready', 'prorank-seo') : __('Some Missing', 'prorank-seo')}
              </div>
            </div>
          </div>

          <div className={`pr:flex pr:items-center pr:gap-3 pr:p-4 pr:rounded-lg pr:border ${systemInfo.memory.available ? 'pr:border-success-200 pr:bg-success-50' : 'pr:border-warning-200 pr:bg-warning-50'}`}>
            <div className={`pr:p-2 pr:rounded-lg ${systemInfo.memory.available ? 'pr:bg-success-100' : 'pr:bg-warning-100'}`}>
              {systemInfo.memory.available ? (
                <CheckCircleIcon className="pr:w-5 pr:h-5 pr:text-success-600" />
              ) : (
                <ExclamationTriangleIcon className="pr:w-5 pr:h-5 pr:text-warning-600" />
              )}
            </div>
            <div>
              <div className="pr:text-sm pr:font-medium pr:text-gray-700">{__('Memory', 'prorank-seo')}</div>
              <div className="pr:text-sm pr:text-gray-600">{systemInfo.memory.limit || 'Sufficient'}</div>
            </div>
          </div>
        </div>
        )}
      </Card>

      {/* Competitor Detection Card */}
      <Card variant="elevated">
        <div className="pr:flex pr:items-start pr:gap-3 pr:mb-4">
          <div className="pr:p-2 pr:bg-warning-100 pr:rounded-lg">
            <PuzzlePieceIcon className="pr:w-5 pr:h-5 pr:text-warning-600" />
          </div>
          <div className="pr:flex-1">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900 pr:mb-1">
              {__('SEO Plugin Compatibility', 'prorank-seo')}
            </h3>
            <p className="pr:text-sm pr:text-gray-600">
              {__('Checking for other SEO plugins that might conflict', 'prorank-seo')}
            </p>
          </div>
        </div>

        {/* Competitor Check Warning */}
        {competitorCheckWarning && (
          <Alert variant="warning" className="pr:mb-4" isDismissible onDismiss={() => setCompetitorCheckWarning(null)}>
            <div className="pr:flex pr:items-center pr:gap-2">
              <ExclamationTriangleIcon className="pr:w-5 pr:h-5 pr:text-warning-600 pr:shrink-0" />
              <span>{competitorCheckWarning}</span>
              <Button
                variant="link"
                size="sm"
                onClick={detectCompetitors}
                className="pr:ml-auto pr:text-warning-700 pr:hover:text-warning-800"
              >
                {__('Retry', 'prorank-seo')}
              </Button>
            </div>
          </Alert>
        )}

        {loadingCompetitors ? (
          <LoadingState message={__('Scanning for other SEO plugins...', 'prorank-seo')} />
        ) : activeCompetitors.length > 0 ? (
          <div className="pr:space-y-4">
            <Alert variant="warning" title={__('Potential conflicts detected:', 'prorank-seo')}>
              {__('We found other SEO plugins that should be deactivated to avoid conflicts.', 'prorank-seo')}
            </Alert>

            <div className="pr:space-y-2">
              {activeCompetitors.map((plugin) => (
                <div key={plugin.file} className="pr:flex pr:items-center pr:justify-between pr:p-4 pr:bg-gray-50 pr:rounded-lg pr:border pr:border-gray-200">
                  <div className="pr:flex pr:items-center pr:gap-3">
                    <ExclamationTriangleIcon className="pr:w-5 pr:h-5 pr:text-warning-600" />
                    <span className="pr:text-sm pr:font-medium pr:text-gray-900">{plugin.name}</span>
                  </div>
                  {deactivatedPlugins.includes(plugin.name) && (
                    <Badge variant="success" size="sm">
                      <CheckCircleIcon className="pr:w-3 pr:h-3" />
                      {__('Deactivated', 'prorank-seo')}
                    </Badge>
                  )}
                </div>
              ))}
            </div>

            {deactivatedPlugins.length === 0 && (
              <div className="pr:space-y-3">
                <Button
                  variant="secondary"
                  onClick={handleDeactivateCompetitors}
                  loading={deactivating}
                  disabled={deactivating}
                  className="pr:w-full"
                >
                  {deactivating
                    ? __('Deactivating Plugins...', 'prorank-seo')
                    : __('Deactivate Conflicting Plugins', 'prorank-seo')
                  }
                </Button>

                <div className="pr:flex pr:items-center pr:gap-2 pr:justify-center pr:text-sm pr:text-gray-600">
                  <ShieldCheckIcon className="pr:w-4 pr:h-4" />
                  <span>{__('Don\'t worry! Your SEO data is safe. You can import it in the next step.', 'prorank-seo')}</span>
                </div>
              </div>
            )}

            {deactivatedPlugins.length > 0 && (
              <Alert variant="success" title={__('Perfect! Conflicting plugins have been deactivated.', 'prorank-seo')}>
                {__('Your SEO data is preserved and ready to import.', 'prorank-seo')}
              </Alert>
            )}
          </div>
        ) : inactiveImportable.length > 0 ? (
          <div className="pr:space-y-4">
            <Alert variant="info" title={__('No active conflicts found', 'prorank-seo')}>
              {__('We found SEO data from previously used plugins. You can import it in the next step.', 'prorank-seo')}
            </Alert>

            <div className="pr:space-y-2">
              {inactiveImportable.map((plugin) => (
                <div key={plugin.file} className="pr:flex pr:items-center pr:justify-between pr:p-4 pr:bg-gray-50 pr:rounded-lg pr:border pr:border-gray-200">
                  <div className="pr:flex pr:items-center pr:gap-3">
                    <CheckCircleIcon className="pr:w-5 pr:h-5 pr:text-success-600" />
                    <span className="pr:text-sm pr:font-medium pr:text-gray-900">{plugin.name}</span>
                  </div>
                  <Badge variant="warning" size="sm">
                    {__('Deactivated - data found', 'prorank-seo')}
                  </Badge>
                </div>
              ))}
            </div>
          </div>
        ) : (
          <div className="pr:text-center pr:py-8">
            <div className="pr:inline-flex pr:items-center pr:justify-center pr:w-16 pr:h-16 pr:bg-success-100 pr:rounded-full pr:mb-4">
              <CheckCircleIcon className="pr:w-10 pr:h-10 pr:text-success-600" />
            </div>
            <h4 className="pr:text-lg pr:font-semibold pr:text-gray-900 pr:mb-2">{__('All Clear!', 'prorank-seo')}</h4>
            <p className="pr:text-sm pr:text-gray-600">{__('No conflicting SEO plugins detected. You\'re ready to proceed.', 'prorank-seo')}</p>
          </div>
        )}

        {error && (
          <Alert variant="info" className="pr:mt-4">
            {error}
          </Alert>
        )}
      </Card>

      {/* Features Preview */}
      <Card variant="elevated">
        <h3 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-1">
          {__('What We\'ll Set Up', 'prorank-seo')}
        </h3>
        <p className="pr:text-sm pr:text-gray-600 pr:mb-4">
          {__('Essential configurations for your site:', 'prorank-seo')}
        </p>

        <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:gap-2 pr:mb-3">
          {features.map((feature, index) => {
            const IconComponent = feature.icon;
            return (
              <div key={index} className="pr:flex pr:items-center pr:gap-3 pr:p-3 pr:bg-gray-50 pr:rounded-lg">
                <div className="pr:p-1.5 pr:bg-primary-100 pr:rounded-md">
                  <IconComponent className="pr:w-4 pr:h-4 pr:text-primary-600" />
                </div>
                <div className="pr:flex-1">
                  <h4 className="pr:text-sm pr:font-medium pr:text-gray-900">{feature.title}</h4>
                  <p className="pr:text-xs pr:text-gray-500">{feature.description}</p>
                </div>
              </div>
            );
          })}
        </div>

        <div className="pr:flex pr:items-center pr:gap-2 pr:justify-center pr:text-xs pr:text-gray-500 pr:p-2 pr:bg-gray-100 pr:rounded-md">
          <CheckCircleIcon className="pr:w-3.5 pr:h-3.5 pr:text-gray-400" />
          <span>{__('5 min setup • Skip any step • Configure later', 'prorank-seo')}</span>
        </div>
      </Card>
    </div>
  );
};

export default WelcomeStep;
