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

const DEFAULT_SETTINGS = {
  remove_rsd_link: false,
  remove_wlwmanifest_link: false,
  remove_wp_generator: false,
  remove_feed_links: false,
  remove_feed_links_extra: false,
  remove_adjacent_posts_links: false,
  remove_wp_shortlink: false,
  remove_rest_api_links: false,
  remove_oembed_links: false,
  remove_emoji_scripts: false,
  remove_dns_prefetch: false,
  remove_version_numbers: false,
  disable_xmlrpc: false,
  remove_jquery_migrate: false,
  disable_self_pingbacks: false,
  limit_post_revisions: false,
  revision_limit: 5,
};

const HeadCleanupSettings = () => {
  const [settings, setSettings] = useState(DEFAULT_SETTINGS);
  const [preview, setPreview] = useState(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [notice, setNotice] = useState(null);
  const { showNotification } = useNotification();

  const loadAll = async () => {
    setLoading(true);
    try {
      const [settingsResponse, previewResponse] = await Promise.all([
        apiFetch({ path: '/prorank-seo/v1/settings/head_cleanup' }),
        apiFetch({ path: '/prorank-seo/v1/settings/head_cleanup/preview' }),
      ]);

      setSettings({ ...DEFAULT_SETTINGS, ...(settingsResponse?.settings || {}) });
      setPreview(previewResponse || null);
    } catch (error) {
      const message = error?.message || __('Failed to load head cleanup settings.', 'prorank-seo');
      setNotice({ type: 'error', message });
    } finally {
      setLoading(false);
    }
  };

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

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

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

    try {
      await apiFetch({
        path: '/prorank-seo/v1/settings/head_cleanup',
        method: 'POST',
        data: settings,
      });
      await loadAll();
      setNotice({ type: 'success', message: __('Head cleanup settings saved.', 'prorank-seo') });
      showNotification(__('Head cleanup settings saved.', 'prorank-seo'), 'success');
    } catch (error) {
      const message = error?.message || __('Failed to save head cleanup settings.', 'prorank-seo');
      setNotice({ type: 'error', message });
      showNotification(message, 'error');
    } finally {
      setSaving(false);
    }
  };

  const previewItems = [
    ['rsd_link', __('RSD link', 'prorank-seo')],
    ['wlwmanifest_link', __('WLW manifest', 'prorank-seo')],
    ['wp_generator', __('WordPress generator meta', 'prorank-seo')],
    ['feed_links', __('Main feed links', 'prorank-seo')],
    ['rest_api_links', __('REST API links', 'prorank-seo')],
    ['emoji_scripts', __('Emoji scripts', 'prorank-seo')],
    ['jquery_migrate', __('jQuery Migrate', 'prorank-seo')],
    ['xmlrpc', __('XML-RPC', 'prorank-seo')],
  ];

  if (loading) {
    return <div className="pr:p-6 pr:text-sm pr:text-gray-600">{__('Loading head cleanup 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">{__('WordPress Head Cleanup', 'prorank-seo')}</h3>
          <p className="pr:text-sm pr:text-gray-600">
            {__('Remove unnecessary meta tags, discovery links, and legacy scripts from the front-end head output.', 'prorank-seo')}
          </p>
          <Toggle label={__('Remove RSD link', 'prorank-seo')} checked={settings.remove_rsd_link} onChange={(value) => updateSetting('remove_rsd_link', value)} />
          <Toggle label={__('Remove WLW manifest link', 'prorank-seo')} checked={settings.remove_wlwmanifest_link} onChange={(value) => updateSetting('remove_wlwmanifest_link', value)} />
          <Toggle label={__('Remove WordPress generator meta', 'prorank-seo')} checked={settings.remove_wp_generator} onChange={(value) => updateSetting('remove_wp_generator', value)} />
          <Toggle label={__('Remove shortlink', 'prorank-seo')} checked={settings.remove_wp_shortlink} onChange={(value) => updateSetting('remove_wp_shortlink', value)} />
          <Toggle label={__('Remove adjacent post links', 'prorank-seo')} checked={settings.remove_adjacent_posts_links} onChange={(value) => updateSetting('remove_adjacent_posts_links', value)} />
          <Toggle label={__('Remove main feed links', 'prorank-seo')} checked={settings.remove_feed_links} onChange={(value) => updateSetting('remove_feed_links', value)} />
          <Toggle label={__('Remove extra feed links', 'prorank-seo')} checked={settings.remove_feed_links_extra} onChange={(value) => updateSetting('remove_feed_links_extra', value)} />
          <Toggle label={__('Remove REST API links', 'prorank-seo')} checked={settings.remove_rest_api_links} onChange={(value) => updateSetting('remove_rest_api_links', value)} />
          <Toggle label={__('Remove oEmbed links', 'prorank-seo')} checked={settings.remove_oembed_links} onChange={(value) => updateSetting('remove_oembed_links', value)} />
        </div>
      </Card>

      <Card>
        <div className="pr:space-y-4">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">{__('Performance & Hardening', 'prorank-seo')}</h3>
          <Toggle label={__('Remove emoji scripts', 'prorank-seo')} checked={settings.remove_emoji_scripts} onChange={(value) => updateSetting('remove_emoji_scripts', value)} />
          <Toggle label={__('Remove DNS prefetch hints', 'prorank-seo')} checked={settings.remove_dns_prefetch} onChange={(value) => updateSetting('remove_dns_prefetch', value)} />
          <Toggle label={__('Remove version numbers', 'prorank-seo')} checked={settings.remove_version_numbers} onChange={(value) => updateSetting('remove_version_numbers', value)} />
          <Toggle label={__('Disable XML-RPC', 'prorank-seo')} checked={settings.disable_xmlrpc} onChange={(value) => updateSetting('disable_xmlrpc', value)} />
          <Toggle label={__('Remove jQuery Migrate', 'prorank-seo')} checked={settings.remove_jquery_migrate} onChange={(value) => updateSetting('remove_jquery_migrate', value)} />
          <Toggle label={__('Disable self pingbacks', 'prorank-seo')} checked={settings.disable_self_pingbacks} onChange={(value) => updateSetting('disable_self_pingbacks', value)} />
          <Toggle label={__('Limit post revisions', 'prorank-seo')} checked={settings.limit_post_revisions} onChange={(value) => updateSetting('limit_post_revisions', value)} />
          {settings.limit_post_revisions && (
            <Input
              label={__('Revision limit', 'prorank-seo')}
              type="number"
              value={String(settings.revision_limit || 5)}
              onChange={(value) => updateSetting('revision_limit', Math.max(1, Math.min(50, parseInt(value || '5', 10) || 5)))}
            />
          )}
        </div>
      </Card>

      <Card>
        <div className="pr:space-y-3">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">{__('Current Head Preview', 'prorank-seo')}</h3>
          <div className="pr:grid pr:grid-cols-1 md:pr:grid-cols-2 pr:gap-3">
            {previewItems.map(([key, label]) => {
              const active = Boolean(preview?.elements?.[key]);
              return (
                <div key={key} className="pr:flex pr:items-center pr:justify-between pr:border pr:border-gray-200 pr:rounded-md pr:px-3 pr:py-2">
                  <span className="pr:text-sm pr:text-gray-700">{label}</span>
                  <span className={`pr:text-xs pr:font-medium pr:px-2 pr:py-1 pr:rounded-full ${active ? 'pr:bg-amber-100 pr:text-amber-700' : 'pr:bg-emerald-100 pr:text-emerald-700'}`}>
                    {active ? __('Present', 'prorank-seo') : __('Removed', 'prorank-seo')}
                  </span>
                </div>
              );
            })}
          </div>
        </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>
        <Button variant="secondary" onClick={loadAll} disabled={saving}>
          {__('Reload Preview', 'prorank-seo')}
        </Button>
      </div>
    </div>
  );
};

export default HeadCleanupSettings;
