import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { Card, Button, Alert, Toggle, Select } from '../../../components/ui';
import {
  CheckIcon,
  PencilSquareIcon,
  ArrowTrendingUpIcon,
  RectangleGroupIcon,
} from '@heroicons/react/24/outline';
import { useNotification } from '../../../contexts/NotificationContext';

const ContentAnalysisSettings = () => {
  const [settings, setSettings] = useState({
    enable_realtime: true,
    min_content_length: 300,
    target_readability_score: 60,
    auto_analyze_delay: 2000,
    show_keyword_density: false,
    show_entity_detection: false,
    show_intent_classification: false,
    // Task 5 — custom-field inclusion.
    include_custom_fields_in_analysis: false,
    include_acf_fields_in_analysis: true,
    custom_field_allowlist: [],
    // Task 7 — inclusive language.
    enable_inclusive_language_analysis: true,
    ignored_inclusive_language_terms: [],
    // Task 8 — prominent words.
    enable_prominent_words: true,
    prominent_words_max_terms: 20,
    prominent_words_ignored_terms: [],
  });
  const [isSaving, setIsSaving] = useState(false);
  const [hasSaved, setHasSaved] = useState(false);
  const { showNotification } = useNotification();

  // Load settings on mount
  useEffect(() => {
    loadSettings();
  }, []);

  const loadSettings = async () => {
    try {
      const response = await apiFetch({
        path: '/prorank-seo/v1/settings/content-analysis',
      });
      if (response.data) {
        setSettings(prev => ({ ...prev, ...response.data }));
      }
    } catch (error) {
      // Use defaults if settings not found
    }
  };

  const saveSettings = async () => {
    setIsSaving(true);
    setHasSaved(false);
    try {
      await apiFetch({
        path: '/prorank-seo/v1/settings/content-analysis',
        method: 'POST',
        data: settings,
      });
      setHasSaved(true);
      showNotification(__('Settings saved successfully', 'prorank-seo'), 'success');
      setTimeout(() => setHasSaved(false), 3000);
    } catch (error) {
      showNotification(__('Failed to save settings', 'prorank-seo'), 'error');
    }
    setIsSaving(false);
  };

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

  const features = [
    {
      icon: PencilSquareIcon,
      title: __('Readability Scoring', 'prorank-seo'),
      description: __('Real-time Flesch-Kincaid readability analysis with grade level assessment', 'prorank-seo')
    },
    {
      icon: ArrowTrendingUpIcon,
      title: __('SEO Optimization Tips', 'prorank-seo'),
      description: __('Actionable suggestions to improve content structure and keyword usage', 'prorank-seo')
    },
    {
      icon: RectangleGroupIcon,
      title: __('Content Structure Analysis', 'prorank-seo'),
      description: __('Evaluates heading hierarchy, paragraph length, and content organization', 'prorank-seo')
    },
  ];

  const steps = [
    __('Open any post or page in the WordPress editor', 'prorank-seo'),
    __('Look for the "Content Analysis & SEO" panel in the ProRank SEO sidebar', 'prorank-seo'),
    __('Review readability and SEO score insights in the panel', 'prorank-seo'),
    __('Follow the optimization suggestions to improve your content', 'prorank-seo')
  ];

  return (
    <div className="pr:space-y-6 pr:max-w-4xl">
      {/* Header */}
      <div className="pr:mb-6">
        <h2 className="pr:text-2xl pr:font-semibold pr:text-gray-900 pr:mb-2">
          {__('Content Analysis', 'prorank-seo')}
        </h2>
        <p className="pr:text-sm pr:text-gray-600">
          {__('Enhance your content with readability scoring and SEO optimization directly in the editor.', 'prorank-seo')}
        </p>
      </div>

      {/* Info Notice */}
      <Alert variant="info">
        {__('This feature runs directly inside the WordPress editor. The settings below customize the analysis panel.', 'prorank-seo')}
      </Alert>

      {/* Features Card */}
      <Card>
        <div className="pr:p-6 pr:border-b pr:border-gray-200">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Features', 'prorank-seo')}
          </h3>
        </div>
        <div className="pr:p-6">
          <div className="pr:grid pr:grid-cols-1 pr:md:grid-cols-2 pr:gap-6">
            {features.map((feature, index) => {
              const IconComponent = feature.icon;
              return (
                <div key={index} className="pr:flex pr:gap-3">
                  <div className="pr:shrink-0 pr:w-8 pr:h-8 pr:rounded-lg pr:bg-primary-50 pr:flex pr:items-center pr:justify-center">
                    <IconComponent className="pr:w-5 pr:h-5 pr:text-primary-600" />
                  </div>
                  <div className="pr:flex-1">
                    <h4 className="pr:text-sm pr:font-semibold pr:text-gray-900 pr:mb-1">
                      {feature.title}
                    </h4>
                    <p className="pr:text-xs pr:text-gray-600 pr:leading-relaxed">
                      {feature.description}
                    </p>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </Card>

      {/* How to Use Card */}
      <Card>
        <div className="pr:p-6 pr:border-b pr:border-gray-200">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('How to Use', 'prorank-seo')}
          </h3>
        </div>
        <div className="pr:p-6">
          <ol className="pr:space-y-3">
            {steps.map((step, index) => (
              <li key={index} className="pr:flex pr:gap-3">
                <span className="pr:shrink-0 pr:w-6 pr:h-6 pr:rounded-full pr:bg-primary-500 pr:text-white pr:flex pr:items-center pr:justify-center pr:text-xs pr:font-semibold">
                  {index + 1}
                </span>
                <span className="pr:text-sm pr:text-gray-700 pr:leading-relaxed pr:pt-0.5">
                  {step}
                </span>
              </li>
            ))}
          </ol>
        </div>
      </Card>

      {/* Configuration Card */}
      <Card>
        <div className="pr:p-6 pr:border-b pr:border-gray-200">
          <h3 className="pr:text-lg pr:font-semibold pr:text-gray-900">
            {__('Configuration', 'prorank-seo')}
          </h3>
        </div>
        <div className="pr:p-6 pr:space-y-6">
          {/* Analysis Settings Section */}
          <div className="pr:space-y-4">
            <h4 className="pr:text-base pr:font-semibold pr:text-gray-900">
              {__('Analysis Settings', 'prorank-seo')}
            </h4>

            <Toggle
              label={__('Enable Real-time Analysis', 'prorank-seo')}
              description={__('Automatically analyze content as you type in the editor', 'prorank-seo')}
              checked={settings.enable_realtime}
              onChange={(value) => updateSetting('enable_realtime', value)}
            />

            <Select
              label={__('Auto-analyze Delay', 'prorank-seo')}
              helperText={__('Time to wait after user stops typing before analyzing', 'prorank-seo')}
              value={settings.auto_analyze_delay.toString()}
              onChange={(value) => updateSetting('auto_analyze_delay', parseInt(value))}
              options={[
                { value: '1000', label: __('1 second', 'prorank-seo') },
                { value: '2000', label: __('2 seconds (recommended)', 'prorank-seo') },
                { value: '3000', label: __('3 seconds', 'prorank-seo') },
                { value: '5000', label: __('5 seconds', 'prorank-seo') },
              ]}
            />
          </div>

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

          {/* Content Thresholds Section */}
          <div className="pr:space-y-4">
            <h4 className="pr:text-base pr:font-semibold pr:text-gray-900">
              {__('Content Thresholds', 'prorank-seo')}
            </h4>

            <div className="pr:space-y-2">
              <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                {__('Target Readability Score', 'prorank-seo')}
              </label>
              <input
                type="range"
                min="30"
                max="90"
                step="5"
                value={settings.target_readability_score}
                onChange={(e) => updateSetting('target_readability_score', parseInt(e.target.value))}
                className="pr:w-full pr:h-2 pr:bg-gray-200 pr:rounded-lg pr:appearance-none pr:cursor-pointer"
              />
              <div className="pr:flex pr:justify-between pr:text-xs pr:text-gray-500">
                <span>{__('30 (Difficult)', 'prorank-seo')}</span>
                <span className="pr:font-medium pr:text-primary-600">{settings.target_readability_score}</span>
                <span>{__('90 (Very Easy)', 'prorank-seo')}</span>
              </div>
              <p className="pr:text-xs pr:text-gray-500">
                {__('Minimum Flesch reading ease score for good readability', 'prorank-seo')}
              </p>
            </div>

            <div className="pr:space-y-2">
              <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                {__('Minimum Content Length', 'prorank-seo')}
              </label>
              <input
                type="range"
                min="100"
                max="1000"
                step="50"
                value={settings.min_content_length}
                onChange={(e) => updateSetting('min_content_length', parseInt(e.target.value))}
                className="pr:w-full pr:h-2 pr:bg-gray-200 pr:rounded-lg pr:appearance-none pr:cursor-pointer"
              />
              <div className="pr:flex pr:justify-between pr:text-xs pr:text-gray-500">
                <span>{__('100 words', 'prorank-seo')}</span>
                <span className="pr:font-medium pr:text-primary-600">{settings.min_content_length}</span>
                <span>{__('1000 words', 'prorank-seo')}</span>
              </div>
              <p className="pr:text-xs pr:text-gray-500">
                {__('Minimum word count before showing analysis', 'prorank-seo')}
              </p>
            </div>
          </div>

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

          {/* Task 5 — Custom field inclusion */}
          <div className="pr:space-y-4">
            <h4 className="pr:text-base pr:font-semibold pr:text-gray-900">
              {__('Custom Field Content', 'prorank-seo')}
            </h4>

            <Toggle
              label={__('Include custom fields in content analysis', 'prorank-seo')}
              description={__('When on, visible text stored in post meta and ACF fields is added to the analyzed content. Off by default.', 'prorank-seo')}
              checked={!!settings.include_custom_fields_in_analysis}
              onChange={(value) => updateSetting('include_custom_fields_in_analysis', !!value)}
            />

            {settings.include_custom_fields_in_analysis && (
              <>
                <Toggle
                  label={__('Include ACF text fields when available', 'prorank-seo')}
                  description={__('Adds text-shaped ACF fields (text, textarea, wysiwyg, select labels). Image/file/gallery/repeater fields are skipped.', 'prorank-seo')}
                  checked={!!settings.include_acf_fields_in_analysis}
                  onChange={(value) => updateSetting('include_acf_fields_in_analysis', !!value)}
                />

                <div className="pr:space-y-2">
                  <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                    {__('Custom field allowlist (optional)', 'prorank-seo')}
                  </label>
                  <textarea
                    rows={4}
                    className="pr:w-full pr:font-mono pr:text-xs pr:p-3 pr:border pr:border-gray-300 pr:rounded-xs"
                    placeholder={__('hero_subtitle\nbody_text\nsubheading', 'prorank-seo')}
                    value={Array.isArray(settings.custom_field_allowlist)
                      ? settings.custom_field_allowlist.join('\n')
                      : (settings.custom_field_allowlist || '')}
                    onChange={(event) => {
                      const lines = event.target.value
                        .split(/\r?\n|,/)
                        .map((s) => s.trim())
                        .filter((s) => s.length > 0);
                      updateSetting('custom_field_allowlist', lines);
                    }}
                  />
                  <p className="pr:text-xs pr:text-gray-500">
                    {__('One meta key per line. Protected keys (starting with "_") are only included if listed here. Leave empty to include all non-protected meta.', 'prorank-seo')}
                  </p>
                </div>
              </>
            )}
          </div>

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

          {/* Task 7 — Inclusive language analysis */}
          <div className="pr:space-y-4">
            <h4 className="pr:text-base pr:font-semibold pr:text-gray-900">
              {__('Inclusive Language', 'prorank-seo')}
            </h4>

            <Toggle
              label={__('Enable inclusive language analysis', 'prorank-seo')}
              description={__('Flag a curated set of non-inclusive terms in the content analysis panel. No content is rewritten and publishing is never blocked.', 'prorank-seo')}
              checked={!!settings.enable_inclusive_language_analysis}
              onChange={(value) => updateSetting('enable_inclusive_language_analysis', !!value)}
            />

            {settings.enable_inclusive_language_analysis && (
              <div className="pr:space-y-2">
                <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                  {__('Ignored terms (optional)', 'prorank-seo')}
                </label>
                <textarea
                  rows={4}
                  className="pr:w-full pr:font-mono pr:text-xs pr:p-3 pr:border pr:border-gray-300 pr:rounded-xs"
                  placeholder={__('blacklist\nwhitelist', 'prorank-seo')}
                  value={Array.isArray(settings.ignored_inclusive_language_terms)
                    ? settings.ignored_inclusive_language_terms.join('\n')
                    : (settings.ignored_inclusive_language_terms || '')}
                  onChange={(event) => {
                    const lines = event.target.value
                      .split(/\r?\n|,/)
                      .map((s) => s.trim())
                      .filter((s) => s.length > 0);
                    updateSetting('ignored_inclusive_language_terms', lines);
                  }}
                />
                <p className="pr:text-xs pr:text-gray-500">
                  {__('One term per line. Listed terms will never be flagged on this site.', 'prorank-seo')}
                </p>
              </div>
            )}
          </div>

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

          {/* Task 8 — Prominent words / topical authority */}
          <div className="pr:space-y-4">
            <h4 className="pr:text-base pr:font-semibold pr:text-gray-900">
              {__('Prominent Words', 'prorank-seo')}
            </h4>

            <Toggle
              label={__('Enable prominent-words index', 'prorank-seo')}
              description={__('Extracts and stores the top meaningful terms per post (title + body). Used by the editor panel and future internal-link suggestions. Read-only — never rewrites your content.', 'prorank-seo')}
              checked={!!settings.enable_prominent_words}
              onChange={(value) => updateSetting('enable_prominent_words', !!value)}
            />

            {settings.enable_prominent_words && (
              <>
                <div className="pr:space-y-2">
                  <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                    {__('Max stored terms per post', 'prorank-seo')}
                  </label>
                  <input
                    type="range"
                    min="5"
                    max="50"
                    step="1"
                    value={settings.prominent_words_max_terms}
                    onChange={(e) => updateSetting('prominent_words_max_terms', parseInt(e.target.value, 10))}
                    className="pr:w-full pr:h-2 pr:bg-gray-200 pr:rounded-lg pr:appearance-none pr:cursor-pointer"
                  />
                  <div className="pr:flex pr:justify-between pr:text-xs pr:text-gray-500">
                    <span>{__('5', 'prorank-seo')}</span>
                    <span className="pr:font-medium pr:text-primary-600">{settings.prominent_words_max_terms}</span>
                    <span>{__('50', 'prorank-seo')}</span>
                  </div>
                </div>

                <div className="pr:space-y-2">
                  <label className="pr:block pr:text-sm pr:font-medium pr:text-gray-700">
                    {__('Custom ignored terms (optional)', 'prorank-seo')}
                  </label>
                  <textarea
                    rows={4}
                    className="pr:w-full pr:font-mono pr:text-xs pr:p-3 pr:border pr:border-gray-300 pr:rounded-xs"
                    placeholder={__('brand-name\ntagline', 'prorank-seo')}
                    value={Array.isArray(settings.prominent_words_ignored_terms)
                      ? settings.prominent_words_ignored_terms.join('\n')
                      : (settings.prominent_words_ignored_terms || '')}
                    onChange={(event) => {
                      const lines = event.target.value
                        .split(/\r?\n|,/)
                        .map((s) => s.trim())
                        .filter((s) => s.length > 0);
                      updateSetting('prominent_words_ignored_terms', lines);
                    }}
                  />
                  <p className="pr:text-xs pr:text-gray-500">
                    {__('One term per line. Listed terms are never included in the index.', 'prorank-seo')}
                  </p>
                </div>
              </>
            )}
          </div>

          {/* Save Button */}
          <div className="pr:flex pr:items-center pr:gap-3 pr:pt-4">
            <Button
              variant="primary"
              onClick={saveSettings}
              loading={isSaving}
              disabled={isSaving}
            >
              {isSaving ? __('Saving...', 'prorank-seo') : __('Save Settings', 'prorank-seo')}
            </Button>
            {hasSaved && (
              <span className="pr:flex pr:items-center pr:gap-2 pr:text-sm pr:text-success-600">
                <CheckIcon className="pr:w-5 pr:h-5" />
                {__('Settings saved successfully', 'prorank-seo')}
              </span>
            )}
          </div>
        </div>
      </Card>

      {/* Help Section */}
      <Card>
        <div className="pr:p-6">
          <h3 className="pr:text-base pr:font-semibold pr:text-gray-900 pr:mb-2">
            {__('Need Help?', 'prorank-seo')}
          </h3>
          <p className="pr:text-sm pr:text-gray-600 pr:mb-4">
            {__('Learn more about using content analysis features in the editor', 'prorank-seo')}
          </p>
          <Button
            variant="secondary"
            onClick={() => window.open('https://prorank.io/docs/ai-tools/', '_blank')}
          >
            {__('View Documentation', 'prorank-seo')}
          </Button>
        </div>
      </Card>
    </div>
  );
};

export default ContentAnalysisSettings;
