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

const DEFAULT_SETTINGS = {
  enable_html_sitemap: true,
  sitemap_page_id: '',
  auto_insert_shortcode: false,
  include_sections: ['pages', 'posts', 'categories', 'tags'],
  show_post_count: true,
  show_date: false,
  show_excerpt: false,
  columns: 1,
  style: 'list',
  heading_tag: 'h3',
  widget_enabled: true,
  widget_title: __('Sitemap', 'prorank-seo'),
  widget_sections: ['pages', 'posts'],
};

const HtmlSitemapSettings = () => {
  const [settings, setSettings] = useState(DEFAULT_SETTINGS);
  const [pages, setPages] = useState([{ value: '', label: __('— Select —', 'prorank-seo') }]);
  const [preview, setPreview] = useState('');
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [previewing, setPreviewing] = useState(false);
  const [notice, setNotice] = useState(null);
  const virtualSitemapUrl = `${window.location.origin}/html-sitemap/`;

  const buildPageOptions = (pagesResponse = []) => {
    const titleCounts = pagesResponse.reduce((acc, page) => {
      const title = (page.title?.rendered || '').trim() || `#${page.id}`;
      acc[title] = (acc[title] || 0) + 1;
      return acc;
    }, {});

    return [
      { value: '', label: __('— Select —', 'prorank-seo') },
      ...pagesResponse.map((page) => {
        const title = (page.title?.rendered || '').trim() || `#${page.id}`;
        const needsSlug = titleCounts[title] > 1;

        return {
          value: String(page.id),
          label: needsSlug ? `${title} (${page.slug})` : title,
        };
      }),
    ];
  };

  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      try {
        const [settingsResponse, pagesResponse] = await Promise.all([
          apiFetch({ path: '/prorank-seo/v1/settings/html-sitemap' }),
          apiFetch({ path: '/wp/v2/pages?per_page=100&orderby=title&order=asc' }),
        ]);

        setSettings({ ...DEFAULT_SETTINGS, ...(settingsResponse?.settings || {}) });
        setPages(Array.isArray(pagesResponse) ? buildPageOptions(pagesResponse) : [{ value: '', label: __('— Select —', 'prorank-seo') }]);
      } catch (error) {
        setNotice({ type: 'error', message: error?.message || __('Failed to load HTML sitemap settings.', 'prorank-seo') });
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, []);

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

  const toggleArrayValue = (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/html-sitemap',
        method: 'POST',
        data: { settings },
      });
      setNotice({ type: 'success', message: __('HTML sitemap settings saved.', 'prorank-seo') });
    } catch (error) {
      setNotice({ type: 'error', message: error?.message || __('Failed to save HTML sitemap settings.', 'prorank-seo') });
    } finally {
      setSaving(false);
    }
  };

  const loadPreview = async () => {
    setPreviewing(true);
    setNotice(null);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/html-sitemap/preview',
        method: 'POST',
        data: { settings },
      });
      setPreview(response?.preview || '');
    } catch (error) {
      setNotice({ type: 'error', message: error?.message || __('Failed to generate preview.', 'prorank-seo') });
    } finally {
      setPreviewing(false);
    }
  };

  const sectionOptions = [
    ['pages', __('Pages', 'prorank-seo')],
    ['posts', __('Posts', 'prorank-seo')],
    ['categories', __('Categories', 'prorank-seo')],
    ['tags', __('Tags', 'prorank-seo')],
  ];

  if (loading) {
    return <div className="pr:p-6 pr:text-sm pr:text-gray-600">{__('Loading HTML sitemap settings…', 'prorank-seo')}</div>;
  }

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

      <Card>
        <div className="pr:space-y-4">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">{__('HTML Sitemap', 'prorank-seo')}</h3>
          <p className="pr:text-sm pr:text-gray-600">
            {__('Create a visitor-facing sitemap page using the built-in shortcode or automatic page insertion.', 'prorank-seo')}
          </p>
          <Alert
            variant="info"
            title={__('Built-in HTML sitemap URL', 'prorank-seo')}
          >
            <a
              href={virtualSitemapUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="pr:text-blue-600 pr:hover:text-blue-700 pr:underline"
            >
              {virtualSitemapUrl}
            </a>
            <div className="pr:mt-2">
              {__('If you do not assign a dedicated page, ProRank serves a fallback HTML sitemap at this URL.', 'prorank-seo')}
            </div>
          </Alert>
          <Toggle
            label={__('Enable HTML sitemap shortcode and widget', 'prorank-seo')}
            checked={settings.enable_html_sitemap}
            onChange={(value) => updateSetting('enable_html_sitemap', value)}
          />
          <Select
            label={__('Sitemap page', 'prorank-seo')}
            value={String(settings.sitemap_page_id || '')}
            onChange={(value) => updateSetting('sitemap_page_id', value)}
            options={pages}
          />
          <p className="pr:text-sm pr:text-gray-600">
            {__('Optional: select a page to embed the sitemap shortcode inside a normal WordPress page.', 'prorank-seo')}
          </p>
          <Toggle
            label={__('Automatically insert shortcode into the selected page', 'prorank-seo')}
            checked={settings.auto_insert_shortcode}
            onChange={(value) => updateSetting('auto_insert_shortcode', value)}
          />
          <div className="pr:text-sm pr:text-gray-600">
            <strong>{__('Shortcode:', 'prorank-seo')}</strong> <code>[prorank_sitemap]</code>
          </div>
        </div>
      </Card>

      <Card>
        <div className="pr:space-y-4">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">{__('Included Content', 'prorank-seo')}</h3>
          <div className="pr:grid pr:grid-cols-1 md:pr:grid-cols-2 pr:gap-3">
            {sectionOptions.map(([value, label]) => (
              <Toggle
                key={value}
                label={label}
                checked={Array.isArray(settings.include_sections) && settings.include_sections.includes(value)}
                onChange={(enabled) => toggleArrayValue('include_sections', value, enabled)}
              />
            ))}
          </div>
          <Toggle
            label={__('Show post counts', 'prorank-seo')}
            checked={settings.show_post_count}
            onChange={(value) => updateSetting('show_post_count', value)}
          />
          <Toggle
            label={__('Show publish dates', 'prorank-seo')}
            checked={settings.show_date}
            onChange={(value) => updateSetting('show_date', value)}
          />
          <Toggle
            label={__('Show excerpts for posts', 'prorank-seo')}
            checked={settings.show_excerpt}
            onChange={(value) => updateSetting('show_excerpt', value)}
          />
        </div>
      </Card>

      <Card>
        <div className="pr:space-y-4">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">{__('Display Options', 'prorank-seo')}</h3>
          <Input
            label={__('Columns', 'prorank-seo')}
            type="number"
            min="1"
            max="4"
            value={String(settings.columns || 1)}
            onChange={(value) => updateSetting('columns', Math.max(1, Math.min(4, parseInt(value || '1', 10) || 1)))}
          />
          <Select
            label={__('Layout style', 'prorank-seo')}
            value={settings.style || 'list'}
            onChange={(value) => updateSetting('style', value)}
            options={[
              { value: 'list', label: __('List', 'prorank-seo') },
              { value: 'compact', label: __('Compact', 'prorank-seo') },
            ]}
          />
          <Select
            label={__('Heading tag', 'prorank-seo')}
            value={settings.heading_tag || 'h3'}
            onChange={(value) => updateSetting('heading_tag', value)}
            options={['h2', 'h3', 'h4'].map((tag) => ({ value: tag, label: tag.toUpperCase() }))}
          />
          <Toggle
            label={__('Enable HTML sitemap widget', 'prorank-seo')}
            checked={settings.widget_enabled}
            onChange={(value) => updateSetting('widget_enabled', value)}
          />
          <Input
            label={__('Widget title', 'prorank-seo')}
            value={settings.widget_title || ''}
            onChange={(value) => updateSetting('widget_title', value)}
          />
        </div>
      </Card>

      <Card>
        <div className="pr:space-y-4">
          <div className="pr:flex pr:items-center pr:justify-between pr:gap-3">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">{__('Preview', 'prorank-seo')}</h3>
            <Button variant="secondary" onClick={loadPreview} disabled={previewing}>
              {previewing ? __('Generating…', 'prorank-seo') : __('Generate Preview', 'prorank-seo')}
            </Button>
          </div>
          {preview ? (
            <div className="pr:border pr:border-gray-200 pr:rounded-md pr:p-4 pr:bg-white" dangerouslySetInnerHTML={{ __html: preview }} />
          ) : (
            <p className="pr:text-sm pr:text-gray-600">{__('Generate a preview to see the current output.', 'prorank-seo')}</p>
          )}
        </div>
      </Card>

      <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 HtmlSitemapSettings;
