/* global wp */
import { useState, useCallback, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import ModuleNav from '../../components/ModuleNav';
import ProrankHeader from '../../components/ProrankHeader';
import ProrankDivider from '../../components/ProrankDivider';
import { useNotification } from '../../contexts/NotificationContext';
import SitemapSettings from '../../settings/TechnicalSEO/Sitemaps/SitemapSettings';
import RobotsIndexingSettings from '../../settings/TechnicalSEO/RobotsIndexing/RobotsIndexingSettings';
import RedirectSettings from '../../settings/TechnicalSEO/Redirects/RedirectSettings';
import UrlCleanupSettings from '../../settings/TechnicalSEO/UrlCleanup/UrlCleanupSettings';
import HeadCleanupSettings from '../../settings/TechnicalSEO/HeadCleanup/HeadCleanupSettings';
import headerBadges from '../../utils/headerBadges';
const CLEANUP_TAB_SLUG = 'cleanup';
const CLEANUP_DEFAULT_SLUG = 'head_cleanup';
const CLEANUP_CHILD_SLUGS = new Set(['head_cleanup', 'head-cleanup', 'url-cleanup']);
const FREE_HIDDEN_TECHNICAL_SEO_SLUGS = new Set([
  'internationalisation',
  'headless',
  'ethical-seo',
  'schema',
  'schema-markup',
]);
const TECHNICAL_SEO_NAV_ORDER = new Map(
  [
    'sitemaps',
    'robots-indexing',
    'redirects',
    CLEANUP_TAB_SLUG,
  ].map((id, index) => [id, index])
);

const getRequestedTabFromLocation = (): string => {
  const query = new URLSearchParams(window.location.search);
  const queryModule = query.get('module');
  if (queryModule) {
    return queryModule;
  }

  const rawHash = (window.location.hash || '').replace(/^#\/?/, '');
  const hashTab = rawHash.split('?')[0].trim();
  return hashTab;
};

const sortTechnicalSeoNavModules = (navModules) =>
  [...navModules].sort((a, b) => {
    const aOrder = TECHNICAL_SEO_NAV_ORDER.has(a.id)
      ? TECHNICAL_SEO_NAV_ORDER.get(a.id)
      : Number.MAX_SAFE_INTEGER;
    const bOrder = TECHNICAL_SEO_NAV_ORDER.has(b.id)
      ? TECHNICAL_SEO_NAV_ORDER.get(b.id)
      : Number.MAX_SAFE_INTEGER;

    if (aOrder !== bOrder) {
      return aOrder - bOrder;
    }

    return String(a.label || '').localeCompare(String(b.label || ''));
  });

const TechnicalSEO = () => {
  const [activeTab, setActiveTab] = useState('sitemaps');
  const [cleanupSubTab, setCleanupSubTab] = useState(CLEANUP_DEFAULT_SLUG);
  const [modules, setModules] = useState([]);
  const [moduleGroup, setModuleGroup] = useState(null);
  const [loading, setLoading] = useState(true);
  const [updating, setUpdating] = useState({});
  const { showNotification } = useNotification();
  const loadModules = useCallback(async () => {
    setLoading(true);
    try {
      // Load modules from REST API
      const response = await apiFetch({
        path: '/prorank-seo/v1/modules/by-group/technical-seo',
      });

      if (response && response.modules) {
        const visibleModules = response.modules.filter(
          (module) =>
            (!module?.tier || module.tier === 'free') &&
            !FREE_HIDDEN_TECHNICAL_SEO_SLUGS.has(module.slug)
        );
        setModules(visibleModules);
        setModuleGroup(response.group);
      }
    } catch (error) {
      // Show error state instead of using fallback data
      showNotification(
        __('Failed to load modules. Please refresh the page.', 'prorank-seo'),
        'error'
      );
      setModules([]);
      setModuleGroup(null);
    } finally {
      setLoading(false);
    }
  }, [showNotification]);
  // Set page title
  useEffect(() => {
    document.title =
      __('Technical SEO', 'prorank-seo') +
      ' ‹ ' +
      __('ProRank SEO', 'prorank-seo') +
      ' — WordPress';
  }, []);
  // Load modules from API
  useEffect(() => {
    loadModules();
  }, [loadModules]);

  useEffect(() => {
    if (!modules.length) {
      return;
    }

    const syncTabFromLocation = () => {
      const requestedTab = getRequestedTabFromLocation();
      if (!requestedTab) {
        return;
      }

      if (CLEANUP_CHILD_SLUGS.has(requestedTab)) {
        setActiveTab(CLEANUP_TAB_SLUG);
        setCleanupSubTab(requestedTab);
        return;
      }
      if (requestedTab === CLEANUP_TAB_SLUG) {
        setActiveTab(CLEANUP_TAB_SLUG);
        return;
      }

      if (modules.some((module) => module.slug === requestedTab)) {
        setActiveTab(requestedTab);
      }
    };

    syncTabFromLocation();
    window.addEventListener('hashchange', syncTabFromLocation);
    return () => window.removeEventListener('hashchange', syncTabFromLocation);
  }, [modules]);

  const handleModuleChange = (moduleId: string) => {
    if (moduleId === CLEANUP_TAB_SLUG) {
      const defaultCleanupSlug =
        modules.find((m) => CLEANUP_CHILD_SLUGS.has(m.slug))?.slug || CLEANUP_DEFAULT_SLUG;
      const nextCleanupSlug = modules.some((m) => m.slug === cleanupSubTab) ? cleanupSubTab : defaultCleanupSlug;
      setCleanupSubTab(nextCleanupSlug);
    }
    setActiveTab(moduleId);
    const nextUrl = `${window.location.pathname}${window.location.search}#${moduleId}`;
    window.history.replaceState({}, '', nextUrl);
  };

  const toggleCleanupModules = async (newState: boolean) => {
    const cleanupModules = modules.filter((module) => CLEANUP_CHILD_SLUGS.has(module.slug));
    const togglableModules = cleanupModules.filter(
      (module) => module.available !== false && module.enabled !== newState
    );

    if (!togglableModules.length) {
      return;
    }

    setUpdating((prev) => {
      const next = { ...prev, cleanup: true };
      togglableModules.forEach((module) => {
        next[module.slug] = true;
      });
      return next;
    });

    const results = await Promise.allSettled(
      togglableModules.map((module) =>
        apiFetch({
          path: `/prorank-seo/v1/modules/${module.slug}/toggle`,
          method: 'POST',
          data: { enabled: newState },
        })
      )
    );

    const successfulSlugs: string[] = [];
    results.forEach((result, index) => {
      if (result.status === 'fulfilled') {
        successfulSlugs.push(togglableModules[index].slug);
      }
    });

    if (successfulSlugs.length) {
      setModules((prev) =>
        prev.map((module) =>
          successfulSlugs.includes(module.slug) ? { ...module, enabled: newState } : module
        )
      );
    }

    if (successfulSlugs.length === togglableModules.length) {
      showNotification(
        newState
          ? __('Cleanup modules enabled successfully', 'prorank-seo')
          : __('Cleanup modules disabled successfully', 'prorank-seo'),
        'success'
      );
    } else {
      showNotification(
        __('Some cleanup modules failed to update. Please try again.', 'prorank-seo'),
        'warning'
      );
    }

    setUpdating((prev) => {
      const next = { ...prev, cleanup: false };
      togglableModules.forEach((module) => {
        next[module.slug] = false;
      });
      return next;
    });
  };
  const toggleModule = async (module) => {
    const slug = module.slug;
    const newState = !module.enabled;
    setUpdating((prev) => ({ ...prev, [slug]: true }));
    try {
      // Toggle module via REST API
      await apiFetch({
        path: `/prorank-seo/v1/modules/${slug}/toggle`,
        method: 'POST',
        data: { enabled: newState },
      });

      // Update module state locally
      setModules((prev) => prev.map((m) => (m.slug === slug ? { ...m, enabled: newState } : m)));
      showNotification(
        newState
          ? __('Module enabled successfully', 'prorank-seo')
          : __('Module disabled successfully', 'prorank-seo'),
        'success'
      );
      // If we disabled the current active tab, keep it active but show disabled state
    } catch (error) {
      showNotification(error.message || __('Failed to toggle module', 'prorank-seo'), 'error');
    } finally {
      setUpdating((prev) => ({ ...prev, [slug]: false }));
    }
  };
  const toggleModuleGroup = async () => {
    if (!moduleGroup) return;
    const newState = !moduleGroup.enabled;
    setUpdating((prev) => ({ ...prev, group: true }));
    try {
      // Make API call to toggle module group
      await apiFetch({
        path: `/prorank-seo/v1/modules/groups/${moduleGroup.slug}/status`,
        method: 'POST',
        data: { enabled: newState },
      });
      setModuleGroup((prev) => ({ ...prev, enabled: newState }));
      setModules((prev) =>
        prev.map((m) => ({
          ...m,
          enabled: m.available !== undefined && m.available !== null ? newState !== '' : false,
        }))
      );
      showNotification(
        newState
          ? __('All modules enabled successfully', 'prorank-seo')
          : __('All modules disabled successfully', 'prorank-seo'),
        'success'
      );
      // Close sidebar if disabling
      // Keep the current tab active
    } catch (error) {
      showNotification(
        error.message || __('Failed to toggle module group', 'prorank-seo'),
        'error'
      );
    } finally {
      setUpdating((prev) => ({ ...prev, group: false }));
    }
  };
  const renderSettingsForModule = (moduleSlug: string) => {
    switch (moduleSlug) {
      case 'sitemaps':
        return <SitemapSettings />;
      case 'robots-indexing':
        return <RobotsIndexingSettings />;
      case 'redirects':
        return <RedirectSettings />;
      case 'head-cleanup':
      case 'head_cleanup':
        return <HeadCleanupSettings />;
      case 'url-cleanup':
        return <UrlCleanupSettings />;
      default:
        return (
          <div className="prorank-settings-card" style={{ textAlign: 'center', padding: '60px' }}>
            <h3>{__('Module Not Found', 'prorank-seo')}</h3>
            <p>{__('The selected module does not have settings available.', 'prorank-seo')}</p>
          </div>
        );
    }
  };

  const renderSingleModuleContent = (module) => {
    if (!module) {
      return null;
    }
    const isEnabled = module.enabled;
    if (module.available === false) {
      return (
        <div className="prorank-module-disabled">
          <div className="prorank-disabled-content">
            <span
              className="dashicons dashicons-lock"
              style={{ fontSize: '48px', marginBottom: '16px' }}
            ></span>
            <h3>{module.name}</h3>
            <p>
              {__('This module is not available in this build.', 'prorank-seo')}
            </p>
          </div>
        </div>
      );
    }
    if (!isEnabled) {
      return (
        <div className="prorank-module-disabled">
          <div className="prorank-disabled-content">
            <span
              className={`dashicons ${module.icon}`}
              style={{ fontSize: '48px', marginBottom: '16px', opacity: 0.5 }}
            ></span>
            <h3>{module.name}</h3>
            <p>
              {__(
                'This module is currently disabled. Enable it to access its settings and features.',
                'prorank-seo'
              )}
            </p>
          </div>
        </div>
      );
    }
    return <div className="prorank-settings-wrapper">{renderSettingsForModule(module.slug)}</div>;
  };

  const renderTabContent = () => {
    if (activeTab === CLEANUP_TAB_SLUG) {
      const cleanupModules = modules.filter((module) => CLEANUP_CHILD_SLUGS.has(module.slug));
      const selectedCleanupModule =
        cleanupModules.find((module) => module.slug === cleanupSubTab) || cleanupModules[0];

      if (!selectedCleanupModule) {
        return null;
      }

      return (
        <div>
          <div className="prorank-tab-panel">
            <div className="prorank-tab-panel__tabs" role="tablist" aria-label={__('Cleanup settings', 'prorank-seo')}>
              {cleanupModules.map((module) => (
                <button
                  key={module.slug}
                  type="button"
                  className={`prorank-tab-panel__tab ${selectedCleanupModule.slug === module.slug ? 'is-active' : ''}`}
                  onClick={() => {
                    setCleanupSubTab(module.slug);
                    const nextUrl = `${window.location.pathname}${window.location.search}#${module.slug}`;
                    window.history.replaceState({}, '', nextUrl);
                  }}
                >
                  {module.name}
                </button>
              ))}
            </div>
          </div>
          {renderSingleModuleContent(selectedCleanupModule)}
        </div>
      );
    }

    const activeModule = modules.find((module) => module.slug === activeTab);
    return renderSingleModuleContent(activeModule);
  };
  if (loading) {
    return (
      <div className="prorank-page prorank-technical-seo-page">
        <div className="prorank-loading">
          <div className="prorank-loading-spinner"></div>
          <p>{__('Loading modules…', 'prorank-seo')}</p>
        </div>
      </div>
    );
  }
  return (
    <div className="prorank-page prorank-technical-seo-page">
      <ProrankHeader
        title={__('Technical SEO', 'prorank-seo')}
        subtitle={__('Configure advanced technical SEO settings and optimizations', 'prorank-seo')}
        badges={headerBadges['technical-seo']}
      />
      
      {/* Main Content */}
      <div className="prorank-content prorank-technical-seo-content">
        <ModuleNav
          modules={(() => {
            const navModules = [];
            let cleanupInserted = false;

            modules.forEach((module) => {
              if (CLEANUP_CHILD_SLUGS.has(module.slug)) {
                if (!cleanupInserted) {
                  const cleanupModules = modules.filter((item) =>
                    CLEANUP_CHILD_SLUGS.has(item.slug)
                  );
                  const togglableCleanupModules = cleanupModules.filter(
                    (item) => item.available !== false
                  );
                  const cleanupEnabled =
                    togglableCleanupModules.length > 0 &&
                    togglableCleanupModules.some((item) => item.enabled);
                  const cleanupUpdating =
                    updating.cleanup ||
                    togglableCleanupModules.some((item) => updating[item.slug]);
                  navModules.push({
                    id: CLEANUP_TAB_SLUG,
                    label: __('Cleanup', 'prorank-seo'),
                    badge: null,
                    badgeVariant: null,
                    hasToggle: togglableCleanupModules.length > 0,
                    toggleValue: cleanupEnabled,
                    toggleDisabled: cleanupUpdating,
                  });
                  cleanupInserted = true;
                }
                return;
              }

              navModules.push({
                id: module.slug,
                label: module.name,
                badge: null,
                badgeVariant: null,
                hasToggle: !module.noToggle,
                toggleValue: module.enabled,
                toggleDisabled: updating[module.slug] || module.available === false,
              });
            });

            return sortTechnicalSeoNavModules(navModules);
          })()}
          activeModule={activeTab}
          onModuleChange={handleModuleChange}
          onToggleChange={(moduleId, checked) => {
            if (moduleId === CLEANUP_TAB_SLUG) {
              toggleCleanupModules(checked);
              return;
            }
            const module = modules.find((item) => item.slug === moduleId);
            if (!module || module.enabled === checked) return;
            toggleModule(module);
          }}
        />

        <ProrankDivider />

        <div className="pr:mt-6">{renderTabContent()}</div>
      </div>
    </div>
  );
};
export default TechnicalSEO;
