/**
 * Competitor Import Step Component
 *
 * Allows importing data from competitor SEO plugins
 */

import { useState, useEffect } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Card, Alert, Button } from '../../../../components/ui';
import {
  ArrowDownTrayIcon,
  ArchiveBoxIcon,
  LinkIcon,
  CodeBracketIcon,
  UserGroupIcon,
} from '@heroicons/react/24/outline';

const CompetitorImportStep = ({ wizardData, updateWizardData, onNext }) => {
  const [availableImports, setAvailableImports] = useState([]);
  const [selectedImports, setSelectedImports] = useState({});
  const [importing, setImporting] = useState(false);
  const [importProgress, setImportProgress] = useState(0);
  const [importStatus, setImportStatus] = useState('');
  const [importResults, setImportResults] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    checkAvailableImports();
  }, []);

  const checkAvailableImports = async () => {
    try {
      // Fetch fresh competitor data from the API instead of relying on
      // potentially stale wizardData (which may have been cached before
      // deactivated-plugin detection was added).
      let plugins = wizardData.detectedCompetitors || [];
      try {
        const response = await apiFetch({
          path: '/prorank-seo/v1/system/competitors',
        });
        if (response.importable && response.importable.length > 0) {
          plugins = response.importable;
          updateWizardData('detectedCompetitors', response.competitors || []);
        }
      } catch {
        // Fall back to cached wizardData
      }
      const available = [];

      for (const plugin of plugins) {
        // Map plugin names to import keys
        let importKey = '';
        if (plugin.name.includes('Yoast')) importKey = 'yoast';
        else if (plugin.name.includes('Rank Math')) importKey = 'rankmath';
        else if (plugin.name.includes('All in One SEO')) importKey = 'aioseo';
        else if (plugin.name.includes('SEOPress')) importKey = 'seopress';

        if (importKey) {
          available.push({
            key: importKey,
            name: plugin.name,
            description: getImportDescription(importKey),
            icon: getImportIcon(importKey),
            active: plugin.active !== false,
            hasData: !!plugin.has_data,
          });
        }
      }

      setAvailableImports(available);

      // Auto-select first available import
      if (available.length > 0) {
        const initial = {};
        initial[available[0].key] = true;
        setSelectedImports(initial);
      }
    } catch (err) {
      // Error handled silently
    }
  };

  const getImportDescription = (key) => {
    const descriptions = {
      yoast: __('Import all SEO settings, meta data, redirects, and schema markup from Yoast SEO', 'prorank-seo'),
      rankmath: __('Import all SEO settings, meta data, redirects, and schema markup from Rank Math', 'prorank-seo'),
      aioseo: __('Import SEO settings, meta data, and social profiles from All in One SEO', 'prorank-seo'),
      seopress: __('Import titles, descriptions, and social media settings from SEOPress', 'prorank-seo'),
    };
    return descriptions[key] || '';
  };

  const getImportIcon = (key) => {
    const icons = {
      yoast: ArchiveBoxIcon,
      rankmath: CodeBracketIcon,
      aioseo: LinkIcon,
      seopress: UserGroupIcon,
    };
    return icons[key] || ArchiveBoxIcon;
  };

  const handleImport = async () => {
    const selectedPlugins = Object.keys(selectedImports).filter(key => selectedImports[key]);

    if (selectedPlugins.length === 0) {
      setError(__('Please select at least one plugin to import from', 'prorank-seo'));
      return;
    }

    setImporting(true);
    setError(null);
    setImportProgress(0);
    setImportResults(null);

    try {
      const totalPlugins = selectedPlugins.length;
      let currentPlugin = 0;
      const results = {};

      for (const pluginKey of selectedPlugins) {
        currentPlugin++;
        setImportStatus(__(`Importing from ${pluginKey}...`, 'prorank-seo'));
        setImportProgress((currentPlugin - 1) / totalPlugins * 100);

        const response = await apiFetch({
          path: '/prorank-seo/v1/import-export/competitor',
          method: 'POST',
          data: {
            source: pluginKey,
            types: ['meta', 'settings', 'redirects', 'schema', 'locations'], // Import all types
          },
        });

        results[pluginKey] = response;
        setImportProgress(currentPlugin / totalPlugins * 100);
      }

      setImportResults(results);
      updateWizardData('importResults', results);
      setImportStatus(__('Import completed successfully!', 'prorank-seo'));
    } catch (err) {
      setError(err.message || __('Import failed. Please try again.', 'prorank-seo'));
      setImportProgress(0);
    } finally {
      setImporting(false);
    }
  };

  const handleSkip = () => {
    updateWizardData('skippedImport', true);
    onNext();
  };

  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">
          {__('Import SEO Data', 'prorank-seo')}
        </h2>
        <p className="pr:text-sm pr:text-gray-600">
          {__('Import your existing SEO data from other plugins. This ensures a smooth transition without losing your SEO work.', 'prorank-seo')}
        </p>
      </div>

      {availableImports.length > 0 ? (
        <div className="pr:space-y-6">
          <Card variant="elevated">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900 pr:mb-2">
              {__('Available Imports', 'prorank-seo')}
            </h3>
            <p className="pr:text-sm pr:text-gray-600 pr:mb-4">
              {__('Select the plugins you want to import data from:', 'prorank-seo')}
            </p>

            <div className="pr:space-y-3">
              {availableImports.map((plugin) => {
                const IconComponent = plugin.icon;
                const isSelected = selectedImports[plugin.key] || false;

                return (
                  <label
                    key={plugin.key}
                    className={`pr:flex pr:items-start pr:gap-4 pr:p-4 pr:rounded-lg pr:border pr:cursor-pointer pr:transition-all ${
                      isSelected
                        ? 'pr:border-primary-500 pr:bg-primary-50'
                        : 'pr:border-gray-200 pr:bg-white pr:hover:border-gray-300'
                    } ${importing ? 'pr:opacity-60 pr:cursor-not-allowed' : ''}`}
                  >
                    <input
                      type="checkbox"
                      checked={isSelected}
                      onChange={(value) => {
                        const checked = value?.target ? value.target.checked : !!value;
                        setSelectedImports({
                          ...selectedImports,
                          [plugin.key]: checked,
                        });
                      }}
                      disabled={importing}
                      className="pr:w-5 pr:h-5 pr:text-primary-600 pr:rounded-xs pr:border-gray-300 pr:focus:ring-primary-500 pr:mt-0.5"
                    />
                    <div className="pr:p-2 pr:bg-gray-100 pr:rounded-lg">
                      <IconComponent className="pr:w-6 pr:h-6 pr:text-gray-600" />
                    </div>
                    <div className="pr:flex-1">
                      <div className="pr:font-semibold pr:text-gray-900 pr:mb-1">
                        {plugin.name}
                        {!plugin.active && plugin.hasData && (
                          <span className="pr:ml-2 pr:text-xs pr:font-normal pr:text-amber-600 pr:bg-amber-50 pr:px-2 pr:py-0.5 pr:rounded-full">
                            {__('deactivated — data found', 'prorank-seo')}
                          </span>
                        )}
                      </div>
                      <div className="pr:text-sm pr:text-gray-600">{plugin.description}</div>
                    </div>
                  </label>
                );
              })}
            </div>
          </Card>

          <Card variant="elevated">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900 pr:mb-4">
              {__('What Will Be Imported', 'prorank-seo')}
            </h3>
            <ul className="pr:space-y-2 pr:text-sm pr:text-gray-700">
              <li className="pr:flex pr:items-start pr:gap-2">
                <span className="pr:text-success-600">•</span>
                {__('SEO titles and meta descriptions', 'prorank-seo')}
              </li>
              <li className="pr:flex pr:items-start pr:gap-2">
                <span className="pr:text-success-600">•</span>
                {__('Focus keywords and keyphrases', 'prorank-seo')}
              </li>
              <li className="pr:flex pr:items-start pr:gap-2">
                <span className="pr:text-success-600">•</span>
                {__('Open Graph and Twitter Card data', 'prorank-seo')}
              </li>
              <li className="pr:flex pr:items-start pr:gap-2">
                <span className="pr:text-success-600">•</span>
                {__('Canonical URLs and meta robots settings', 'prorank-seo')}
              </li>
              <li className="pr:flex pr:items-start pr:gap-2">
                <span className="pr:text-success-600">•</span>
                {__('Redirect rules (if available)', 'prorank-seo')}
              </li>
              <li className="pr:flex pr:items-start pr:gap-2">
                <span className="pr:text-success-600">•</span>
                {__('Schema markup (if available)', 'prorank-seo')}
              </li>
              <li className="pr:flex pr:items-start pr:gap-2">
                <span className="pr:text-success-600">•</span>
                {__('XML sitemap settings', 'prorank-seo')}
              </li>
              <li className="pr:flex pr:items-start pr:gap-2">
                <span className="pr:text-success-600">•</span>
                {__('Local SEO business locations and contact details (if available)', 'prorank-seo')}
              </li>
            </ul>
          </Card>

          {/* Import Progress */}
          {importing && (
            <Card variant="elevated">
              <div className="pr:space-y-3">
                <div className="pr:flex pr:items-center pr:gap-3">
                  <div className="pr:animate-spin pr:w-5 pr:h-5 pr:border-2 pr:border-primary-500 pr:border-t-transparent pr:rounded-full"></div>
                  <span className="pr:text-sm pr:text-gray-700">{importStatus}</span>
                </div>
                <div className="pr:w-full pr:bg-gray-200 pr:rounded-full pr:h-2 pr:overflow-hidden">
                  <div
                    className="pr:h-full pr:bg-gradient-to-r pr:from-primary-500 pr:to-primary-600 pr:transition-all pr:duration-300"
                    style={{ width: `${importProgress}%` }}
                  />
                </div>
              </div>
            </Card>
          )}

          {/* Import Results */}
          {importResults && (
            <Alert variant="success" title={__('Import Completed!', 'prorank-seo')}>
              <div className="pr:space-y-2 pr:mt-2">
                {Object.entries(importResults).map(([plugin, result]) => (
                  <div key={plugin}>
                    <div className="pr:font-semibold pr:text-sm">{plugin}:</div>
                    {result.stats && (
                      <ul className="pr:space-y-1 pr:text-sm pr:text-gray-700 pr:ml-4">
                        {result.stats.posts && (
                          <li>{sprintf(__('%d posts imported', 'prorank-seo'), result.stats.posts)}</li>
                        )}
                        {result.stats.terms && (
                          <li>{sprintf(__('%d terms imported', 'prorank-seo'), result.stats.terms)}</li>
                        )}
                        {result.stats.redirects && (
                          <li>{sprintf(__('%d redirects imported', 'prorank-seo'), result.stats.redirects)}</li>
                        )}
                      </ul>
                    )}
                  </div>
                ))}
              </div>
            </Alert>
          )}

          {error && (
            <Alert variant="error">
              {error}
            </Alert>
          )}

          <div className="pr:flex pr:items-center pr:justify-between pr:gap-3">
            <Button
              variant="primary"
              onClick={handleImport}
              loading={importing}
              disabled={importing || importResults !== null}
              icon={ArrowDownTrayIcon}
            >
              {importing
                ? __('Importing...', 'prorank-seo')
                : importResults
                  ? __('Import Complete', 'prorank-seo')
                  : __('Start Import', 'prorank-seo')
              }
            </Button>

            {!importing && !importResults && (
              <Button
                variant="ghost"
                onClick={handleSkip}
              >
                {__('Skip Import', 'prorank-seo')}
              </Button>
            )}
          </div>
        </div>
      ) : (
        <Card variant="elevated">
          <Alert variant="info">
            {__('No competitor plugins detected or all have been deactivated. You can proceed to the next step.', 'prorank-seo')}
          </Alert>
        </Card>
      )}
    </div>
  );
};

export default CompetitorImportStep;
