/**
 * Breadcrumbs Settings Component
 *
 * @package
 * @since   1.0.0
 */

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

const BreadcrumbsSettings = () => {
  const previewSiteUrl =
    window.prorankSeo?.siteUrl ||
    window.prorankSeoAdmin?.siteUrl ||
    window.prorankSeoAdmin?.site_url ||
    window.location?.origin ||
    'https://example.com';
  const previewBaseUrl = String(previewSiteUrl).endsWith('/') ? String(previewSiteUrl).slice(0, -1) : String(previewSiteUrl);
  const [settings, setSettings] = useState({
    enabled: true,
    separator: '›',
    home_text: 'Home',
    show_current: true,
    show_home: true,
    home_icon: false,
    auto_insert: false,
    position: 'before',
    enable_schema: true,
    schema_type: 'jsonld',
    style: 'default', // 'default', 'arrow', 'slash', 'pipe'
    display_style: 'inline', // 'inline', 'background', 'compact', 'large'
    show_on_home: false,
    show_on_posts: true,
    show_on_pages: true,
    show_on_archives: true,
    show_on_404: false,
    custom_css: '',
    enable_cache: false,
  });

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

  useEffect(() => {
    loadSettings();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  const loadSettings = async () => {
    setLoading(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/breadcrumbs',
      });

      if (response.success && response.data) {
        setSettings((prev) => ({ ...prev, ...response.data }));
      }
    } catch (error) {
      showNotification(__('Failed to load breadcrumbs settings', 'prorank-seo'), 'error');
    } finally {
      setLoading(false);
    }
  };

  const saveSettings = async () => {
    setSaving(true);
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/breadcrumbs',
        method: 'POST',
        data: settings,
      });

      if (response.success) {
        showNotification(__('Breadcrumbs settings saved successfully', 'prorank-seo'), 'success');
      }
    } catch (error) {
      showNotification(__('Failed to save breadcrumbs settings', 'prorank-seo'), 'error');
    } finally {
      setSaving(false);
    }
  };

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

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

  return (
    <div className="pr:space-y-6">
      <Card
        header={
          <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('General Settings', 'prorank-seo')}
            </h3>
          </div>
        }
        padding="none"
      >
        <div className="pr:p-6 pr:space-y-6">
          <Toggle
            label={__('Enable Breadcrumbs', 'prorank-seo')}
            description={__('Enable breadcrumb navigation on your site', 'prorank-seo')}
            checked={settings.enabled}
            onChange={(value) => updateSetting('enabled', value)}
          />

          <Input
            label={__('Separator', 'prorank-seo')}
            helperText={__('Character used to separate breadcrumb items', 'prorank-seo')}
            value={settings.separator}
            onChange={(value) => updateSetting('separator', value)}
          />

          <Input
            label={__('Home Text', 'prorank-seo')}
            helperText={__('Text to display for the home link', 'prorank-seo')}
            value={settings.home_text}
            onChange={(value) => updateSetting('home_text', value)}
          />

          <Toggle
            label={__('Show Current Page', 'prorank-seo')}
            description={__('Display the current page in breadcrumbs', 'prorank-seo')}
            checked={settings.show_current}
            onChange={(value) => updateSetting('show_current', value)}
          />

          <Toggle
            label={__('Show Home Link', 'prorank-seo')}
            description={__('Display a link to the homepage', 'prorank-seo')}
            checked={settings.show_home}
            onChange={(value) => updateSetting('show_home', value)}
          />

          {settings.show_home && (
            <Toggle
              label={__('Show Home Icon', 'prorank-seo')}
              description={__('Display a home icon (🏠) before the home text', 'prorank-seo')}
              checked={settings.home_icon}
              onChange={(value) => updateSetting('home_icon', value)}
            />
          )}
        </div>
      </Card>

      <Card
        header={
          <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Display Settings', 'prorank-seo')}
            </h3>
          </div>
        }
        padding="none"
      >
        <div className="pr:p-6 pr:space-y-6">
          <Toggle
            label={__('Auto Insert', 'prorank-seo')}
            description={__(
              'Automatically insert breadcrumbs into content (or use [prorank_breadcrumbs] shortcode)',
              'prorank-seo'
            )}
            checked={settings.auto_insert}
            onChange={(value) => updateSetting('auto_insert', value)}
          />

          {settings.auto_insert && (
            <Select
              label={__('Position', 'prorank-seo')}
              helperText={__('Where to insert breadcrumbs in content', 'prorank-seo')}
              value={settings.position}
              options={[
                { label: __('Before Content', 'prorank-seo'), value: 'before' },
                { label: __('After Content', 'prorank-seo'), value: 'after' },
              ]}
              onChange={(value) => updateSetting('position', value)}
            />
          )}

          <hr className="pr:border-t pr:border-gray-200 pr:my-6" />

          <h3 className="pr:text-base pr:font-semibold pr:text-gray-900">
            {__('Show Breadcrumbs On', 'prorank-seo')}
          </h3>

          <Toggle
            label={__('Homepage', 'prorank-seo')}
            checked={settings.show_on_home}
            onChange={(value) => updateSetting('show_on_home', value)}
          />

          <Toggle
            label={__('Posts', 'prorank-seo')}
            checked={settings.show_on_posts}
            onChange={(value) => updateSetting('show_on_posts', value)}
          />

          <Toggle
            label={__('Pages', 'prorank-seo')}
            checked={settings.show_on_pages}
            onChange={(value) => updateSetting('show_on_pages', value)}
          />

          <Toggle
            label={__('Archives', 'prorank-seo')}
            checked={settings.show_on_archives}
            onChange={(value) => updateSetting('show_on_archives', value)}
          />

          <Toggle
            label={__('404 Pages', 'prorank-seo')}
            checked={settings.show_on_404}
            onChange={(value) => updateSetting('show_on_404', value)}
          />
        </div>
      </Card>

      <Card
        header={
          <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Appearance Settings', 'prorank-seo')}
            </h3>
          </div>
        }
        padding="none"
      >
        <div className="pr:p-6 pr:space-y-6">
          <Select
            label={__('Separator Style', 'prorank-seo')}
            helperText={__('Choose the visual style for breadcrumb separators', 'prorank-seo')}
            value={settings.style}
            options={[
              { label: __('Default (›)', 'prorank-seo'), value: 'default' },
              { label: __('Arrow (→)', 'prorank-seo'), value: 'arrow' },
              { label: __('Slash (/)', 'prorank-seo'), value: 'slash' },
              { label: __('Pipe (|)', 'prorank-seo'), value: 'pipe' },
            ]}
            onChange={(value) => updateSetting('style', value)}
          />

          <Select
            label={__('Display Style', 'prorank-seo')}
            helperText={__('Choose how breadcrumbs are displayed', 'prorank-seo')}
            value={settings.display_style}
            options={[
              { label: __('Inline', 'prorank-seo'), value: 'inline' },
              { label: __('With Background', 'prorank-seo'), value: 'background' },
              { label: __('Compact', 'prorank-seo'), value: 'compact' },
              { label: __('Large', 'prorank-seo'), value: 'large' },
            ]}
            onChange={(value) => updateSetting('display_style', value)}
          />
        </div>
      </Card>

      <Card
        header={
          <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Schema Settings', 'prorank-seo')}
            </h3>
          </div>
        }
        padding="none"
      >
        <div className="pr:p-6 pr:space-y-6">
          <Toggle
            label={__('Enable Schema Markup', 'prorank-seo')}
            description={__('Add structured data markup to breadcrumbs for better SEO', 'prorank-seo')}
            checked={settings.enable_schema}
            onChange={(value) => updateSetting('enable_schema', value)}
          />

          {settings.enable_schema && (
            <Select
              label={__('Schema Type', 'prorank-seo')}
              helperText={__('Choose which schema format to use. JSON-LD is the recommended modern format.', 'prorank-seo')}
              value={settings.schema_type}
              options={[
                { label: __('JSON-LD Only (Recommended)', 'prorank-seo'), value: 'jsonld' },
                { label: __('Both Formats', 'prorank-seo'), value: 'both' },
                { label: __('Microdata Only (Legacy)', 'prorank-seo'), value: 'microdata' },
              ]}
              onChange={(value) => updateSetting('schema_type', value)}
            />
          )}
        </div>
      </Card>

      <Card
        header={
          <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Custom Styling', 'prorank-seo')}
            </h3>
          </div>
        }
        padding="none"
      >
        <div className="pr:p-6 pr:space-y-6">
          <Textarea
            label={__('Custom CSS', 'prorank-seo')}
            helperText={__('Add custom CSS to style your breadcrumbs. Use .prorank-breadcrumbs as the main selector.', 'prorank-seo')}
            value={settings.custom_css}
            onChange={(value) => updateSetting('custom_css', value)}
            rows={6}
            placeholder={`.prorank-breadcrumbs {
  /* Your custom styles */
  font-size: 14px;
}

.prorank-breadcrumb-item a {
  color: #0073aa;
}`}
          />
        </div>
      </Card>

      <Card
        header={
          <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Performance', 'prorank-seo')}
            </h3>
          </div>
        }
        padding="none"
      >
        <div className="pr:p-6 pr:space-y-6">
          <Toggle
            label={__('Enable Caching', 'prorank-seo')}
            description={__('Cache breadcrumb trails to improve page load performance. Cache is automatically cleared when content is updated.', 'prorank-seo')}
            checked={settings.enable_cache}
            onChange={(value) => updateSetting('enable_cache', value)}
          />
          <Alert variant="info" title={__('Cache Duration', 'prorank-seo')}>
            {__('Breadcrumb cache is stored for 1 hour and is automatically invalidated when posts, pages, or categories are modified.', 'prorank-seo')}
          </Alert>
        </div>
      </Card>

      <Card
        header={
          <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Live Preview', 'prorank-seo')}
            </h3>
          </div>
        }
        padding="none"
      >
        <div className="pr:p-6 pr:space-y-4">
          <p className="pr:text-sm pr:text-gray-600">
            {__('This is how your breadcrumbs will appear on the frontend:', 'prorank-seo')}
          </p>

          {/* Browser mockup frame */}
          <div className="pr:rounded-xl pr:border pr:border-gray-200 pr:overflow-hidden" style={{ boxShadow: '0 4px 24px -4px rgba(0,0,0,0.08)' }}>
            {/* Title bar */}
            <div className="pr:flex pr:items-center pr:gap-2 pr:px-4 pr:py-2.5 pr:bg-gray-100 pr:border-b pr:border-gray-200">
              <div className="pr:flex pr:gap-1.5">
                <span className="pr:block pr:w-3 pr:h-3 pr:rounded-full pr:bg-red-400" />
                <span className="pr:block pr:w-3 pr:h-3 pr:rounded-full pr:bg-yellow-400" />
                <span className="pr:block pr:w-3 pr:h-3 pr:rounded-full pr:bg-green-400" />
              </div>
              <div className="pr:flex-1 pr:mx-2">
                <div className="pr:bg-white pr:rounded-md pr:border pr:border-gray-200 pr:px-3 pr:py-1 pr:text-xs pr:text-gray-400 pr:font-mono pr:text-center pr:truncate">
                  {`${previewBaseUrl}/category/current-page`}
                </div>
              </div>
            </div>

            {/* Page body */}
            <div className="pr:bg-white pr:p-6">
              {/* Breadcrumb trail */}
              <nav aria-label="Breadcrumbs" className={`
                pr:mb-5
                ${settings.display_style === 'background' ? 'pr:bg-gray-50 pr:rounded-lg pr:px-4 pr:py-2.5 pr:border pr:border-gray-100' : ''}
                ${settings.display_style === 'compact' ? 'pr:text-xs' : 'pr:text-sm'}
                ${settings.display_style === 'large' ? 'pr:text-base' : ''}
              `}>
                <ol className="pr:flex pr:flex-wrap pr:items-center pr:gap-1.5" style={{ listStyle: 'none', margin: 0, padding: 0 }}>
                  {settings.show_home && (
                    <li className="pr:flex pr:items-center pr:gap-1.5">
                      <a
                        href="#"
                        onClick={(e) => e.preventDefault()}
                        className="pr:text-primary-600 pr:hover:text-primary-700 pr:transition-colors pr:no-underline pr:hover:underline"
                      >
                        {settings.home_icon && <span aria-hidden="true">🏠 </span>}
                        {settings.home_text}
                      </a>
                      <span className="pr:text-gray-300 pr:mx-0.5" aria-hidden="true">
                        {settings.style === 'arrow' ? '→' : settings.style === 'slash' ? '/' : settings.style === 'pipe' ? '|' : settings.separator}
                      </span>
                    </li>
                  )}
                  <li className="pr:flex pr:items-center pr:gap-1.5">
                    <a
                      href="#"
                      onClick={(e) => e.preventDefault()}
                      className="pr:text-primary-600 pr:hover:text-primary-700 pr:transition-colors pr:no-underline pr:hover:underline"
                    >
                      {__('Category', 'prorank-seo')}
                    </a>
                    {settings.show_current && (
                      <span className="pr:text-gray-300 pr:mx-0.5" aria-hidden="true">
                        {settings.style === 'arrow' ? '→' : settings.style === 'slash' ? '/' : settings.style === 'pipe' ? '|' : settings.separator}
                      </span>
                    )}
                  </li>
                  {settings.show_current && (
                    <li className="pr:text-gray-500 pr:font-medium" aria-current="page">
                      {__('Current Page', 'prorank-seo')}
                    </li>
                  )}
                </ol>
              </nav>

              {/* Fake page content lines */}
              <div className="pr:space-y-3">
                <div className="pr:h-6 pr:bg-gray-800 pr:rounded pr:w-3/5" />
                <div className="pr:h-3 pr:bg-gray-100 pr:rounded pr:w-full" />
                <div className="pr:h-3 pr:bg-gray-100 pr:rounded pr:w-11/12" />
                <div className="pr:h-3 pr:bg-gray-100 pr:rounded pr:w-4/5" />
                <div className="pr:mt-4 pr:h-3 pr:bg-gray-100 pr:rounded pr:w-full" />
                <div className="pr:h-3 pr:bg-gray-100 pr:rounded pr:w-3/4" />
              </div>
            </div>
          </div>
        </div>
      </Card>

      <Card
        header={
          <div className="pr:p-6 pr:border-b pr:border-gray-200 pr:bg-gray-50">
            <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
              {__('Shortcode', 'prorank-seo')}
            </h3>
          </div>
        }
        padding="none"
      >
        <div className="pr:p-6 pr:space-y-6">
          <p className="pr:text-sm pr:text-gray-600">
            {__(
              'Use the following shortcode to manually add breadcrumbs to your content:',
              'prorank-seo'
            )}
          </p>
          <code className="pr:block pr:bg-gray-100 pr:px-3 pr:py-2 pr:rounded-xs pr:font-mono pr:text-sm pr:text-gray-900">
            [prorank_breadcrumbs]
          </code>

          <hr className="pr:border-t pr:border-gray-200 pr:my-6" />

          <div className="pr:space-y-3">
            <p className="pr:text-sm pr:font-medium pr:text-gray-700">
              {__('Shortcode parameters:', 'prorank-seo')}
            </p>
            <ul className="pr:space-y-2 pr:text-sm pr:text-gray-600">
              <li className="pr:flex pr:gap-2">
                <code className="pr:bg-gray-100 pr:px-2 pr:py-0.5 pr:rounded-xs pr:font-mono pr:text-xs">
                  separator=&quot;›&quot;
                </code>
                <span>- {__('Custom separator', 'prorank-seo')}</span>
              </li>
              <li className="pr:flex pr:gap-2">
                <code className="pr:bg-gray-100 pr:px-2 pr:py-0.5 pr:rounded-xs pr:font-mono pr:text-xs">
                  home_text=&quot;Home&quot;
                </code>
                <span>- {__('Custom home text', 'prorank-seo')}</span>
              </li>
              <li className="pr:flex pr:gap-2">
                <code className="pr:bg-gray-100 pr:px-2 pr:py-0.5 pr:rounded-xs pr:font-mono pr:text-xs">
                  show_current=&quot;true&quot;
                </code>
                <span>- {__('Show/hide current page', 'prorank-seo')}</span>
              </li>
              <li className="pr:flex pr:gap-2">
                <code className="pr:bg-gray-100 pr:px-2 pr:py-0.5 pr:rounded-xs pr:font-mono pr:text-xs">
                  style=&quot;arrow&quot;
                </code>
                <span>- {__('Separator style (arrow, slash, pipe)', 'prorank-seo')}</span>
              </li>
              <li className="pr:flex pr:gap-2">
                <code className="pr:bg-gray-100 pr:px-2 pr:py-0.5 pr:rounded-xs pr:font-mono pr:text-xs">
                  class=&quot;custom-class&quot;
                </code>
                <span>- {__('Add custom CSS classes', 'prorank-seo')}</span>
              </li>
            </ul>
          </div>

          <hr className="pr:border-t pr:border-gray-200 pr:my-6" />

          <Alert variant="info" title={__('Search Appearance Note', 'prorank-seo')}>
            {__('Search engines may display breadcrumbs differently across devices and result types. Breadcrumbs still help site navigation, internal linking, and structured data clarity. JSON-LD remains the recommended structured data format.', 'prorank-seo')}
          </Alert>
        </div>
      </Card>

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

export default BreadcrumbsSettings;
