import { useEffect, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Alert, Button, Card, Input, Textarea, Toggle } from '../../../components/ui';
import ModuleNav from '../../../components/ModuleNav';
import LoadingState from '../../../components/LoadingState';
import HtmlSitemapSettings from '../HtmlSitemap/HtmlSitemapSettings';

const DEFAULT_SETTINGS = {
  enable_xml_sitemap: true,
  posts_per_sitemap: 1000,
  include_post_types: ['post', 'page'],
  include_taxonomies: ['category', 'post_tag'],
  exclude_empty_terms: true,
  include_images: true,
  include_featured_images: true,
  exclude_noindex: true,
  ping_search_engines: true,
  sitemap_index_url: 'sitemap_index.xml',
  exclude_posts: '',
  exclude_terms: '',
  landing_page_priority_enabled: false,
  landing_page_priority: 0.9,
  landing_page_patterns: '',
};

const DEFAULT_POST_TYPES = [
  { value: 'post', label: __('Posts', 'prorank-seo') },
  { value: 'page', label: __('Pages', 'prorank-seo') },
];

const DEFAULT_TAXONOMIES = [
  { value: 'category', label: __('Categories', 'prorank-seo') },
  { value: 'post_tag', label: __('Tags', 'prorank-seo') },
];

const SitemapSettings = () => {
  const [activeTab, setActiveTab] = useState('general');
  const [settings, setSettings] = useState(DEFAULT_SETTINGS);
  const [postTypes, setPostTypes] = useState(DEFAULT_POST_TYPES);
  const [taxonomies, setTaxonomies] = useState(DEFAULT_TAXONOMIES);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [notice, setNotice] = useState(null);

  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      try {
        const [settingsResponse, postTypesResponse, taxonomiesResponse] = await Promise.all([
          apiFetch({ path: '/prorank-seo/v1/settings/sitemaps' }),
          apiFetch({ path: '/wp/v2/types' }),
          apiFetch({ path: '/wp/v2/taxonomies' }),
        ]);

        setSettings({ ...DEFAULT_SETTINGS, ...(settingsResponse?.settings || {}) });

        if (postTypesResponse && typeof postTypesResponse === 'object') {
          const nextPostTypes = Object.entries(postTypesResponse)
            .filter(([slug, type]) => type?.viewable && type?.public !== false && slug !== 'attachment')
            .map(([slug, type]) => ({ value: slug, label: type?.name || slug }));
          if (nextPostTypes.length) {
            setPostTypes(nextPostTypes);
          }
        }

        if (taxonomiesResponse && typeof taxonomiesResponse === 'object') {
          const nextTaxonomies = Object.entries(taxonomiesResponse)
            .filter(([slug, tax]) =>
              tax?.visibility?.publicly_queryable &&
              !['post_format', 'nav_menu', 'link_category'].includes(slug) &&
              !slug.startsWith('wp_')
            )
            .map(([slug, tax]) => ({ value: slug, label: tax?.name || slug }));
          if (nextTaxonomies.length) {
            setTaxonomies(nextTaxonomies);
          }
        }
      } catch (error) {
        setNotice({ type: 'error', message: error?.message || __('Failed to load sitemap settings.', 'prorank-seo') });
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, []);

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

  const toggleArraySetting = (key, value, enabled) => {
    const current = Array.isArray(settings[key]) ? settings[key] : [];
    updateSetting(
      key,
      enabled ? [...new Set([...current, value])] : current.filter((item) => item !== value)
    );
  };

  const saveSettings = async () => {
    setSaving(true);
    setNotice(null);
    try {
      await apiFetch({
        path: '/prorank-seo/v1/settings/sitemaps',
        method: 'POST',
        data: settings,
      });
      setNotice({ type: 'success', message: __('Sitemap settings saved.', 'prorank-seo') });
    } catch (error) {
      setNotice({ type: 'error', message: error?.message || __('Failed to save sitemap settings.', 'prorank-seo') });
    } finally {
      setSaving(false);
    }
  };

  const getSitemapUrl = () => `${window.location.origin}/${settings.sitemap_index_url || 'sitemap_index.xml'}`;
  const getSitemapAliasUrl = () => `${window.location.origin}/sitemap.xml`;

  const modules = [
    { id: 'general', label: __('XML Sitemap', 'prorank-seo') },
    { id: 'content', label: __('Content Types', 'prorank-seo') },
    { id: 'html', label: __('HTML Sitemap', 'prorank-seo') },
    { id: 'help', label: __('Help', 'prorank-seo') },
  ];

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

  return (
    <div className="pr:space-y-6">
      {notice && <Alert variant={notice.type} title={notice.message} />}

      <ModuleNav
        modules={modules}
        activeModule={activeTab}
        onModuleChange={setActiveTab}
      />

      {activeTab === 'general' && (
        <div className="pr:space-y-6">
          <Card>
            <div className="pr:space-y-4">
              <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">{__('XML Sitemap', 'prorank-seo')}</h3>
              <Toggle
                label={__('Enable XML sitemap', 'prorank-seo')}
                checked={settings.enable_xml_sitemap}
                onChange={(value) => updateSetting('enable_xml_sitemap', value)}
              />
              <Input
                label={__('Posts per sitemap', 'prorank-seo')}
                type="number"
                value={String(settings.posts_per_sitemap || 1000)}
                onChange={(value) => updateSetting('posts_per_sitemap', Math.max(1, parseInt(value || '1000', 10) || 1000))}
              />
              <Toggle
                label={__('Include images', 'prorank-seo')}
                checked={settings.include_images}
                onChange={(value) => updateSetting('include_images', value)}
              />
              <Toggle
                label={__('Include featured images', 'prorank-seo')}
                checked={settings.include_featured_images}
                onChange={(value) => updateSetting('include_featured_images', value)}
              />
              <Toggle
                label={__('Exclude noindex content', 'prorank-seo')}
                checked={settings.exclude_noindex}
                onChange={(value) => updateSetting('exclude_noindex', value)}
              />
              <Toggle
                label={__('Ping search engines', 'prorank-seo')}
                checked={settings.ping_search_engines}
                onChange={(value) => updateSetting('ping_search_engines', value)}
              />
              <p className="pr:text-sm pr:text-gray-500">
                {__('Send legacy sitemap ping requests when sitemaps are updated. Search engines may ignore these hints.', 'prorank-seo')}
              </p>
              <Input
                label={__('Sitemap index filename', 'prorank-seo')}
                value={settings.sitemap_index_url || 'sitemap_index.xml'}
                onChange={(value) => updateSetting('sitemap_index_url', value || 'sitemap_index.xml')}
              />
            </div>
          </Card>

          <Card>
            <div className="pr:space-y-3">
              <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">{__('Current Sitemap URL', 'prorank-seo')}</h3>
              <a
                href={getSitemapUrl()}
                target="_blank"
                rel="noopener noreferrer"
                className="pr:text-sm pr:text-blue-600 pr:hover:text-blue-700 pr:underline"
              >
                {getSitemapUrl()}
              </a>
              <p className="pr:text-xs pr:text-gray-500">
                {__('Compatibility alias:', 'prorank-seo')}{' '}
                <a
                  href={getSitemapAliasUrl()}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="pr:text-blue-600 pr:hover:text-blue-700 pr:underline"
                >
                  {getSitemapAliasUrl()}
                </a>
              </p>
            </div>
          </Card>

          <Card>
            <div className="pr:space-y-4">
              <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">{__('Priority Controls', 'prorank-seo')}</h3>
              <Toggle
                label={__('Boost landing pages in XML sitemaps', 'prorank-seo')}
                checked={settings.landing_page_priority_enabled}
                onChange={(value) => updateSetting('landing_page_priority_enabled', value)}
              />
              {settings.landing_page_priority_enabled && (
                <>
                  <Input
                    label={__('Landing page priority', 'prorank-seo')}
                    type="number"
                    value={String(settings.landing_page_priority ?? 0.9)}
                    onChange={(value) =>
                      updateSetting('landing_page_priority', Math.max(0, Math.min(1, parseFloat(value || '0.9') || 0.9)))
                    }
                    min={0}
                    max={1}
                    step={0.1}
                  />
                  <Textarea
                    label={__('Landing page rules', 'prorank-seo')}
                    value={settings.landing_page_patterns || ''}
                    onChange={(value) => updateSetting('landing_page_patterns', value)}
                    rows={4}
                    placeholder={__('service-area, pricing, /locations/, 123', 'prorank-seo')}
                    helperText={__(
                      'Enter page IDs, slugs, or URL fragments separated by commas or new lines. Matching pages get the boosted sitemap priority unless a page-level override is set.',
                      'prorank-seo'
                    )}
                  />
                </>
              )}
              <p className="pr:text-xs pr:text-gray-500">
                {__('Per-page sitemap priority overrides in the SEO meta box take precedence. Search engines may ignore sitemap priority hints, so use this as a crawl hint rather than a ranking lever.', 'prorank-seo')}
              </p>
            </div>
          </Card>
        </div>
      )}

      {activeTab === 'content' && (
        <div className="pr:space-y-6">
          <Alert
            variant="info"
            title={__('Choose which content types should appear in your XML sitemap index.', 'prorank-seo')}
          >
            {__('Search engines use these sitemap entries to discover indexable content faster. Noindex content can still be excluded globally from the XML Sitemap tab.', 'prorank-seo')}
          </Alert>

          <Card>
            <div className="pr:space-y-4">
              <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">{__('Post Types', 'prorank-seo')}</h3>
              <p className="pr:text-sm pr:text-gray-600">
                {__('Include published post types that should have their own XML sitemap entries.', 'prorank-seo')}
              </p>
              <div className="pr:grid pr:grid-cols-1 md:pr:grid-cols-2 pr:gap-3">
                {postTypes.map((postType) => (
                  <Toggle
                    key={postType.value}
                    label={postType.label}
                    checked={Array.isArray(settings.include_post_types) && settings.include_post_types.includes(postType.value)}
                    onChange={(enabled) => toggleArraySetting('include_post_types', postType.value, enabled)}
                  />
                ))}
              </div>
            </div>
          </Card>

          <Card>
            <div className="pr:space-y-4">
              <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">{__('Taxonomies', 'prorank-seo')}</h3>
              <p className="pr:text-sm pr:text-gray-600">
                {__('Include archive URLs for taxonomies that you want search engines to crawl and index.', 'prorank-seo')}
              </p>
              <div className="pr:grid pr:grid-cols-1 md:pr:grid-cols-2 pr:gap-3">
                {taxonomies.map((taxonomy) => (
                  <Toggle
                    key={taxonomy.value}
                    label={taxonomy.label}
                    checked={Array.isArray(settings.include_taxonomies) && settings.include_taxonomies.includes(taxonomy.value)}
                    onChange={(enabled) => toggleArraySetting('include_taxonomies', taxonomy.value, enabled)}
                  />
                ))}
              </div>
              <Toggle
                label={__('Exclude empty terms', 'prorank-seo')}
                checked={settings.exclude_empty_terms}
                onChange={(value) => updateSetting('exclude_empty_terms', value)}
              />
              <p className="pr:text-sm pr:text-gray-500">
                {__('Keep taxonomy sitemap files focused by hiding categories or tags that have no published content.', 'prorank-seo')}
              </p>
            </div>
          </Card>

          <Card>
            <div className="pr:space-y-4">
              <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">{__('Exclusions', 'prorank-seo')}</h3>
              <p className="pr:text-sm pr:text-gray-600">
                {__('Use these fields when you need to keep specific posts or taxonomy terms out of the sitemap without changing their content settings.', 'prorank-seo')}
              </p>
              <Input
                label={__('Exclude specific posts by ID', 'prorank-seo')}
                value={settings.exclude_posts || ''}
                onChange={(value) => updateSetting('exclude_posts', value)}
                placeholder={__('1, 23, 456', 'prorank-seo')}
              />
              <Input
                label={__('Exclude specific terms by ID', 'prorank-seo')}
                value={settings.exclude_terms || ''}
                onChange={(value) => updateSetting('exclude_terms', value)}
                placeholder={__('5, 10, 15', 'prorank-seo')}
              />
            </div>
          </Card>

          <Alert variant="info" title={__('What happens after you save?', 'prorank-seo')}>
            {__('The sitemap index and section files will reflect these selections. If you also enable "Exclude noindex content" in the XML Sitemap tab, noindex posts and pages will stay out of the sitemap even if their content type is included.', 'prorank-seo')}
          </Alert>
        </div>
      )}

      {activeTab === 'html' && <HtmlSitemapSettings />}

      {activeTab === 'help' && (
        <Card>
          <div className="pr:space-y-4">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">{__('Sitemap Help', 'prorank-seo')}</h3>
            <ul className="pr:list-disc pr:pl-5 pr:space-y-2 pr:text-sm pr:text-gray-600">
              <li>{__('XML sitemaps help search engines discover your content faster.', 'prorank-seo')}</li>
              <li>{__('HTML sitemaps create a visitor-facing overview page using the built-in shortcode or the /html-sitemap/ fallback URL.', 'prorank-seo')}</li>
              <li>{__('Use the sitemap index URL in robots.txt and Search Console. The /sitemap.xml URL remains available as a compatibility alias.', 'prorank-seo')}</li>
            </ul>
          </div>
        </Card>
      )}

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

export default SitemapSettings;
