/* 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 SiteBasicsSettings from '../../settings/OnPageSEO/SiteBasics/SiteBasicsSettings';
import TitleMetaSettings from '../../settings/OnPageSEO/TitlesMeta/TitleMetaSettings';
import BreadcrumbsSettings from '../../settings/OnPageSEO/Breadcrumbs/BreadcrumbsSettings';
import PodcastSeoSettings from '../../settings/OnPageSEO/PodcastSeo/PodcastSeoSettings';
import ContentAnalysisSettings from '../../settings/OnPageSEO/ContentAnalysis/ContentAnalysisSettings';
import { Alert, Button, Card, Input, Select, Toggle } from '../../components/ui';
import LoadingState from '../../components/LoadingState';
import headerBadges from '../../utils/headerBadges';

const SchemaMarkupSettings = ({ initialSubTab = 'basic-schema', showSubTabs = true }) => {
  const [settings, setSettings] = useState({
    enable_website_schema: true,
    enable_organization_schema: true,
    enable_article_schema: true,
    enable_breadcrumb_schema: true,
    organization_name: '',
    organization_logo: '',
    organization_type: 'Organization',
  });
  const [activeSubTab, setActiveSubTab] = useState(initialSubTab);

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [notice, setNotice] = useState(null);
  const { showNotification } = useNotification();

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

  useEffect(() => {
    setActiveSubTab(initialSubTab);
  }, [initialSubTab]);

  const loadSettings = async () => {
    setLoading(true);
    setNotice(null);

    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/basic-schema',
        method: 'GET',
      });

      if (response && typeof response === 'object') {
        setSettings((prev) => ({ ...prev, ...response }));
      }
    } catch (error) {
      setNotice({ type: 'error', message: __('Failed to load schema settings', 'prorank-seo') });
    } finally {
      setLoading(false);
    }
  };

  const saveSettings = async () => {
    setSaving(true);
    setNotice(null);

    try {
      await apiFetch({
        path: '/prorank-seo/v1/settings/basic-schema',
        method: 'POST',
        data: settings,
      });

      setNotice({ type: 'success', message: __('Settings saved successfully', 'prorank-seo') });
      showNotification(__('Schema settings saved', 'prorank-seo'), 'success');
    } catch (error) {
      setNotice({ type: 'error', message: __('Failed to save schema settings', 'prorank-seo') });
      showNotification(__('Failed to save schema settings', 'prorank-seo'), 'error');
    } finally {
      setSaving(false);
    }
  };

  const updateSetting = (key, value) => {
    setSettings((prev) => ({ ...prev, [key]: value }));
  };

  if (loading) {
    return <LoadingState message={__('Loading schema settings…', 'prorank-seo')} />;
  }

  return (
    <div className="pr:space-y-6 pr:max-w-4xl">
      <div className="pr:mb-6">
        <h2 className="pr:text-2xl pr:font-semibold pr:text-gray-900 pr:mb-2">
          {__('Schema Markup', 'prorank-seo')}
        </h2>
        <p className="pr:text-sm pr:text-gray-600">
          {__(
            'Enable basic structured data (WebSite, Organization, Article, Breadcrumbs) to help search engines understand your site.',
            'prorank-seo'
          )}
        </p>
      </div>

      {notice && (
        <Alert variant={notice.type === 'success' ? 'success' : 'error'} title={notice.message} />
      )}
      {showSubTabs && (
        <div className="pr:flex pr:items-center pr:gap-2 pr:border-b pr:border-gray-200 pr:pb-2">
          <button
            type="button"
            className={`pr:px-3 pr:py-1.5 pr:rounded-md pr:text-sm pr:font-medium pr:transition-colors ${
              activeSubTab === 'basic-schema'
                ? 'pr:bg-primary-500 pr:text-white'
                : 'pr:bg-gray-100 pr:text-gray-700 hover:pr:bg-gray-200'
            }`}
            onClick={() => setActiveSubTab('basic-schema')}
          >
            {__('Schema Settings', 'prorank-seo')}
          </button>
        </div>
      )}

      {activeSubTab === 'basic-schema' && (
        <>
          <Card>
            <div className="pr:p-6 pr:space-y-5">
              <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">{__('Schemas', 'prorank-seo')}</h3>

              <Toggle
                label={__('WebSite schema', 'prorank-seo')}
                checked={Boolean(settings.enable_website_schema)}
                onChange={(value) => updateSetting('enable_website_schema', value)}
                help={__('Outputs WebSite JSON-LD (with search action).', 'prorank-seo')}
              />

              <Toggle
                label={__('Organization schema', 'prorank-seo')}
                checked={Boolean(settings.enable_organization_schema)}
                onChange={(value) => updateSetting('enable_organization_schema', value)}
                help={__(
                  'Outputs the basic homepage entity schema. Site Representation settings can change the final type to Organization, LocalBusiness, or Person.',
                  'prorank-seo'
                )}
              />

              <Toggle
                label={__('Article schema (posts)', 'prorank-seo')}
                checked={Boolean(settings.enable_article_schema)}
                onChange={(value) => updateSetting('enable_article_schema', value)}
                help={__('Outputs Article JSON-LD on single posts.', 'prorank-seo')}
              />

              <Toggle
                label={__('Breadcrumb schema', 'prorank-seo')}
                checked={Boolean(settings.enable_breadcrumb_schema)}
                onChange={(value) => updateSetting('enable_breadcrumb_schema', value)}
                help={__('Outputs BreadcrumbList JSON-LD on non-home pages.', 'prorank-seo')}
              />
            </div>
          </Card>

          <Card>
            <div className="pr:p-6 pr:space-y-5">
              <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
                {__('Organization Details', 'prorank-seo')}
              </h3>

              <Input
                label={__('Organization name', 'prorank-seo')}
                value={settings.organization_name || ''}
                onChange={(value) => updateSetting('organization_name', value)}
                placeholder={__('Your business or site name', 'prorank-seo')}
              />

              <Select
                label={__('Schema entity type', 'prorank-seo')}
                value={settings.organization_type || 'Organization'}
                onChange={(value) => updateSetting('organization_type', value)}
                helperText={__(
                  'Default entity type for this basic schema. Site Basics > Site Representation takes precedence when it is set to Person or Local Business.',
                  'prorank-seo'
                )}
                options={[
                  { label: __('Organization', 'prorank-seo'), value: 'Organization' },
                  { label: __('LocalBusiness', 'prorank-seo'), value: 'LocalBusiness' },
                  { label: __('Person', 'prorank-seo'), value: 'Person' },
                ]}
              />

              <Input
                label={__('Organization logo URL', 'prorank-seo')}
                value={settings.organization_logo || ''}
                onChange={(value) => updateSetting('organization_logo', value)}
                placeholder={__('https://example.com/logo.png', 'prorank-seo')}
                help={__(
                  'Optional override. If empty, ProRank falls back to the Site Basics organization/person logo.',
                  'prorank-seo'
                )}
              />
            </div>
          </Card>

          <div className="pr:flex pr:gap-3">
            <Button variant="primary" onClick={saveSettings} loading={saving} disabled={saving}>
              {saving ? __('Saving…', 'prorank-seo') : __('Save Settings', 'prorank-seo')}
            </Button>
            <Button variant="secondary" onClick={loadSettings} disabled={saving}>
              {__('Reload', 'prorank-seo')}
            </Button>
          </div>
        </>
      )}
    </div>
  );
};

const OnPageSEO = () => {
  const [activeTab, setActiveTab] = useState('site-basics');
  const [siteBasicsSection, setSiteBasicsSection] = useState('site-basics');
  const [schemaSection, setSchemaSection] = useState('schema-markup');
  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 {
      const response = await apiFetch({
        path: '/prorank-seo/v1/modules/by-group/on-page-seo',
        method: 'GET',
      });

      if (response && response.modules) {
        const nextModules = response.modules || [];
        const visibleModules = nextModules.filter((m) => !m?.tier || m.tier === 'free');

        const relevantModuleSlugs = [
          'site-basics',
          'breadcrumbs',
          'titles-meta',
          'schema-markup',
          'content-analysis',
          'podcast-seo',
        ];

        const relevantModules = visibleModules.filter((m) => relevantModuleSlugs.includes(m.slug));
        const orderIndex = new Map(relevantModuleSlugs.map((slug, idx) => [slug, idx]));

        setModules(
          relevantModules.slice().sort((a, b) => {
            const ai = orderIndex.has(a.slug) ? orderIndex.get(a.slug) : 999;
            const bi = orderIndex.has(b.slug) ? orderIndex.get(b.slug) : 999;
            if (ai !== bi) return ai - bi;
            return String(a.name || '').localeCompare(String(b.name || ''));
          })
        );
        setModuleGroup(response.group);
      }
    } catch (error) {
      console.error('Failed to load modules:', error);
      showNotification(
        __('Failed to load modules. Please refresh the page.', 'prorank-seo'),
        'error'
      );
    } finally {
      setLoading(false);
    }
  }, []);
  // Set page title
  useEffect(() => {
    document.title =
      __('On-Page SEO', 'prorank-seo') + ' ‹ ' + __('ProRank SEO', 'prorank-seo') + ' — WordPress';
  }, []);
  // Load modules from API once on mount
  useEffect(() => {
    loadModules();
  }, []);

  const getModule = (slug) => modules.find((module) => module.slug === slug) || null;

  const renderModuleSettings = (slug) => {
    switch (slug) {
      case 'site-basics':
        return <SiteBasicsSettings />;
      case 'titles-meta':
        return <TitleMetaSettings />;
      case 'breadcrumbs':
        return <BreadcrumbsSettings />;
      case 'schema-markup':
        return <SchemaMarkupSettings initialSubTab="basic-schema" showSubTabs={false} />;
      case 'content-analysis':
        return <ContentAnalysisSettings />;
      case 'podcast-seo':
        return <PodcastSeoSettings moduleSlug={slug} />;
      default:
        return null;
    }
  };

  const renderModulePanel = (slug) => {
    const module = getModule(slug);
    if (!module) {
      return null;
    }

    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 (!module.enabled) {
      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">{renderModuleSettings(slug)}</div>;
  };

  const buildNavItem = (module, overrides = {}) => {
    if (!module) {
      return null;
    }

    return {
      id: overrides.id || module.slug,
      label: overrides.label || module.name,
      badge: null,
      badgeVariant: null,
      hasToggle: overrides.hasToggle !== undefined ? overrides.hasToggle : true,
      toggleValue: overrides.toggleValue !== undefined ? overrides.toggleValue : module.enabled,
      toggleDisabled:
        overrides.toggleDisabled !== undefined
          ? overrides.toggleDisabled
          : updating[module.slug] || module.available === false,
      disabled: Boolean(overrides.disabled),
    };
  };

  const siteBasicsSections = ['site-basics', 'breadcrumbs'].map((slug) => getModule(slug)).filter(Boolean);
  const schemaSections = ['schema-markup'].map((slug) => getModule(slug)).filter(Boolean);

  const topLevelTabs = [
    buildNavItem(getModule('site-basics'), {
      id: 'site-basics',
      label: __('Site Basics', 'prorank-seo'),
      hasToggle: false,
    }),
    buildNavItem(getModule('titles-meta')),
    buildNavItem(getModule('schema-markup'), {
      id: 'schema',
      label: __('Schema', 'prorank-seo'),
      hasToggle: false,
    }),
    buildNavItem(getModule('content-analysis')),
    buildNavItem(getModule('podcast-seo')),
  ].filter(Boolean);

  useEffect(() => {
    const validTopLevelIds = topLevelTabs.map((tab) => tab.id);
    if (validTopLevelIds.length > 0 && !validTopLevelIds.includes(activeTab)) {
      setActiveTab(validTopLevelIds[0]);
    }
  }, [activeTab, topLevelTabs]);

  useEffect(() => {
    const validSiteBasicsSections = siteBasicsSections.map((module) => module.slug);
    if (validSiteBasicsSections.length > 0 && !validSiteBasicsSections.includes(siteBasicsSection)) {
      setSiteBasicsSection(validSiteBasicsSections[0]);
    }

    const validSchemaSections = schemaSections.map((module) => module.slug);
    if (validSchemaSections.length > 0 && !validSchemaSections.includes(schemaSection)) {
      setSchemaSection(validSchemaSections[0]);
    }
  }, [schemaSection, schemaSections, siteBasicsSection, siteBasicsSections]);

  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'
      );
    } 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: Boolean(newState && m.available !== false),
        }))
      );
      showNotification(
        newState
          ? __('All modules enabled successfully', 'prorank-seo')
          : __('All modules disabled successfully', 'prorank-seo'),
        'success'
      );
    } catch (error) {
      showNotification(
        error.message || __('Failed to toggle module group', 'prorank-seo'),
        'error'
      );
    } finally {
      setUpdating((prev) => ({ ...prev, group: false }));
    }
  };
  const renderTabContent = () => {
    if (activeTab === 'site-basics') {
      return (
        <div className="pr:space-y-6">
          <ModuleNav
            modules={siteBasicsSections.map((module) => buildNavItem(module))}
            activeModule={siteBasicsSection}
            onModuleChange={setSiteBasicsSection}
            onToggleChange={(moduleId, checked) => {
              const module = getModule(moduleId);
              if (!module || module.enabled === checked) return;
              toggleModule(module);
            }}
          />
          <div className="pr:mt-6">{renderModulePanel(siteBasicsSection)}</div>
        </div>
      );
    }

    if (activeTab === 'schema') {
      return (
        <div className="pr:space-y-6">
          <ModuleNav
            modules={schemaSections.map((module) =>
              buildNavItem(module, {
                label: __('Basic Schema', 'prorank-seo'),
              })
            )}
            activeModule={schemaSection}
            onModuleChange={setSchemaSection}
            onToggleChange={(moduleId, checked) => {
              const module = getModule(moduleId);
              if (!module || module.enabled === checked) return;
              toggleModule(module);
            }}
          />
          <div className="pr:mt-6">{renderModulePanel(schemaSection)}</div>
        </div>
      );
    }

    return renderModulePanel(activeTab);
  };
  if (loading) {
    return (
      <div className="prorank-page prorank-onpage-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-onpage-seo-page">
      <ProrankHeader
        title={__('On-Page SEO', 'prorank-seo')}
        subtitle={__('Optimize your on-page elements for better search engine visibility', 'prorank-seo')}
        badges={headerBadges['on-page-seo']}
      />
      
      {/* Main Content */}
      <div className="prorank-content prorank-onpage-seo-content">
        <ModuleNav
          modules={topLevelTabs}
          activeModule={activeTab}
          onModuleChange={setActiveTab}
          onToggleChange={(moduleId, checked) => {
            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 OnPageSEO;
