/**
 * Optimization Step Component
 *
 * Quick optimization settings and automatic configurations
 */

import { useState, useEffect, useCallback } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Card, Alert, Button, Badge } from '../../../../components/ui';
import {
  CheckCircleIcon,
  XCircleIcon,
  CogIcon,
} from '@heroicons/react/24/solid';
import {
  CheckIcon,
  XMarkIcon,
  ArrowPathIcon,
  ExclamationTriangleIcon,
} from '@heroicons/react/24/outline';

const OptimizationStep = ({ wizardData, updateWizardData, onNext, onValidationChange }) => {
  const [optimizations, setOptimizations] = useState(() => ({
    robots_txt: true,
    xml_sitemap: true,
    breadcrumbs: true,
    permalinks: true,
    image_alt_text: false,
    noindex_archives: false,
    schema_markup: true,
    redirect_attachments: true,
    ...(wizardData.optimization_selections || {}),
  }));

  const [applying, setApplying] = useState(false);
  const [retrying, setRetrying] = useState(null); // Track which item is being retried
  const [currentlyApplying, setCurrentlyApplying] = useState(null);
  const [applied, setApplied] = useState(wizardData.optimizations_applied || {});
  const [failed, setFailed] = useState({}); // Track failed items separately
  const [results, setResults] = useState({});
  const [error, setError] = useState(null);
  const [progress, setProgress] = useState(0);

  const optimizationCategories = {
    'Technical SEO': [
      {
        key: 'robots_txt',
        label: __('Generate Robots.txt', 'prorank-seo'),
        description: __('Create an optimized robots.txt file for search engines', 'prorank-seo'),
        icon: '🤖',
        impact: 'high',
        details: __('Tells search engines which pages to crawl and index', 'prorank-seo'),
      },
      {
        key: 'xml_sitemap',
        label: __('Create XML Sitemap', 'prorank-seo'),
        description: __('Generate XML sitemaps for better search engine discovery', 'prorank-seo'),
        icon: '🗺️',
        impact: 'high',
        details: __('Helps search engines find all your important pages', 'prorank-seo'),
      },
      {
        key: 'permalinks',
        label: __('Optimize Permalinks', 'prorank-seo'),
        description: __('Set SEO-friendly URL structure (removes dates and categories)', 'prorank-seo'),
        icon: '🔗',
        impact: 'medium',
        details: __('Creates cleaner, more memorable URLs', 'prorank-seo'),
      },
    ],
    'Content Optimization': [
      {
        key: 'breadcrumbs',
        label: __('Enable Breadcrumbs', 'prorank-seo'),
        description: __('Add navigation breadcrumbs for better user experience and SEO', 'prorank-seo'),
        icon: '🍞',
        impact: 'medium',
        details: __('Improves navigation and shows in search results', 'prorank-seo'),
      },
      {
        key: 'image_alt_text',
        label: __('Auto-Generate Image Alt Text', 'prorank-seo'),
        description: __('Automatically add alt text to images without it', 'prorank-seo'),
        icon: '🖼️',
        impact: 'low',
        details: __('Improves accessibility and image SEO', 'prorank-seo'),
      },
      {
        key: 'noindex_archives',
        label: __('NoIndex Archive Pages', 'prorank-seo'),
        description: __('Prevent duplicate content by noindexing archive pages', 'prorank-seo'),
        icon: '📚',
        impact: 'medium',
        details: __('Avoids duplicate content penalties', 'prorank-seo'),
      },
    ],
    'Rich Results': [
      {
        key: 'schema_markup',
        label: __('Enable Basic Schema Markup', 'prorank-seo'),
        description: __('Add structured data for rich snippets in search results', 'prorank-seo'),
        icon: '⭐',
        impact: 'high',
        details: __('Shows star ratings, prices, and more in search results', 'prorank-seo'),
      },
      {
        key: 'redirect_attachments',
        label: __('Redirect Attachment Pages', 'prorank-seo'),
        description: __('Redirect attachment pages to their parent posts', 'prorank-seo'),
        icon: '↪️',
        impact: 'low',
        details: __('Prevents thin content pages from being indexed', 'prorank-seo'),
      },
    ],
  };

  const handleToggle = (key, checked) => {
    const nextOptimizations = {
      ...optimizations,
      [key]: checked,
    };
    setOptimizations(nextOptimizations);
    updateWizardData('optimization_selections', nextOptimizations);
  };

  const applyOptimizations = async () => {
    setApplying(true);
    setError(null);
    setProgress(0);

    const selectedKeys = Object.entries(optimizations)
      .filter(([, enabled]) => enabled)
      .map(([key]) => key);

    try {
      // Show progress animation
      setProgress(20);
      setCurrentlyApplying(selectedKeys[0]);

      const response = await apiFetch({
        path: '/prorank-seo/v1/wizard/apply-optimizations',
        method: 'POST',
        data: { optimizations: selectedKeys },
      });

      setProgress(90);

      const serverResults = response.results || {};
      const appliedItems = {};
      const resultItems = {};
      const failedItems = {};

      Object.entries(serverResults).forEach(([key, result]) => {
        resultItems[key] = result;
        if (result.success) {
          appliedItems[key] = true;
        } else {
          failedItems[key] = result.error || __('Failed to apply', 'prorank-seo');
        }
      });

      setApplied(appliedItems);
      setResults(resultItems);
      setFailed(failedItems);
      updateWizardData('optimizations_applied', appliedItems);
      setCurrentlyApplying(null);
      setProgress(100);

      if (Object.keys(failedItems).length > 0) {
        setError(sprintf(
          __('%d optimization(s) failed. You can retry them individually below.', 'prorank-seo'),
          Object.keys(failedItems).length
        ));
      }
    } catch (err) {
      setError(err.message || __('Failed to apply optimizations. You can configure them manually later.', 'prorank-seo'));
    } finally {
      setApplying(false);
    }
  };

  // Retry a single failed optimization
  const retryOptimization = useCallback(async (key) => {
    setRetrying(key);
    setError(null);

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/wizard/apply-optimizations',
        method: 'POST',
        data: { optimizations: [key] },
      });

      const result = response.results?.[key];
      if (result?.success) {
        setApplied(prev => ({ ...prev, [key]: true }));
        setResults(prev => ({ ...prev, [key]: result }));
        setFailed(prev => {
          const newFailed = { ...prev };
          delete newFailed[key];
          return newFailed;
        });
        updateWizardData('optimizations_applied', { ...applied, [key]: true });
      } else {
        const errorMessage = result?.error || __('Failed to apply optimization', 'prorank-seo');
        setResults(prev => ({ ...prev, [key]: { error: errorMessage } }));
        setFailed(prev => ({ ...prev, [key]: errorMessage }));
      }
    } catch (err) {
      const errorMessage = err.message || __('Failed to apply optimization', 'prorank-seo');
      setResults(prev => ({ ...prev, [key]: { error: errorMessage } }));
      setFailed(prev => ({ ...prev, [key]: errorMessage }));
    } finally {
      setRetrying(null);
    }
  }, [applied, updateWizardData]);

  // Retry all failed optimizations
  const retryAllFailed = useCallback(async () => {
    const failedKeys = Object.keys(failed);
    for (const key of failedKeys) {
      await retryOptimization(key);
    }
  }, [failed, retryOptimization]);

  const selectedCount = Object.values(optimizations).filter(Boolean).length;
  const appliedCount = Object.values(applied).filter(Boolean).length;
  const failedCount = Object.keys(failed).length;
  const allApplied = selectedCount > 0 && selectedCount === appliedCount && failedCount === 0;

  const getImpactVariant = (impact) => {
    switch (impact) {
      case 'high': return 'success';
      case 'medium': return 'warning';
      case 'low': return 'secondary';
      default: return 'secondary';
    }
  };

  useEffect(() => {
    if (onValidationChange) {
      // The user can skip this step, but if they choose optimizations they
      // must actually apply them before the wizard can continue.
      onValidationChange(allApplied);
    }
  }, [onValidationChange, allApplied]);

  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">
          {__('Quick Optimizations', 'prorank-seo')}
        </h2>
        <p className="pr:text-sm pr:text-gray-600">
          {__('Apply recommended SEO optimizations with one click. These settings can be changed later.', 'prorank-seo')}
        </p>
      </div>

      {/* Optimization Stats - Mobile responsive */}
      <div className="pr:grid pr:grid-cols-1 pr:sm:grid-cols-3 pr:gap-4">
        <Card variant="outlined">
          <div className="pr:text-center">
            <div className="pr:text-3xl pr:font-bold pr:text-primary-600">{selectedCount}</div>
            <div className="pr:text-sm pr:text-gray-600">{__('Selected', 'prorank-seo')}</div>
          </div>
        </Card>
        <Card variant="outlined">
          <div className="pr:text-center">
            <div className="pr:text-3xl pr:font-bold pr:text-success-600">{appliedCount}</div>
            <div className="pr:text-sm pr:text-gray-600">{__('Applied', 'prorank-seo')}</div>
          </div>
        </Card>
        <Card variant="outlined">
          <div className="pr:text-center">
            <div className="pr:text-3xl pr:font-bold pr:text-gray-900">{selectedCount - appliedCount}</div>
            <div className="pr:text-sm pr:text-gray-600">{__('Pending', 'prorank-seo')}</div>
          </div>
        </Card>
      </div>

      {/* Progress Bar */}
      {applying && (
        <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:font-semibold pr:text-gray-900">
                {currentlyApplying
                  ? sprintf(__('Applying: %s', 'prorank-seo'),
                    Object.values(optimizationCategories).flat().find(o => o.key === currentlyApplying)?.label
                  )
                  : __('Preparing optimizations...', 'prorank-seo')
                }
              </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: `${progress}%` }}
              />
            </div>
          </div>
        </Card>
      )}

      {/* Optimization Categories */}
      <div className="pr:space-y-6">
        {Object.entries(optimizationCategories).map(([category, items]) => (
          <div key={category} className="pr:space-y-4">
            <div className="pr:flex pr:items-center pr:gap-2">
              <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
                {category}
              </h3>
              <Badge variant="secondary" size="sm">
                {items.filter(item => optimizations[item.key]).length}/{items.length}
              </Badge>
            </div>

            <div className="pr:space-y-3">
              {items.map((item) => {
                const isSelected = optimizations[item.key];
                const isApplied = applied[item.key];
                const hasError = results[item.key]?.error;

                return (
                  <Card
                    key={item.key}
                    variant={isSelected ? 'elevated' : 'outlined'}
                    className={`pr:relative ${isSelected ? 'pr:ring-2 pr:ring-primary-500' : ''}`}
                  >
                    <div className="pr:flex pr:items-start pr:gap-4">
                      <input
                        type="checkbox"
                        checked={isSelected}
                        onChange={(value) => handleToggle(item.key, value?.target ? value.target.checked : !!value)}
                        disabled={applying || isApplied}
                        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">
                        <span className="pr:text-2xl">{item.icon}</span>
                      </div>

                      <div className="pr:flex-1">
                        <div className="pr:flex pr:items-start pr:justify-between pr:gap-2 pr:mb-2">
                          <h4 className="pr:text-base pr:font-semibold pr:text-gray-900">{item.label}</h4>
                          <div className="pr:flex pr:items-center pr:gap-2 pr:shrink-0">
                            <Badge variant={getImpactVariant(item.impact)} size="sm">
                              {sprintf(__('%s impact', 'prorank-seo'), item.impact)}
                            </Badge>
                            {isApplied && !hasError && (
                              <Badge variant="success" size="sm">
                                <CheckIcon className="pr:w-3 pr:h-3" />
                                {__('Applied', 'prorank-seo')}
                              </Badge>
                            )}
                            {hasError && (
                              <Badge variant="danger" size="sm">
                                <XMarkIcon className="pr:w-3 pr:h-3" />
                                {__('Failed', 'prorank-seo')}
                              </Badge>
                            )}
                          </div>
                        </div>
                        <p className="pr:text-sm pr:text-gray-700 pr:mb-1">{item.description}</p>
                        <p className="pr:text-sm pr:text-gray-500">{item.details}</p>
                        {hasError && (
                          <div className="pr:mt-3 pr:p-3 pr:bg-red-50 pr:rounded-lg pr:border pr:border-red-200">
                            <div className="pr:flex pr:items-start pr:justify-between pr:gap-3">
                              <div className="pr:flex pr:items-start pr:gap-2">
                                <ExclamationTriangleIcon className="pr:w-5 pr:h-5 pr:text-red-500 pr:shrink-0 pr:mt-0.5" />
                                <div>
                                  <p className="pr:text-sm pr:font-medium pr:text-red-800">
                                    {__('Failed to apply', 'prorank-seo')}
                                  </p>
                                  <p className="pr:text-xs pr:text-red-600 pr:mt-0.5">
                                    {results[item.key].error || __('An error occurred', 'prorank-seo')}
                                  </p>
                                </div>
                              </div>
                              <Button
                                variant="secondary"
                                size="sm"
                                onClick={() => retryOptimization(item.key)}
                                disabled={retrying === item.key}
                                icon={ArrowPathIcon}
                                className={retrying === item.key ? 'pr:animate-spin' : ''}
                              >
                                {retrying === item.key ? __('Retrying...', 'prorank-seo') : __('Retry', 'prorank-seo')}
                              </Button>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  </Card>
                );
              })}
            </div>
          </div>
        ))}
      </div>

      {/* Action Button */}
      {!allApplied && selectedCount > 0 && (
        <Card variant="elevated" className="pr:text-center">
          <div className="pr:py-4">
            <CogIcon className="pr:w-8 pr:h-8 pr:text-primary-600 pr:mx-auto pr:mb-3" />
            <div className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-2">
              {sprintf(__('Ready to apply %d optimizations?', 'prorank-seo'), selectedCount)}
            </div>
            <p className="pr:text-sm pr:text-gray-600 pr:mb-4">
              {__('This will configure your site with SEO best practices. The process takes about 30 seconds.', 'prorank-seo')}
            </p>
            <Button
              variant="primary"
              onClick={applyOptimizations}
              loading={applying}
              disabled={applying || selectedCount === 0}
              size="lg"
            >
              {applying
                ? __('Applying Optimizations...', 'prorank-seo')
                : sprintf(__('Apply %d Optimizations', 'prorank-seo'), selectedCount)
              }
            </Button>
          </div>
        </Card>
      )}

      {/* Success Message */}
      {allApplied && (
        <Alert variant="success" title={__('🎉 Optimizations Complete!', 'prorank-seo')}>
          {sprintf(__('Successfully applied %d optimizations to your site.', 'prorank-seo'), appliedCount)}
        </Alert>
      )}

      {/* Error Message with Retry All Button */}
      {error && failedCount > 0 && (
        <Alert variant="warning">
          <div className="pr:flex pr:items-center pr:justify-between pr:gap-4">
            <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>{error}</span>
            </div>
            <Button
              variant="secondary"
              size="sm"
              onClick={retryAllFailed}
              disabled={retrying !== null}
              icon={ArrowPathIcon}
            >
              {retrying !== null
                ? __('Retrying...', 'prorank-seo')
                : sprintf(__('Retry All (%d)', 'prorank-seo'), failedCount)
              }
            </Button>
          </div>
        </Alert>
      )}

      {/* General error without specific failures */}
      {error && failedCount === 0 && (
        <Alert variant="warning">
          {error}
        </Alert>
      )}
    </div>
  );
};

export default OptimizationStep;
