/**
 * Modules Step Component
 *
 * Shows top-level module groups with toggle switches.
 * Individual sub-module configuration is deferred to post-wizard.
 */

import { useState, useEffect } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Card, Alert, Toggle } from '../../../../components/ui';
import LoadingState from '../../../../components/LoadingState';
import { useLicense } from '../../../../contexts/LicenseContext';
import {
  LockClosedIcon,
} from '@heroicons/react/24/solid';
import {
  PencilIcon,
  ShieldCheckIcon,
  RocketLaunchIcon,
  ChartBarIcon,
  ShoppingBagIcon,
  GlobeAltIcon,
  UserGroupIcon,
  BuildingOfficeIcon,
} from '@heroicons/react/24/outline';

// Icon mapping for module groups (matches ModuleManagerTab)
const moduleIcons = {
  'on-page-seo': PencilIcon,
  'technical-seo': ShieldCheckIcon,
  performance: RocketLaunchIcon,
  analytics: ChartBarIcon,
  woocommerce: ShoppingBagIcon,
  'local-seo': GlobeAltIcon,
  'ai-tools': RocketLaunchIcon,
  support: UserGroupIcon,
  'agency-hub': BuildingOfficeIcon,
};

// Tier badge colors
const tierColors = {
  free: { bg: 'pr:bg-green-100', text: 'pr:text-green-800' },
  pro: { bg: 'pr:bg-purple-100', text: 'pr:text-purple-800' },
  business: { bg: 'pr:bg-yellow-100', text: 'pr:text-yellow-800' },
  agency: { bg: 'pr:bg-red-100', text: 'pr:text-red-800' },
};

const ModulesStep = ({ wizardData, updateWizardData, onValidationChange }) => {
  const [groups, setGroups] = useState([]);
  const [enabledGroups, setEnabledGroups] = useState({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const { isTierActive } = useLicense();

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

  useEffect(() => {
    if (onValidationChange && !loading && !error) {
      onValidationChange(true);
    }
  }, [onValidationChange, loading, error]);

  useEffect(() => {
    // Only persist once groups have loaded to avoid saving empty state
    if (!loading && Object.keys(enabledGroups).length > 0) {
      updateWizardData('selectedModules', enabledGroups);
    }
  }, [enabledGroups, loading]);

  const loadGroups = async () => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/modules/groups',
      });

      const fetchedGroups = response.groups || [];
      setGroups(fetchedGroups);

      // Start from the saved wizard draft when available, otherwise use real current group status.
      const initial = {};
      fetchedGroups.forEach((group) => {
        if (wizardData?.selectedModules && Object.prototype.hasOwnProperty.call(wizardData.selectedModules, group.slug)) {
          initial[group.slug] = !!wizardData.selectedModules[group.slug];
        } else if (group.enabled !== undefined) {
          initial[group.slug] = !!group.enabled;
        }
      });
      setEnabledGroups(initial);
    } catch (err) {
      setError(
        __('Unable to load module groups. Please check your connection and try again.', 'prorank-seo')
      );
    } finally {
      setLoading(false);
    }
  };

  const handleToggle = (slug, tier) => {
    // Don't allow toggling tier-locked groups the user can't access
    if (tier && tier !== 'free' && !isTierActive(tier)) return;

    setEnabledGroups((prev) => ({
      ...prev,
      [slug]: !prev[slug],
    }));
  };

  if (loading) {
    return <LoadingState message={__('Loading module groups...', 'prorank-seo')} />;
  }

  if (error) {
    return (
      <Card variant="elevated">
        <Alert variant="error">{error}</Alert>
      </Card>
    );
  }

  if (groups.length === 0) {
    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">
            {__('Choose Module Groups', 'prorank-seo')}
          </h2>
          <p className="pr:text-sm pr:text-gray-600">
            {__('No module groups available. You can configure modules after setup.', 'prorank-seo')}
          </p>
        </div>
      </div>
    );
  }

  const enabledCount = Object.values(enabledGroups).filter(Boolean).length;

  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">
          {__('Choose Module Groups', 'prorank-seo')}
        </h2>
        <p className="pr:text-sm pr:text-gray-600">
          {__('Enable the SEO feature groups you need. You can configure individual modules later.', 'prorank-seo')}
        </p>
      </div>

      <div className="pr:grid pr:grid-cols-1 md:pr:grid-cols-2 pr:gap-4">
        {groups.map((group) => {
          const isEnabled = enabledGroups[group.slug] || false;
          const isLocked = group.tier && group.tier !== 'free' && !isTierActive(group.tier);
          const IconComponent = moduleIcons[group.slug] || ShieldCheckIcon;
          const tier = tierColors[group.tier] || tierColors.free;

          return (
            <Card
              key={group.slug}
              variant="elevated"
              className={`pr:relative pr:transition-all ${
                isEnabled && !isLocked ? 'pr:ring-2 pr:ring-primary-500' : ''
              } ${isLocked ? 'pr:opacity-60' : ''}`}
            >
              <div className="pr:flex pr:items-start pr:gap-4">
                <div
                  className={`pr:p-3 pr:rounded-lg pr:shrink-0 ${
                    isEnabled && !isLocked ? 'pr:bg-primary-100' : 'pr:bg-gray-100'
                  }`}
                >
                  <IconComponent
                    className={`pr:w-6 pr:h-6 ${
                      isEnabled && !isLocked ? 'pr:text-primary-600' : 'pr:text-gray-500'
                    }`}
                  />
                </div>

                <div className="pr:flex-1 pr:min-w-0">
                  <div className="pr:flex pr:items-center pr:gap-2 pr:mb-1">
                    <h3 className="pr:text-base pr:font-semibold pr:text-gray-900">
                      {group.name}
                    </h3>
                    {isLocked && (
                      <span
                        className={`pr:inline-flex pr:items-center pr:gap-1 pr:px-2 pr:py-0.5 pr:rounded-full pr:text-xs pr:font-semibold pr:uppercase ${tier.bg} ${tier.text}`}
                      >
                        <LockClosedIcon className="pr:w-3 pr:h-3" />
                        {group.tier}
                      </span>
                    )}
                  </div>
                  <p className="pr:text-sm pr:text-gray-600">{group.description}</p>
                </div>

                <div className="pr:shrink-0 pr:pt-1">
                  <Toggle
                    checked={isEnabled && !isLocked}
                    onChange={() => handleToggle(group.slug, group.tier)}
                    disabled={isLocked}
                    size="sm"
                  />
                </div>
              </div>
            </Card>
          );
        })}
      </div>

      <p className="pr:text-center pr:text-sm pr:text-gray-500">
        {sprintf(
          __('%1$d of %2$d module groups enabled', 'prorank-seo'),
          enabledCount,
          groups.length
        )}
      </p>
    </div>
  );
};

export default ModulesStep;
