/**
 * Site Audit & Tools Page
 *
 * Main wrapper component for Site Audit module with tabs
 *
 * @package ProRank\SEO
 * @since   1.0.0
 */

import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

// Custom Components
import { ProrankSpinner } from '../../components/ProrankSpinner';
import ProrankHeader from '../../components/ProrankHeader';
import ProrankDivider from '../../components/ProrankDivider';
import ModuleNav from '../../components/ModuleNav';
import { useNotification } from '../../contexts/NotificationContext';
import headerBadges from '../../utils/headerBadges';

// Import sub-pages
import SiteAuditDashboard from './SiteAuditDashboard';
import CoreWebVitals from './components/CoreWebVitalsEnhanced';
import ImportExport from '../ImportExport';

// Component imports validated

import * as React from 'react';

const DEFAULT_TAB = 'audit';
const LEGACY_TAB_ALIASES: Record<string, string> = {
  'eeat-monitor': 'eeat',
};
const LEGACY_AUDIT_SUBTAB_ALIASES: Record<string, string> = {
  overview: 'dashboard',
  audit: 'dashboard',
  dashboard: 'dashboard',
  issues: 'issues',
  history: 'history',
  settings: 'settings',
};

// TypeScript interfaces
interface Tab {
  name: string;
  title: string;
  available: boolean;
}

const SiteAuditPage: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const { showNotification } = useNotification();

  // Set page title
  useEffect(() => {
    document.title =
      __('Site Audit & Tools', 'prorank-seo') +
      ' ‹ ' +
      __('ProRank SEO', 'prorank-seo') +
      ' — WordPress';
  }, []);

  // Tabs configuration
  const tabs: Tab[] = [
    {
      name: 'audit',
      title: __('Site Audit', 'prorank-seo'),
      available: true,
    },
    {
      name: 'core-web-vitals',
      title: __('Core Web Vitals', 'prorank-seo'),
      available: true,
    },
    {
      name: 'import-export',
      title: __('Import/Export', 'prorank-seo'),
      available: true,
    },
  ];

  const normalizeRequestedTab = (value: string): string => LEGACY_TAB_ALIASES[value] || value;

  const readTabFromValue = (value: string): string => {
    if (!value) {
      return '';
    }

    const query = value.includes('?')
      ? value.split('?')[1]
      : value.replace(/^#\/?/, '');

    const params = new URLSearchParams(query);
    return normalizeRequestedTab(params.get('tab') || '');
  };

  const getRequestedTab = (): string => {
    if (typeof window === 'undefined') {
      return DEFAULT_TAB;
    }

    const requestedTab =
      readTabFromValue(window.location.search || '') ||
      readTabFromValue(window.location.hash || '') ||
      '';

    if (tabs.some((tab) => tab.name === requestedTab)) {
      return requestedTab;
    }

    return LEGACY_AUDIT_SUBTAB_ALIASES[requestedTab] ? DEFAULT_TAB : DEFAULT_TAB;
  };

  const [activeTab, setActiveTab] = useState<string>(() => getRequestedTab());

  useEffect(() => {
    if (typeof window === 'undefined') {
      return;
    }

    const requestedTab = getRequestedTab();
    const searchTab = readTabFromValue(window.location.search || '');
    const hashTab = readTabFromValue(window.location.hash || '');
    const legacyAuditSubtab = LEGACY_AUDIT_SUBTAB_ALIASES[searchTab] || LEGACY_AUDIT_SUBTAB_ALIASES[hashTab] || '';

    if (requestedTab === DEFAULT_TAB && !searchTab && !hashTab && !legacyAuditSubtab) {
      return;
    }

    const expectedHash = requestedTab === DEFAULT_TAB && legacyAuditSubtab
      ? `?tab=${requestedTab}&audit_tab=${legacyAuditSubtab}`
      : `?tab=${requestedTab}`;

    if ((window.location.hash || '').replace(/^#/, '') === expectedHash) {
      return;
    }

    const url = new URL(window.location.href);
    url.searchParams.set('tab', requestedTab);
    if (legacyAuditSubtab) {
      url.searchParams.set('audit_tab', legacyAuditSubtab);
      url.hash = `?tab=${requestedTab}&audit_tab=${legacyAuditSubtab}`;
    } else {
      url.searchParams.delete('audit_tab');
      url.hash = `?tab=${requestedTab}`;
    }
    window.history.replaceState(window.history.state, document.title, url.toString());
  }, []);

  useEffect(() => {
    const handleHashChange = () => {
      const requestedTab = getRequestedTab();
      if (requestedTab !== activeTab) {
        setActiveTab(requestedTab);
      }
    };

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

  const handleTabChange = (tabName: string) => {
    setActiveTab(tabName);

    if (typeof window === 'undefined') {
      return;
    }

    const url = new URL(window.location.href);
    url.searchParams.set('tab', tabName);
    url.searchParams.delete('audit_tab');
    url.hash = `?tab=${tabName}`;
    window.history.replaceState(window.history.state, document.title, url.toString());
  };

  const renderTabContent = (): JSX.Element | null => {
    switch (activeTab) {
      case 'audit':
        return <SiteAuditDashboard />;
      case 'core-web-vitals':
        return <CoreWebVitals />;
      case 'import-export':
        return <ImportExport />;
      default:
        return null;
    }
  };

  if (loading) {
    return (
      <div className="prorank-page">
        <div className="prorank-loading-container">
          <ProrankSpinner size="large" />
          <p className="prorank-loading-text">{__('Loading…', 'prorank-seo')}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="prorank-page prorank-site-audit-page">
      <ProrankHeader
        title={__('Site Audit & Tools', 'prorank-seo')}
        subtitle={__('Comprehensive analysis and optimization tools for your website', 'prorank-seo')}
        badges={headerBadges['site-audit']}
      />

      {/* Main Content */}
      <div className="prorank-content prorank-site-audit-shell">
        <ModuleNav
          modules={tabs.map((tab) => ({
            id: tab.name,
            label: tab.title,
            badge: null,
            badgeVariant: null,
            hasToggle: false,
          }))}
          activeModule={activeTab}
          onModuleChange={handleTabChange}
        />

        <ProrankDivider />

        {/* Tab Content */}
        <div className="pr:mt-6">{renderTabContent()}</div>
      </div>
    </div>
  );
};

export default SiteAuditPage;
